I have some Python unittests that I am discovering and running with nose. I've observed some strange sequencing of the setUpModule(), tearDownModule() and imports of test modules. I have this (example) directory structure:
test1.py
test_dir/test2.py
Both test1.py and test2.py look like this:
import sys
import unittest
def flushwrite(text):
sys.stdout.write(text + '\n')
sys.stdout.flush()
flushwrite("import %s" % __name__)
def setUpModule():
flushwrite("setUp %s" % __name__)
def tearDownModule():
flushwrite("tearDown %s" % __name__)
class Test(unittest.TestCase):
def test1(self):
flushwrite("running %s.test1" % __name__)
When I run nosetests -s test1.py test_dir/test2.py
, I see this sequence:
- import test1
- import test2
- setUp test1
- running test1.test1
- tearDown test1
- setUp test2
- running test2.test1
- tearDown test2
Which is what I'd expect/desire. When I run nosetests -s test1.py test_dir
(using test discovery to find test2.py), I see this sequence:
- import test1
- import test2
- setUp test1
- running test1.test1
- setUp test2
- running test2.test1
- tearDown test2
- tearDown test1
Note that tearDown for test1 executes AFTER test2's tests. This means that the system is not in a clean state when test2 runs! Obviously, this can be a problem in a production environment of thousands of tests discovered from a large directory tree.
What's up? Am I misunderstanding something? Is there a way to ensure that tearDownModule gets run after each test module?