18

Is there any runtime-logic difference between these two methods? Or any behviour differences?
If not, then should I forget about __init__ and use only setUpClass thinking here about unittests classes like about namespaces instead of language OOP paradigm?

1 Answer 1

23

The two are quite different.

setUpClass is a class method, for one, so it'll only let you set class attributes.

They are also called at different times. The test runner creates a new instance for every test. If your test class contains 5 test methods, 5 instances are created and __init__ is called 5 times.

setUpClass is normally called only once. (If you shuffle up test ordering and test methods from different classes are intermingled, setUpClass can be called multiple times, use tearDownClass to clean up properly and that won't be a problem).

Also, a test runner usually creates all test instances at the start of the test run; this is normally cheap, as test instances don't hold (much) state so won't take up much memory.

As a rule of thumb, you should not use __init__ at all. Use setUpClass to create state shared between all the tests, and use setUp to create per-test state. setUp is called just before a test is run, so you can avoid building up a lot of memory-intensive state until it is needed for a test, and not before.

Sign up to request clarification or add additional context in comments.

4 Comments

Are there any hooks to run code when the unittests start running? Like a module-level hook? I'm looking to load some expensive data and am getting warnings about calling multiprocessing outside main after Py3 upgrade, but I'd rather not delay until setUpClass is called.
I also read that this particular warning shouldn't actually crop up on Unix systems at all due to the support for fork (which doesn't require calling the module with a different name), but it is showing on OSX. Curious if you have any insights on this Martijn?
@DylanYoung you can always use unittest.main() to control when tests start. Or use the setUpModule() and tearDownModule() hooks.
Thanks Martijn! setUpModule and tearDownModule did the task admirably. Don't know how I missed those.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.