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

相关推荐
测试19985 小时前
Jmeter性能压测:TPS与QPS
自动化测试·软件测试·python·jmeter·测试用例·压力测试·性能测试
我的xiaodoujiao6 小时前
API 接口自动化测试详细图文教程学习系列25--继续处理testCase中的数据
python·学习·测试工具·pytest
孙高飞11 小时前
从0开始学AI测试系列-工具篇
人工智能·自动化·测试用例
人形贴片机1 天前
低温车间防静电桌垫:低温环境真的会影响电阻测试仪测量吗?
测试用例
xiaobai1781 天前
pytest+playwright实现UI自动化(4)-上夹具fixture
ui·自动化·pytest·playwright
弹简特1 天前
【接口自动化】02-Pytest固件fixture核心机制与Allure企业级报告实战
自动化·pytest·测试
弹简特3 天前
【接口自动化】01-pytest详解、pytest执行逻辑、pytest参数、配置文件和pytest标记
自动化·pytest
香辣西红柿炒蛋3 天前
pytest框架介绍
python·pytest
kft13144 天前
04 — AI 测试用例生成与评审实战
人工智能·测试用例