unittest and threading

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Jan 25 02:47:56 EST 2012


On Tue, 24 Jan 2012 13:54:23 -0800, Ross Boylan wrote:

> Is it safe to use unittest with threads?

I see nobody else has answered, so I'll have a go.

I think you need to explain what you mean here in a little more detail.

If you mean, "I have a library that uses threads internally, and I want 
to test it with unittest", then the answer is almost certainly yes it is 
safe.

If you mean, "I want to write unit tests which use threads as part of the 
test", then the answer again remains almost certainly yes it is safe.

Provided, of course, that your test code is not buggy. Tests, being code, 
are not immune to bugs, and the more complex your tests, the more likely 
they contain bugs.

Lastly, if you mean, "I want to execute each unit test in a separate 
thread, so that all my tests run in parallel instead of sequentially", 
then the answer is that as far as I know the unittest framework does not 
support this.

You would have to write your own framework. You might be able to inherit 
some of the behaviour from the unittest module, but all the threading 
would be up to you. So only you will know whether it will be safe or not.

Alternatively, you could try the nose or py.test frameworks, which I 
understand already support running tests in parallel.


-- 
Steven



More information about the Python-list mailing list