<p>How does one test a worker, collector, queue, etc? I have code that's similar to the code in <a href="http://nesv.github.io/golang/2014/02/25/worker-queues-in-go.html" rel="nofollow">this post</a> and I'm not sure how to test it. I guess intersect the work from the channel to test the output or something, sure. I then have to worry about cancelling them, context durations, etc.</p>
<p>Is there a way to rewrite it in a testable way? All these blog posts that talk about concurrency and workers and etc don't really do anything for testing well against race conditions or anything.</p>
<p><a href="https://play.golang.org/p/pGLrmUluYo" rel="nofollow">Here's</a> a non-working play.golang of some of the code.</p>
<p>I ended up having a function that takes a function that returns channels, and takes a function to handle each request</p>
<p>So, something like this:</p>
<pre><code>func processor(validator func() <-chan string, starter func(string) error) {
jobs := validator()
for i := range workers {
select {
case <-ctx.Done():
return
case j := <- jobs:
go func(id string) {
if err := starter(id); err != nil {
// handle err
}
}(id)
}
}
}
</code></pre>
<p>Now I can test validator, I can test starter, and I can test processor with bogus validators and starters.</p>
<hr/>**评论:**<br/><br/>tgulacsi: <pre><p>Add a known number of tasks taking a known amount of time, and check whether the run time is within a threshold?</p></pre>natdm: <pre><p>I was thinking more about unit testing independent pieces of code.</p>
<p>I've changed some of it to have methods return channels, which I can range over in tests</p></pre>natdm: <pre><p>Gave my solution above.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传