如何在Pytest中仅在1_test.py测试完成后执行Python代码?
可行方案
方案1:模块级Fixture(最直接)
在1_test.py内定义一个作用域为module的fixture,利用其yield后的代码(teardown逻辑)在整个模块测试完成后执行发送操作,同时通过钩子收集所有失败用例的信息。
示例代码:
import pytest import requests @pytest.fixture(scope="module", autouse=True) def module_post_process(request): # 初始化失败信息存储 request.config._failure_list = [] yield # 模块所有测试完成后执行:发送失败信息 failure_list = request.config._failure_list if failure_list: payload = {"failure_details": failure_list} # 替换为你的第三方应用接口地址 requests.post("https://your-api-endpoint.com/submit-failures", json=payload) @pytest.hookimpl(tryfirst=True, hookwrapper=True) def pytest_runtest_makereport(item, call): # 捕获测试报告 outcome = yield report = outcome.get_result() # 仅收集调用阶段的失败用例信息 if report.when == "call" and report.failed: failure_info = { "test_case": item.name, "parameters": item.callspec.params if hasattr(item, "callspec") else {}, "error_msg": str(call.excinfo.value) } item.config._failure_list.append(failure_info) # 你的测试用例 @pytest.mark.parametrize("param1, param2", test_list) def test_1(param1, param2): assert param1 == param2 @pytest.mark.parametrize("param1, param2", test_list) def test_2(param1, param2): assert param1 + 1 == param2
说明:
autouse=True让fixture自动应用到当前模块所有测试,无需手动传入测试函数- 用
request.config存储失败信息,避免全局变量污染 yield后的代码会在整个模块测试结束后执行,此时已收集完全部失败数据
方案2:模块级钩子函数
直接在1_test.py内定义pytest_module_sessionfinish钩子,该钩子会在当前模块测试完成后触发,通过模块名称判断确保仅在目标文件执行发送逻辑。
示例代码:
import pytest import requests failure_list = [] @pytest.hookimpl(tryfirst=True, hookwrapper=True) def pytest_runtest_makereport(item, call): outcome = yield report = outcome.get_result() if report.when == "call" and report.failed: failure_info = { "test_case": item.name, "parameters": item.callspec.params if hasattr(item, "callspec") else {}, "error_msg": str(call.excinfo.value) } failure_list.append(failure_info) def pytest_module_sessionfinish(session, module): # 仅在当前模块为1_test.py时执行发送 if module.__name__ == "1_test": if failure_list: payload = {"failure_details": failure_list} requests.post("https://your-api-endpoint.com/submit-failures", json=payload)
注意事项
- 确保已安装
requests库:执行pip install requests - VS Code的Pytest插件会自动识别并执行文件内的钩子和fixture,无需额外配置
- 若需要更复杂的失败信息,可从
report或call对象中提取更多字段(如失败回溯栈)
内容的提问来源于stack exchange,提问作者AzUser1
相关产品推荐
相关产品推荐

