adi ohaion
adi ohaion

Reputation: 374

How can I define one setup function for all nosetests tests?

I'm using google app engine with python and want to run some tests using nosetest. I want each test to run the same setup function. I have already a lot of tests, so I don't want to go through them all and copy&paste the same function. can I define somewhere one setup function and each test would run it first?

thanks.

Upvotes: 4

Views: 2885

Answers (1)

Bakuriu
Bakuriu

Reputation: 101969

You can write your setup function and apply it using the with_setup decorator:

from nose.tools import with_setup


def my_setup():
   ...


@with_setup(my_setup)
def test_one():
    ...


@with_setup(my_setup)
def test_two():
    ...

If you want to use the same setup for several test-cases you can use a similar method. First you create the setup function, then you apply it to all the TestCases with a decorator:

def my_setup(self):
    #do the setup for the test-case

def apply_setup(setup_func):
    def wrap(cls):
        cls.setup = setup_func
        return cls
    return wrap


@apply_setup(my_setup)
class MyTestCaseOne(unittest.TestCase):
    def test_one(self):
        ...
    def test_two(self):
        ...


@apply_setup(my_setup)
class MyTestCaseTwo(unittest.TestCase):
    def test_one(self):
        ...

Or another way could be to simply assign your setup:

class MyTestCaseOne(unittest.TestCase):
    setup = my_setup

Upvotes: 4

Related Questions