Pytest自动化框架之权威教程16-经典xUnit风格的setup/teardown

经典xUnit风格的setup/teardown

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

注意

虽然这些setup/teardown方法对于来自aunittest或nose的人来说简单且熟悉,但background你也可以考虑使用pytest更强大的[Fixture机制利用依赖注入的概念,允许更模块化和更可扩展的方法来管理测试状态,特别是对于大型项目和函数测试。你可以在同一文件中混合两种Fixture机制,但unittest.TestCase子类的测试用例不能接收Fixture参数。

模块级别setup/teardown

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

Copydefsetup_module(module):
    """ setup any state specific to the execution of the given module."""defteardown_module(module):
    """ teardown any state that was previously setup with a setup_module
 method.
 """

从pytest-3.0开始,module参数是可选的。

类级别setup/teardown

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

Copy@classmethoddefsetup_class(cls):
    """ setup any state specific to the execution of the given class (which
 usually contains tests).
 """@classmethoddefteardown_class(cls):
    """ teardown any state that was previously setup with a call to
 setup_class.
 """

方法和函数级别setup/teardown

同样,围绕每个方法调用调用以下方法:

Copydefsetup_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.
 """defteardown_method(self,method):
    """ teardown any state that was previously setup with a setup_method
 call.
 """

从pytest-3.0开始,method参数是可选的。

如果你希望直接在模块级别定义测试函数,还可以使用以下函数来实现fixture:

Copydefsetup_function(function):
    """ setup any state tied to the execution of the given function.
 Invoked for every test function in the module.
 """defteardown_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方法的适当范围规则。

实战案例

光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。

如果对你有帮助的话,点个赞收个藏,给作者一个鼓励。也方便你下次能够快速查找。

如有不懂还要咨询下方小卡片,博主也希望和志同道合的测试人员一起学习进步

在适当的年龄,选择适当的岗位,尽量去发挥好自己的优势。

我的自动化测试开发之路,一路走来都离不每个阶段的计划,因为自己喜欢规划和总结,

测试开发视频教程、学习笔记领取传送门!!!

猜你喜欢

转载自blog.csdn.net/m0_59868866/article/details/129653171
今日推荐