Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setUpModule, tearDownModule and imports can be out of order under nose

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:

  1. import test1
  2. import test2
  3. setUp test1
  4. running test1.test1
  5. tearDown test1
  6. setUp test2
  7. running test2.test1
  8. 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:

  1. import test1
  2. import test2
  3. setUp test1
  4. running test1.test1
  5. setUp test2
  6. running test2.test1
  7. tearDown test2
  8. 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?

like image 701
dbn Avatar asked Jan 16 '13 20:01

dbn


1 Answers

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.

like image 158
gregor2004ua Avatar answered Sep 19 '22 04:09

gregor2004ua