SetUpModule, tearDownModule and import may be out of order under the nose

I have several Python utilities that I open and work with my nose. I have observed some strange sequences of setUpModule (), tearDownModule () and import of test modules. I have this structure (example):

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

This is what I would expect / wish. When I run nosetests -s test1.py test_dir (using test detection to find test2.py), I see the following sequence:

  • import test1
  • import test2
  • setUp test1
  • running test1.test1
  • setUp test2
  • running test2.test1
  • tearDown test2
  • tearDown test1

Note that tearDown for test1 performs AFTER testing test2. This means that the system is not in a clean state when starting test2! Obviously, this can be a problem in the production environment of thousands of tests discovered from a large directory tree.

What? I do not understand something? Is there a way to ensure that tearDownModule starts after each test module?

+7
source share
1 answer

Since your test2.py file is under the same module as test1.py , the setUpModule and tearDownModule from test1.py apply to test2.py .

I would just use setUpClass and tearDownClass and put them in my test class. This way you will see that setUp and tearDown are bound to each class separately.

+1
source

All Articles