Pytest系列-测试用例前后置固件setup和teardown的介绍和使用(2)

简介

在unittest框架中,有两个前置方法,两个后置方法,还有两个模块方法,分别是

  • setup():每个用例执行之前都会自动调用
  • setupClass():在类中所有的测试方法执行前会自动执行的代码,只执行一次
  • teardown():每个用例执行之后都会自动调用
  • teardownClass():在类中所有的测试方法执行后会自动执行的代码,只执行一次

在类外部定义函数

  • setUpModule():模块级别在这个代码文件执行前执行一次
  • tearDownModule():模块级别在这个代码文件执行后执行一次

对于强大的pytest测试框架,给我们提供了10中类似方法:

  • 模块级别:setup_module、teardown_module
  • 函数级别:setup_function、teardown_function
  • 类级别:setup_class、teardown_class
  • 类方法级别:setup_method、teardown_method
  • 函数和方法级别:setup、teardown

Pytest中前后置固件的讲解及使用

模块级别:setup_module、teardown_module

说明 :该方法表示只能类外面执行用例过程中,只执行1次。相当于unittest中的setupclass和teardownclass方法

函数级别:setup_function、teardown_function

说明 :该方法表示在类外面执行用例过程中,每次都会执行前置和后置。

类级别:setup_class、teardown_class

说明 :该方法表示在类中执行测试用例前,只执行1次测试前置和测试后置,注意:放在类外面不生效

方法级别:setup_method、teardown_method

说明 :该方法表示在类中每次执行测试用例前,测试前置和测试后置都会执行一次,注意:放在类外面不生效

函数和方法级别:setup、teardown

说明 :该方法这个可以在类中使用,也可以在类外进行使用,大家最熟悉

多个方法组合使用

说明 :直接查看示例,查看各个方法执行优先级,非常重要

示例如下:

python 复制代码
import pytest

def setup_module():
    print("setup_module 类外前置方法")

def teardown_module():
    print("teatrdown_module 类外后置方法")

def setup_function():
    print("setup_function 类外前置方法")

def teardowm_function():
    print("teardown_function 类外后置方法")

def demo_01():
    print("类外面demo1")

def test_02():
    print("类外面demo2")

class TestDemo:
    def setup_class(self):
        print("--整个测试类开始前只执行一次setup_class---")

    def teardown_class(self):
        print("--整个测试类结束后只执行一次teardown_class--")

    def setup_method(self):
        print("--类里面每个用例执行前都会执行setup_method--")

    def teardown_method(self):
        print("--类里面每个用例结束后都会执行teardown_method--")

    def setup(self):
        print("-类里面每个用例执行前都会执行setup-")

    def teardown(self):
        print("-类里面每个用例结束后都会执行teardown-")

    def test_01(self):
        print("类里面test1")

    def test_02(self):
        print("类里面test2")

if __name__ == '__main__':
    pytest.main(["-q", "-s", "-ra", "setup_teardown.py"])

结果

优先级为

setup_module>setup_function>setup>用例>teardown>teardown_function>teardown_module

setup_module>setup_class>setup_method>setup>用例>teardown>teardown_method>teardown_class>teardown_module

相关推荐
程序员小远21 小时前
软件测试之压力测试详解
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·压力测试
ThreeAu.3 天前
pytest 实战:用例管理、插件技巧、断言详解
python·单元测试·pytest·测试开发工程师
我的xiaodoujiao3 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 18--测试框架Pytest基础 2--插件和参数化
python·学习·测试工具·pytest
小小测试开发3 天前
pytest 库用法示例:Python 测试框架的高效实践
开发语言·python·pytest
know__ledge4 天前
Pytest+requests进行接口自动化测试8.0(Allure进阶 + 文件上传接口 + 单接口多用例)
pytest
测试老哥4 天前
测试用例之正交试验法、功能图法
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
川石课堂软件测试4 天前
CSS中常用的几种定位。
开发语言·css·python·网络协议·http·html·pytest
啊森要自信5 天前
【GUI自动化测试】Python 自动化测试框架 pytest 全面指南:基础语法、核心特性(参数化 / Fixture)及项目实操
开发语言·python·ui·单元测试·pytest
啊森要自信6 天前
【GUI自动化测试】YAML 配置文件应用:从语法解析到 Python 读写
android·python·缓存·pytest·pip·dash