Testing Workers and Queues

xuanbao · · 432 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>How does one test a worker, collector, queue, etc? I have code that&#39;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&#39;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&#39;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&#39;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() &lt;-chan string, starter func(string) error) { jobs := validator() for i := range workers { select { case &lt;-ctx.Done(): return case j := &lt;- 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&#39;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

432 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传