如何在pytest的autouse fixture的teardown中打印测试结果
实现方法
核心思路是借助pytest内置的request对象获取测试用例的执行上下文,在autouse fixture的teardown阶段读取测试结果并打印。
完整代码示例
import pytest @pytest.fixture(autouse=True) def auto_print_test_result(request): yield # Setup阶段无操作,直接进入测试执行 # Teardown阶段:获取并打印测试结果 test_node = request.node test_name = test_node.name # 读取测试执行结果 test_outcome = test_node.rep_call.outcome # 根据结果类型打印信息 if test_outcome == "passed": print(f"\n测试用例 [{test_name}] 执行结果:通过") elif test_outcome == "failed": print(f"\n测试用例 [{test_name}] 执行结果:失败") # 可选:处理测试跳过的场景 elif test_outcome == "skipped": print(f"\n测试用例 [{test_name}] 执行结果:跳过") # 测试用例示例 def test_normal_pass(): assert 2 + 3 == 5 def test_normal_fail(): assert 10 - 3 == 6 @pytest.mark.skip(reason="临时跳过该用例") def test_skip_case(): assert True
关键说明
autouse=True:让该fixture自动应用到所有测试用例,无需手动调用request:pytest内置fixture,提供当前测试请求的上下文信息request.node:代表当前测试用例的节点对象,包含名称、执行结果等元数据rep_call:测试用例执行完成后的结果对象,outcome属性返回执行状态(passed/failed/skipped)
运行注意事项
默认情况下pytest会捕获控制台输出,若要看到打印的结果,运行时需加上-s参数:
pytest your_test_file.py -s
内容的提问来源于stack exchange,提问作者juniper27
相关产品推荐
相关产品推荐

