登录
首页 >  Golang >  Go问答

在 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学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>