How best to initialize in unit tests?

Skip Montanaro skip.montanaro at gmail.com
Wed Oct 4 09:07:44 EDT 2017


Suppose you want to test a package (in the general sense of the word,
not necessarily a Python package). You probably have specific unit
tests, maybe some doctests scattered around in doc strings. Further,
suppose that package requires you call an initialize function of some
sort. Where does that go? I know about setUp and setUpClass methods in
unittest.TestCase. Is order of execution of doctests deterministic
across modules (say, when tests are run through nosetests)?

In my case, I didn't know what order things would be called, so I
added a call to initialize() at the start of every doctest and added a
setUpClass class method to all my TestCase subclasses. Just in case.
It worked okay because my initialize function can be called multiple
times. What about situations where it can only be called once? Do you
have to define some sort of super_initialize() function for your tests
which guarantees that your initialize function is called precisely
once?

This all seems rather messy. I'm open to better ways to do this, but
as I've only had one cup of coffee this morning, no spark of insight
has zapped my frontal cortex as yet.

Thx,

Skip



More information about the Python-list mailing list