4

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.

Sebastian Kreft
  • 7,819
  • 3
  • 24
  • 41
adi ohaion
  • 374
  • 6
  • 21

1 Answers1

4

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
Bakuriu
  • 98,325
  • 22
  • 197
  • 231
  • Hi, thanks for the answer, but this is more work than just copy the function. can't I just tell nosetests which setup function to run each time before each test? – adi ohaion Sep 16 '12 at 07:04
  • How can it be more work? Copying the function would require at least 3-4 lines of code per each test, this solution requires only 1 more line per test. How are your tests organized? They are inside `TestCase`s or they are just functions? – Bakuriu Sep 16 '12 at 07:53
  • they are inside testcase. but I already have a lot test files in the project, and till now was testing using gaeunit. I want to use nosetest but I want my db stub to be initialize before each test. maybe now im explaning myself better. gaeunit was taking care of this by itself, clearing the db before each test. now I want nose to do the same thing, can I make it happen? couldn't find solution in the internet till now. – adi ohaion Sep 16 '12 at 08:04
  • I don't think there is this option. You have package/module/class and test level fixtures, but there is no such thing as a "global fixture". Anyway you can exploit my solution. Create the setup and a decorator and then apply it to all the testcases. I'm updating now my answer. – Bakuriu Sep 16 '12 at 08:39
  • The solution is greate, but I have to explicitly call `my_setup` inside the test classes to trigger setup stuff. Putting only the decorator does not call `my_setup`. What I did was calling `my_setup` from `setUp(self)` inside test classes. – Caco May 19 '17 at 18:19