4

我正在使用带有 python 的谷歌应用引擎,并希望使用nosetest 运行一些测试。我希望每个测试都运行相同的设置功能。我已经有很多测试了,所以我不想通过它们并复制和粘贴相同的功能。我可以在某个地方定义一个设置函数,并且每个测试都会先运行它吗?

谢谢。

4

1 回答 1

4

您可以编写设置函数并使用with_setup装饰器应用它:

from nose.tools import with_setup


def my_setup():
   ...


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


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

如果您想对多个测试用例使用相同的设置,您可以使用类似的方法。首先创建 setup 函数,然后使用装饰器将其应用于所有 TestCases:

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):
        ...

或者另一种方法可能是简单地分配您的设置:

class MyTestCaseOne(unittest.TestCase):
    setup = my_setup
于 2012-09-14T16:44:11.573 回答