Having a common setup function for tests

195 Views Asked by At

So I have a script test.py

from nose.tools import with_setup

class Test:
    @with_setup(setup_func, teardown_func)
    def test(self):
        print "Hello World"

Can I have setup_func() and teardown_func() defined in an init.py in the same directory as "test.py".

Basically, the objective is to have a common setup and teardown for a bunch of test cases.

1

There are 1 best solutions below

2
On

There is nothing magical about setup_func and teardown_func. You can certainly do that by importing them from any module, if it called init.py or __init__. I would suggest you put it in some other module, say test_setup.py because you may not want to have those definitions at the package level of the test module, and "explicit is better than implicit" philosophy will be enforced.

ADDED: However, you have a bigger problem here: with_setup is useful only for test functions, not for test methods or inside of subclasses. As written, in your code, your setup function will not be called regardless where it is specified, see here.

If you intend to make your tests as class methods, you would have to rely on setUp and tearDown methods of the unittest. If you wish, you can inherit your test class from a special setup class and reuse this same special class again for different tests.