如何捕获pytest中每个测试用例的PASSED与FAILED状态
实现pytest测试结果自动写入自定义日志的简便方案
这里给你两种超简便的实现方式,不用复杂配置,几行代码就能搞定:
方案1:自动执行的Fixture(无需手动引用)
在测试文件或者conftest.py中添加以下代码:
import pytest import logging # 配置自定义日志(替换成你的日志文件路径) logging.basicConfig( filename="your_custom_log.log", level=logging.INFO, format="%(asctime)s - Test Case: %(test_name)s - Result: %(result)s", datefmt="%Y-%m-%d %H:%M:%S" ) @pytest.fixture(autouse=True, scope="function") def log_test_result(request): yield # 先执行测试用例 # 测试结束后写入结果 test_name = request.node.name test_result = "PASS" if request.node.rep_call.passed else "FAIL" logging.info("", extra={"test_name": test_name, "result": test_result})
说明:
autouse=True会让这个fixture自动作用于所有测试用例,不用在每个测试里手动调用。scope="function"保证每个测试用例执行完都会触发日志写入。request.node.rep_call是pytest内置的报告对象,直接就能拿到测试的pass/fail状态。
方案2:极简钩子实现(代码量更少)
如果你能接受钩子方案,这个版本代码极简,放在conftest.py里就行:
import logging # 配置自定义日志(替换成你的日志文件路径) logging.basicConfig( filename="your_custom_log.log", level=logging.INFO, format="%(asctime)s - Test Case: %(test_name)s - Result: %(result)s", datefmt="%Y-%m-%d %H:%M:%S" ) def pytest_runtest_makereport(item, call): # 只在测试执行阶段处理结果 if call.when == "call": test_name = item.nodeid.split("::")[-1] # 提取测试用例名称 test_result = "PASS" if call.excinfo is None else "FAIL" logging.info("", extra={"test_name": test_name, "result": test_result})
说明:
- 钩子
pytest_runtest_makereport会在每个测试生成报告时触发,我们只需要在测试执行完成的阶段(call)提取结果写入日志即可。 call.excinfo为None说明测试没抛出异常,也就是PASS,否则就是FAIL。
这两种方式都不需要额外依赖,直接用pytest和Python内置的logging模块就能实现,完全满足你的需求。
内容的提问来源于stack exchange,提问作者Abhilash
相关产品推荐
相关产品推荐

