Setup and teardown functions executed once for all nosetests tests

2.2k views Asked by At

How to execute setup and teardown functions once for all nosetests tests?

def common_setup():
    #time consuming code
    pass

def common_teardown():
    #tidy up
    pass

def test_1():
    pass

def test_2():
    pass

#desired behavior
common_setup()
test_1()
test_2()
common_teardown()

Note that there exists a similar question with an answer that is not working with python 2.7.9-1, python-unittest2 0.5.1-1 and python-nose 1.3.6-1 after replacing the dots with pass and adding the line import unittest. Unfortunately my reputation is too low to comment on that.

1

There are 1 answers

2
Oleksiy On BEST ANSWER

You can have a module level setup function. According to nose documentation:

Test modules offer module-level setup and teardown; define the method setup, setup_module, setUp or setUpModule for setup, teardown, teardown_module, or tearDownModule for teardown.

So, more specifically, for your case:

def setup_module():
    print "common_setup"

def teardown_module():
    print "common_teardown"

def test_1():
    print "test_1"

def test_2():
    print "test_2"

Running test gives you:

$ nosetests common_setup_test.py -s -v
common_setup
common_setup_test.test_1 ... test_1
ok
common_setup_test.test_2 ... test_2
ok
common_teardown

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

It does not matter which name you choose, so both setup and setup_module would work the same, but setup_module has more clarity to it.