Pytest技术问题:测试执行后如何从FixtureRequest获取测试结果?
解决pytest Fixture中无法获取测试结果的问题
FixtureRequest对象本身在测试用例执行前的阶段是拿不到测试结果的——因为fixture默认在测试启动前初始化,而测试结果(通过/失败/异常)要等测试执行完毕才会生成。要获取这些信息,得结合pytest的钩子函数和fixture的yield特性来实现。
具体实现步骤
1. 用钩子函数捕获测试结果
在项目的conftest.py中添加pytest_runtest_makereport钩子,把测试结果存到测试用例的自定义属性里:
import pytest from _pytest.runner import TestReport @pytest.hookimpl(tryfirst=True, hookwrapper=True) def pytest_runtest_makereport(item, call): # 执行其他钩子获取报告对象 outcome = yield rep = outcome.get_result() # 只记录测试用例执行阶段(call)的结果,排除setup/teardown阶段 if rep.when == "call": setattr(item, "test_result", rep)
2. 在fixture中延迟获取结果
修改你的api_interface fixture,用yield分割测试前准备和测试后逻辑,在测试执行完成后从request.node中取出结果:
import pytest from _pytest.fixtures import FixtureRequest @pytest.fixture def api_interface(request: FixtureRequest): # 这里写测试前的准备逻辑,比如初始化API接口等 yield # 测试用例执行到这里会暂停,先跑测试代码,执行完再回到这里 # 测试执行完成后,获取之前钩子存的结果 test_result = getattr(request.node, "test_result", None) if test_result: # 获取测试状态:passed/failed/skipped test_status = test_result.outcome # 获取测试名称和自定义标记 test_name = request.node.name test_case_id = request.node.get_closest_marker("test_case_id").args[0] if request.node.get_closest_marker("test_case_id") else None print(f"测试名称:{test_name}") print(f"测试用例ID:{test_case_id}") print(f"测试结果:{test_status}") # 如果测试失败,获取异常信息 if test_status == "failed": exception_msg = test_result.longreprtext print(f"异常信息:{exception_msg}")
3. 测试用例保持不变
import pytest class TestSomething: @pytest.mark.test_case_id(99999) def test_example(self, api_interface) -> None: assert 5 == 5
关键说明
- 必须用
yield让fixture在测试执行后再执行结果收集逻辑,否则fixture代码会在测试前跑完,拿不到结果。 - 钩子函数里通过
rep.when == "call"过滤掉setup/teardown阶段的报告,只关注测试用例本身的执行结果。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

