pytest后置处理方式

在 pytest 中,确保后置清理代码一定会执行(无论测试通过、失败还是发生异常),推荐使用以下两种最稳健的方式:


1. 使用 yield 的 fixture(推荐)

在 fixture 的 yield 之后编写清理代码,pytest 会在测试结束后自动运行这些代码,即使测试断言失败或抛出异常。

复制代码
import pytest

@pytest.fixture
def db_connection():
    # 前置:建立连接
    conn = create_connection()
    yield conn
    # 后置:一定会执行(除非 fixture 前置阶段就挂了)
    conn.close()

def test_query(db_connection):
    assert db_connection.query("SELECT 1") == 1

⚠️ 注意:如果 yield 之前的代码(建立连接)抛出了异常,那么 yield 之后的清理代码不会执行,因为 fixture 本身没有成功初始化。这是合理的------资源从未被成功获取,自然无需释放。


2. 使用 request.addfinalizer

功能与 yield 类似,但以注册回调函数的方式显式声明清理逻辑。

复制代码
import pytest

@pytest.fixture
def db_connection(request):
    conn = create_connection()
    def cleanup():
        conn.close()
    request.addfinalizer(cleanup)   # 注册后置函数
    return conn

同样,addfinalizer 注册成功后的清理函数一定会执行。


3. 在测试类或模块中使用传统 teardown 方法

适用于经典的 xUnit 风格,pytest 完全支持:

  • 方法级 :def teardown_method(self, method):

  • 类级 :def teardown_class(cls):

  • 模块级 :def teardown_module(module):

复制代码
class TestDatabase:
    def setup_method(self):
        self.conn = create_connection()

    def teardown_method(self):
        self.conn.close()   # 每个测试方法结束后一定会执行

    def test_query(self):
        assert self.conn.query("SELECT 1") == 1

4. 如果需要"无论如何(即使 fixture 设置失败)都执行清理"

如果存在必须执行的全局资源回收(例如临时文件、进程等),可以在 fixture 中使用 try/finally:

复制代码
@pytest.fixture
def temp_file():
    f = None
    try:
        f = open("/tmp/test.txt", "w")
        yield f
    finally:
        if f:
            f.close()
        # 或者无条件删除文件

但这种情况较少见,因为通常设置失败时资源尚未分配,无需清理。

方式 是否保证后置执行 备注
yield fixture ✅(前置成功时) 最推荐,代码简洁
request.addfinalizer ✅(前置成功时) 与 yield 等价
teardown_* 方法 ✅(对应作用域) 适用于传统风格
try/finally ✅(无条件) 适合必须清理的场景
相关推荐
在世修行2 小时前
干货:pytest
pytest·fixture·pytest assert
小小龙学IT2 天前
Python pytest 测试框架深度解析:从断言重写到插件生态的工程化测试体系
网络·python·pytest
落魄大学生之流水线上谋生计4 天前
pytest 入门与实践:从第一个测试到可维护的测试体系
pytest
念越5 天前
Allure 测试报告保姆级教程:从安装到 pytest 集成与报告生成
pytest·allure
念越6 天前
接口自动化测试从入门到实战:接口用例设计、Requests、Pytest、YAML、JSON Schema 与 Allure 报告
python·测试工具·自动化·json·pytest
霍格沃兹测试学院-小舟畅学10 天前
AI+Swagger:一键生成500条pytest接口用例
人工智能·pytest
把头塞进显示器19 天前
电商平台-测试报告
python·selenium·pytest
昔我往昔23 天前
pytest日志问题排查记录
python·pytest
黄昏恋慕黎明1 个月前
博客论坛技术迭代
python·pytest
2601_962078231 个月前
Python接口自动化流程(pytest)
python·pytest·接口自动化·测试框架·断言