How best to initialize in unit tests?

Christopher Reimer christopher_reimer at icloud.com
Wed Oct 4 09:27:19 EDT 2017


On Oct 4, 2017, at 6:07 AM, Skip Montanaro <skip.montanaro at gmail.com> wrote:
> 
> 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
> -- 
> https://mail.python.org/mailman/listinfo/python-list

Seems like you’re overthinking this. You should be able to unit test any part of your code in isolation. If not, you need to refactor your code. I generally don’t use test classes in pytest.

Chris R. 


More information about the Python-list mailing list