如何实现 xunit 风格的 setup

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

注意

虽然这些 setup/teardown 方法对于有 unittestnose 背景的用户来说简单且熟悉,但您也可以考虑使用 pytest 更强大的 fixture 机制,该机制利用了依赖注入的概念,为管理测试状态提供了更模块化和更具可伸缩性的方法,尤其适用于大型项目和功能测试。您可以在同一个文件中混合使用这两种 fixture 机制,但 unittest.TestCase 子类的测试方法不能接收 fixture 参数。

模块级 setup/teardown

如果单个模块中有多个测试函数和测试类,您可以选择实现以下 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 参数是可选的。

类级 setup/teardown

同样,以下方法在调用类的所有测试方法之前和之后在类级别被调用

@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.
    """

方法和函数级 setup/teardown

同样,以下方法在每次方法调用前后被调用

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 参数是可选的。

备注

  • setup/teardown 对可能在每个测试过程中被多次调用。

  • 如果相应的 setup 函数存在且失败/被跳过,则不会调用 teardown 函数。

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

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