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

安稳与你 提交于 2019-12-23 22:50:00

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/12427734/how-can-i-define-one-setup-function-for-all-nosetests-tests

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!