在 Golang 中测试一次条件
来源:stackoverflow
时间:2024-04-11 19:00:33 452浏览 收藏
编程并不是一个机械性的工作,而是需要有思考,有创新的工作,语法是固定的,但解决问题的思路则是依靠人的思维,这就需要我们坚持学习和更新自己的知识。今天golang学习网就整理分享《在 Golang 中测试一次条件》,文章讲解的知识点主要包括,如果你对Golang方面的知识点感兴趣,就不要错过golang学习网,在这可以对大家的知识积累有所帮助,助力开发能力的提升。
我有一个模块,它依赖于通过调用外部服务来填充缓存,如下所示:
func (provider *cache) getitem(productid string, skuid string, itemtype string) (*item, error) { // first, create the key we'll use to uniquely identify the item key := fmt.sprintf("%s:%s", productid, skuid) // now, attempt to get the concurrency control associated with the item key // if we couldn't find it then create one and add it to the map var once *sync.once if entry, ok := provider.lockmap.load(key); ok { once = entry.(*sync.once) } else { once = &sync.once{} provider.lockmap.store(key, once) } // now, use the concurrency control to attempt to request the item // but only once. channel any errors that occur cerr := make(chan error, 1) once.do(func() { // we didn't find the item in the cache so we'll have to get it from the partner-center item, err := provider.client.getitem(productid, skuid) if err != nil { cerr <- err return } // add the item to the cache provider.cache.store(key, &item) }) // attempt to read an error from the channel; if we get one then return it // otherwise, pull the item out of the cache. we have to use the select here because this is // the only way to attempt to read from a channel without it blocking var sku interface{} select { case err, ok := <-cerr: if ok { return nil, err } default: item, _ = provider.cache.load(key) } // now, pull out a reference to the item and return it return item.(*item), nil }
这个方法正如我所期望的那样工作。我的问题是测试;专门进行测试以确保对于给定的键值仅调用 getitem
方法一次。我的测试代码如下:
var _ = Describe("Item Tests", func() { It("GetItem - Not cached, two concurrent requests - Client called once", func() { // setup cache // Setup a wait group so we can ensure both processes finish var wg sync.WaitGroup wg.Add(2) // Fire off two concurrent requests for the same SKU go runRequest(&wg, cache) go runRequest(&wg, cache) wg.Wait() // Check the cache; it should have one value _, ok := cache.cache.Load("PID:SKUID") Expect(ok).Should(BeTrue()) // The client should have only been requested once Expect(client.RequestCount).Should(Equal(1)) // FAILS HERE }) }) // Used for testing concurrency func runRequest(wg *sync.WaitGroup, cache *SkuCache) { defer wg.Done() sku, err := cache.GetItem("PID", "SKUID", "fakeitem") Expect(err).ShouldNot(HaveOccurred()) } type mockClient struct { RequestFails bool RequestCount int lock sync.Mutex } func NewMockClient(requestFails bool) *mockClient { return &mockClient{ RequestFails: requestFails, RequestCount: 0, lock: sync.Mutex{}, } } func (client *mockClient) GetItem(productId string, skuId string) (item Item, err error) { defer GinkgoRecover() // If we want to simulate client failure then return an error here if client.RequestFails { err = fmt.Errorf("GetItem failed") return } // Sleep for 100ms so we can more accurately simulate the request latency time.Sleep(100 * time.Millisecond) // Update the request count client.lock.Lock() client.RequestCount++ client.lock.Unlock() item = Item{ Id: skuId, ProductId: productId, } return }
我一直遇到的问题是,这个测试有时会失败,因为在注释行中请求计数为 1,而预期计数为 1。此故障不一致,我不太确定如何调试此问题。任何帮助将不胜感激。
解决方案
我认为您的测试有时会失败,因为您的缓存无法保证它只获取一次项目,并且您很幸运测试发现了这一点。
如果某个item不在其中,并且2个并发goroutine同时调用cache.getitem()
,则可能会出现lockmap.load()
会在两个goroutines中报告该key不在map中,两个 goroutine 都会创建一个 sync.once
,并且都将在映射中存储自己的实例(显然只有一个——后者——会保留在映射中,但你的缓存不会检查这一点)。
然后这 2 个 goroutine 都会调用 client.getitem()
因为 2 个单独的 sync.once
不提供同步。只有使用同一个 sync.once
实例,才能保证传递给 once.do()
的函数仅执行一次。
我认为 sync.mutex
会更容易、更合适,以避免在此处创建和使用 2 个 sync.once
。
或者,由于您已经在使用 sync.map
,因此您可以使用 Map.LoadOrStore()
方法:创建 sync.once
,并将其传递给 map.loadorstore()
。如果该键已在映射中,则使用返回的 sync.once
。如果密钥不在地图中,您的 sync.once
将存储在其中,因此您可以使用它。这将确保多个并发 goroutine 不能在其中存储多个 sync.once
实例。
类似这样的事情:
var once *sync.Once if entry, loaded := provider.lockMap.LoadOrStore(key, once); loaded { // Was already in the map, use the loaded Once once = entry.(*sync.Once) }
这个解决方案仍然不完美:如果2个goroutine同时调用cache.getitem()
,只有一个goroutine会尝试从客户端获取item,但如果失败,只有这个goroutine会报告错误,另一个 goroutine 不会尝试从客户端获取项目,而是从地图加载它,并且您不检查加载是否成功。您应该这样做,如果它不在地图中,则意味着另一次并发尝试未能获取它。所以你应该报告错误(并清除 sync.once
)。
正如您所看到的,事情变得越来越复杂。我坚持我之前的建议:使用 sync.mutex
在这里会更容易。
到这里,我们也就讲完了《在 Golang 中测试一次条件》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
139 收藏
-
204 收藏
-
325 收藏
-
477 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习