Pytest权威教程-17经典xUnit风格的setup/teardown

时间:2019-09-06
本文章向大家介绍Pytest权威教程-17经典xUnit风格的setup/teardown,主要包括Pytest权威教程-17经典xUnit风格的setup/teardown使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

经典xUnit风格的setup/teardown

本节介绍了如何在每个模块/类/函数的基础上实现Fixture(setup和teardown测试状态)的经典而流行的方法。

注意

虽然这些setup/teardown方法对于来自aunittest或nose的人来说简单且熟悉,但background你也可以考虑使用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之前调用a。

    现在,xunit风格的函数与Fixture机制集成在一起,并遵守调用中涉及的Fixture方法的适当范围规则。

原文地址:https://www.cnblogs.com/superhin/p/11477948.html