且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何为所有鼻子测试测试定义一个设置功能?

更新时间:2023-11-20 22:52:22

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

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

如果要对多个测试用例使用相同的设置,则可以使用类似的方法. 首先创建设置功能,然后使用装饰器将其应用于所有TestCases:

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