如何实现xunit风格的设置

本节介绍了一种经典且流行的方法,您可以通过它在模块/类/函数级别实现fixture(设置和拆卸测试状态)。

注意

虽然这些设置/拆卸方法对于那些具有 unittestnose 背景的人来说简单而熟悉,但您也可以考虑使用pytest更强大的 fixture机制,它利用了依赖注入的概念,为管理测试状态提供了一种更模块化和更具可扩展性的方法,特别是对于大型项目和功能测试。您可以在同一个文件中混合使用两种fixture机制,但 unittest.TestCase 子类的测试方法不能接收fixture参数。

模块级别的设置/拆卸

如果您在一个模块中有多个测试函数和测试类,您可以选择实现以下fixture方法,这些方法通常会为所有函数调用一次

def setup_module(module):
    """setup any state specific to the execution of the given module."""


def teardown_module(module):
    """teardown any state that was previously setup with a setup_module
    method.
    """

自pytest-3.0起,module 参数是可选的。

类级别的设置/拆卸

类似地,在调用类的所有测试方法之前和之后,会调用以下方法

@classmethod
def setup_class(cls):
    """setup any state specific to the execution of the given class (which
    usually contains tests).
    """


@classmethod
def teardown_class(cls):
    """teardown any state that was previously setup with a call to
    setup_class.
    """

方法和函数级别的设置/拆卸

类似地,在每次方法调用前后,会调用以下方法

def setup_method(self, method):
    """setup any state tied to the execution of the given method in a
    class.  setup_method is invoked for every test method of a class.
    """


def teardown_method(self, method):
    """teardown any state that was previously setup with a setup_method
    call.
    """

自pytest-3.0起,method 参数是可选的。

如果您更喜欢直接在模块级别定义测试函数,您也可以使用以下函数来实现fixture

def setup_function(function):
    """setup any state tied to the execution of the given function.
    Invoked for every test function in the module.
    """


def teardown_function(function):
    """teardown any state that was previously setup with a setup_function
    call.
    """

自pytest-3.0起,function 参数是可选的。

备注

  • 设置/拆卸对可能会在每个测试过程中多次调用。

  • 如果相应的设置函数存在并失败/被跳过,则不会调用拆卸函数。

  • 在pytest-4.2之前,xunit风格的函数不遵循fixture的作用域规则,因此,例如,setup_method 可能会在一个会话作用域的自动使用fixture之前被调用。

    现在xunit风格的函数已与fixture机制集成,并遵循调用中涉及的fixture的正确作用域规则。