Golang 测试中未生效的上下文超时
时间:2024-02-22
浏览:448
作者:佚名
学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《Golang 测试中未生效的上下文超时》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!
问题内容
我有一些正在运行的异步调用,并且我正在通过上下文为所有调用设置超时。
ctxWithTimeout, cancel := context.WithTimeout(ctx, getTimeoutDuration()) defer cancel() go func1(ctxWithTimeout, outputChan1, param1) go func2(ctxWithTimeout, outputChan2, param2) go func3(ctxWithTimeout, outputChan3) outputChan1Result := <-outputChan1 Some logic... outputChan2Result := <-outputChan2 Some logic... outputChan3Result := <-outputChan3 Some logic...
gettimeoutduration 将返回“1”(测试时为纳秒),其他情况下返回 60 秒。我确保运行测试时具有正确的值。
func1 和其他 2 个内部有一些逻辑以及我正在使用模拟的其他一些调用。
当我运行服务并通过邮递员调用执行调用时,代码有效,如果超时,我会看到正在执行正确的代码,并且在邮递员中得到正确的响应。超时可以通过以下方式识别
ctx.err() == context.deadlineexceeded
我编写了一个测试并想要达到超时。执行 3 个函数大约需要 130μs 并且代码运行时没有达到 1 纳秒超时。结果也好像我只是设法在时间限制下运行并执行所有代码。
知道为什么超时没有被触发或者如何确保它会被触发吗?
正确答案
根据您的示例,代码无法按您的预期工作。并且您应该在选择中同时等待通道和上下文截止日期。
ctxWithTimeout, cancel := context.WithTimeout(ctx, getTimeoutDuration())
go func1(ctxWithTimeout, outputChan1, param1)
go func2(ctxWithTimeout, outputChan2, param2)
go func3(ctxWithTimeout, outputChan3)
select {
case outputChan1Result := <-outputChan1:
case outputChan2Result := <-outputChan2:
case outputChan3Result := <-outputChan3:
case <-ctxWithTimeout.Done():
}
此外,您应该以某种方式等待所有结果:例如 waitgroup 或计数器
肮脏的例子:https://go.dev/play/p/-eJcjAItMMu
理论要掌握,实操不能落!以上关于《Golang 测试中未生效的上下文超时》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
