3

How can I find out from the current test if its the last to be run? (Python unittest / nosetests)

I have some specific fixture teardown to be done at the very end of the test run and it would be a lot easier if on a test by test basis I could just determine:

if last_test:
   hard_fixture_teardown()
else:
   soft_fixture_teardown()

I have a package teardown which would work perfectly but it seems very messy passing the fixture information back to the __init__.teardown_package().

Jele
  • 215
  • 1
  • 2
  • 11

2 Answers2

1

You can use a combination of TestCase.tearDown() and TestCase.tearDownClass() to achieve this. tearDown() is called for each test method while tearDownClass() is called after all tests in the class have run.

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
  • Thanks, but what if you only want to run the 'hard teardown' at the end of the whole run, which could comprise numerous test classes? – Jele Dec 15 '15 at 08:50
  • 1
    @Jele: as you can guess, there's also [`tearDownModule`](https://docs.python.org/2.7/library/unittest.html#setupmodule-and-teardownmodule). – Eugene Yarmash Dec 15 '15 at 08:55
  • eugene y, cheers. I tried that previously and couldnt seemt to get it working. Where would be the best place to put this? I have an existing setup/teardown module which work higher up in the structure, which would be a great place for 'hard teardown' but its passing the relvant fixture information back to it which felt wrong / messy. Any ideas? – Jele Dec 15 '15 at 09:00
  • 1
    @Jele: You put it on the module level. However, It looks like you need to re-organize your tests so that modules are independent of each other. – Eugene Yarmash Dec 15 '15 at 10:27
0

As stated here unit test are not meant to have an order, unit tests depending on the order are either not well conceived or just have to be merged in a monolithic one. (merging separate functions in a single test is the accepted answer )

[edit after comment]

If the order is not important you can do this (quite messy, imo we are still forcing the boundaries of how unit tests should be used)

in every test package you put:

def tearDownModule():
    xxx = int(os.getenv('XXX', '0')) + 1
    if xxx == NUMBER_OF_TEST_PACKAGES:
        print "hard tear down"
    else:
        print "not yet"
        os.environ['XXX'] = str(xxx)

with NUMBER_OF_TEST_PACKAGES imported from somewhere global.

also if the order is not important I suppose that when used the fixture is only readed and not modified, if so you can setup that as a class method

@classmethod
def setUpClass(cls):
    print "I'll take a lot of time here"
Community
  • 1
  • 1
simone cittadini
  • 358
  • 2
  • 14
  • The order of the tests is irrelevant in this case, its more reducing the time of a lengthy fixture creation and doing the necessary cleanup at the very of the test run rather than between each individual test. – Jele Dec 15 '15 at 08:55