【Pytest】setup和teardown的四个级别

文章目录

  • 1.setup和teardown简介
  • [2.模块级别的 setup 和 teardown](#2.模块级别的 setup 和 teardown)
  • [3.函数级别的 setup 和 teardown](#3.函数级别的 setup 和 teardown)
  • [4.方法级别的 setup 和 teardown](#4.方法级别的 setup 和 teardown)
  • [5.类级别的 setup 和 teardown](#5.类级别的 setup 和 teardown)

1.setup和teardown简介

在 pytest 中,setup 和 teardown 用于在测试用例执行前后执行一些准备和清理操作。

setup 和 teardown共有四个级别

等级 说明 范围
函数级别 setup_function 和 teardown_function 针对每个测试函数执行前和执行后进行操作。
类级别 setup_class 和 teardown_class 针对每个测试类执行前和执行后进行操作,它们必须是类的静态方法。
方法级别 setup_method 和 teardown_method 针对类中的每个测试方法执行前和执行后进行操作。
模块级别 setup_module 和 teardown_modulesetup_module 和 teardown_module 针对整个测试模块执行前和执行后进行操作。

2.模块级别的 setup 和 teardown

针对整个测试模块执行前和执行后进行操作。

示例:

python 复制代码
def setup_module(module):
    print(f"开始执行测试模块: {module.__name__}")

def teardown_module(module):
    print(f"测试模块 {module.__name__} 执行完毕")

def test_example1():
    print('执行测试用例1')
    assert 1==1

def test_example2():
    print('执行测试用例2')
    assert 2==2

运行结果:

3.函数级别的 setup 和 teardown

针对每个测试函数执行前和执行后进行操作。

示例:

python 复制代码
def setup_function(function):
    print(f"开始执行测试函数: {function.__name__}")

def teardown_function(function):
    print(f"测试函数 {function.__name__} 执行完毕")

def test_example1():
    print('执行测试用例1')
    assert 1==1

def test_example2():
    print('执行测试用例2')
    assert 2==2

运行结果:

4.方法级别的 setup 和 teardown

针对类中的每个测试方法执行前和执行后进行操作。

示例:

python 复制代码
class TestClass:
    def setup_method(self,method):
        print(f"开始执行测试方法: {method.__name__}")

    def teardown_method(self, method):
        print(f"测试方法 {method.__name__} 执行完毕")

    def test_example1(self):
        print('执行测试用例1')
        assert 1 == 1

    def test_example2(self):
        print('执行测试用例2')
        assert 2 == 2

运行结果:

5.类级别的 setup 和 teardown

针对每个测试类执行前和执行后进行操作,它们必须是类的静态方法。

示例:

python 复制代码
class TestClass:
    def setup_class(cls):
        print(f"开始执行测试类: {cls.__name__}")

    def teardown_class(cls):
        print(f"测试类 {cls.__name__} 执行完毕")

    def test_example1(self):
        print('执行测试用例1')
        assert 1 == 1

    def test_example2(self):
        print('执行测试用例2')
        assert 2 == 2

运行结果:

相关推荐
淼_@淼2 天前
pytest简介
运维·服务器·pytest
奶茶精Gaaa2 天前
【ZJ】Pytest框架搭建
pytest
趙卋傑3 天前
接口自动化测试
python·pycharm·pytest
测试界萧萧5 天前
Jenkins+Allure+Pytest的持续集成
自动化测试·软件测试·功能测试·程序人生·ci/cd·jenkins·pytest
nvd115 天前
Pytest 中使用 SQLAlchemy 进行异步数据库测试
数据库·oracle·pytest
文人sec6 天前
pytest1-接口自动化测试场景
软件测试·python·单元测试·pytest
我的xiaodoujiao7 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 25--数据驱动--参数化处理 Excel 文件 2
前端·python·学习·测试工具·ui·pytest
我的xiaodoujiao15 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 24--数据驱动--参数化处理 Excel 文件 1
python·学习·测试工具·pytest
西游音月18 天前
(2)pytest+Selenium自动化测试-环境准备
selenium·测试工具·pytest