How best to initialize in unit tests?

Paul Moore p.f.moore at gmail.com
Wed Oct 4 09:54:53 EDT 2017


I've not had this problem myself, but py.test has the idea of "autouse
fixtures" which would work for this situation. Define your setup call
in a function, declare it with the pytest.fixture decorator with
autouse=True, and it'll be run before every test. The declaration goes
in a conftest.py file alongside your test files.

I don't know if unittest or doctest has anything similar, but I
suspect not (or at least not something as simple). Whether you're
comfortable with the level of magic behaviour pytest has is probably
something you'll have to decide for yourself (although I believe it
does discover unittest and doctest tests, so you don't need to change
all your tests over).

There's an example of an autouse fixture in pip's test suite, although
it's massively more complex than what you're describing, so don't be
put off by the size of it :-)

Paul

On 4 October 2017 at 14:07, 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



More information about the Python-list mailing list