Art of Unit Testing

Peter Hansen peter at engcorp.com
Tue Aug 2 23:18:51 CEST 2005


Christoph Zwerschke wrote:
> I completely agree and I think it makes a lot of sense that unittest 
> calls setUp and tearDown for every single test. However, the fact that 
> this is *generally* the best way doesn't exclude the fact that there are 
> *exceptions* when it makes sense to setUp and tearDown not for every 
> test, e.g. when it is absolutely sure that the fixture cannot be 
> destroyed by the individual tests or when creating the fixture takes too 
> much time. I already gave the example of creating database connections 
> or even creating/importing whole databases. My question was, how do I 
> handle these cases with the standard lib unittest?

What's wrong with using Python's existing "global" support, and just 
having your test case setUp() call a global setup routine which checks 
whether that global setup work has already been done and, if not, does 
it once and sets a flag to say that it has now been done?  I've done 
this easily in the few cases where I've wanted this behaviour.  It 
doesn't seem complex enough to warrant adding to the standard unit test 
support.

> According to the "extreme programming" paradigm, testing should be done 
> several times a day. So a requirement for extreme programm is that tests 
> are fast enough. If the testing needs too much time, people are 
> discouraged to test often.

If you're going to quote XP rules of thumb, the tests should be 
independent and very fast, and if you have a setup code that is taking a 
long time, it's likely a "code smell" of some kind, and you should be 
fixing the design which prevents you writing these tests with minimal 
and quick setup.  Are these really like "acceptance" tests?  If they 
were unit tests, they should take only a few minutes to run, total, and 
you should be running them all *many* times a day, not twice.

Still, if you're stuck, and really do need a lengthy setup to execute 
once as an optimization, it's not hard to do with globals.

-Peter



More information about the Python-list mailing list