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:
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:
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?
Since your test2.py
file is under the same module as test1.py
, the setUpModule
and tearDownModule
methods from test1.py
both apply to test2.py
.
I'd just use setUpClass
and tearDownClass
and place them inside your Test class. This way you will make sure that the setUp and tearDown are tied to each class separately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With