How do I find out if the current test is the last to be run?

152 Views Asked by At

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().

2

There are 2 best solutions below

4
Eugene Yarmash On

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.

1
simone cittadini On

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"