Testing a periodic worker

I came across somebody that was asking about how to test their code. They had a function that would do certain work at short intervals and then some other work after a longer period of time. They provided a simplified version of the code and it looked something like this. They had coverage for the short period work (I guess functions foo and/or bar in the simplified example had some side effect they could test for.

Interestingly enough they did know they could add more arguments to their main function to control the shorter period as well as using a function argument to capture the longer period worker. But two problems remained; they would rely on some (short) waiting in their tests and they also would prefer to know that some short period work always happened before the longer period work.

If you accept some really short waiting times (and ignore the second requirement), then you can get away with pretty short waiting times. The problem with short waiting times is that you might end up with too short waiting times and get occasional failures just because something took a little longer than usual due to load on your machine (for example lots of other tests running in parallel). But if you do go down this route you probably end up with something like this.

But I think you can do much better... I think there is an easy way to also test how the shorter and longer period work interacts without any waits in a predictable way. The trick is to not add more parameters to the existing function but rather break out the periodic worker and test that one separately. If you do that you end up with something like this.

Yes, that solution uses three different function arguments which might look scary, but since you get really fast and predictable testing I think it's worth it.

No comments:

Post a Comment