当前位置: 首页 > news >正文

【Pytest】setup和teardown的四个级别

文章目录

  • 1.setup和teardown简介
  • 2.模块级别的 setup 和 teardown
  • 3.函数级别的 setup 和 teardown
  • 4.方法级别的 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

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

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

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

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

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

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

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

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

运行结果:
在这里插入图片描述

相关文章:

  • React底层常见的设计模式
  • P9231 [蓝桥杯 2023 省 A] 平方差
  • 因子有效性的审判使者——回测分析【量化实践】
  • 多智能体博弈代码案例
  • 【西瓜书《机器学习》十至十二章内容通俗理解】
  • Starrocks 写入报错 primary key memory usage exceeds the limit
  • 【canvas】动画
  • 【原创】Open WebUI 本地部署
  • gtest 和 gmock讲解
  • 物理内存组织与分配的核心概念
  • Spring Boot 流式响应豆包大模型对话能力
  • 在ubuntu 24.04.2 通过 Kubeadm 安装 Kubernetes v1.31.6
  • 简洁的个人地址发布页HTML源码
  • conda环境管理 kernel注册到jupyter notebook
  • nginx+keepalived负载均衡及高可用
  • 算法之领域算法
  • Web-to-Web和Server-to-Serve归因方法
  • 一文弄懂TCP断开连接时候的四次挥手
  • iOS接入Flutter项目
  • HTTP~文件 MIME 类型
  • wordpress 主题制作 加入评论/太原seo报价
  • 苏州企业建设网站公司/在线域名解析ip地址
  • 个人模板网站/产品推广策划
  • 广州门户网站建设方案/室内设计培训
  • 成都制作网站/优化建站
  • 现在清算组备案在哪个网站做/搜狗搜索推广