python - 是否有自定义方法来收集 pytest 结果?
问题描述
我想查看刚刚运行的测试结果,以便我可以将信息通过管道传输到自定义文件中。这将在稍后用于自动解析 pytest 结果。
解决方案
是的,有一种方法可以创建/使用 conftest.py。在示例中,将创建一个带有结果的字典,并在所有测试运行后打印结果。
from collections import OrderedDict
test_results = OrderedDict()
def get_current_test():
"""Just a helper function to extract the current test"""
full_name = os.environ.get('PYTEST_CURRENT_TEST').split(' ')[0]
test_file = full_name.split("::")[0].split('/')[-1].split('.py')[0]
test_name = full_name.split("::")[1]
return full_name, test_file, test_name
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
"""The actual wrapper that gets called before and after every test"""
global test_results
outcome = yield
rep = outcome.get_result()
# only check the result of the test
if rep.when == "call":
full_name, test_file, test_name = get_current_test()
test_name_msg = f"{test_name}_msg"
if rep.failed:
test_results[test_name] = "Failure"
# return the last error msg either by pytest.fail or from any exception raised
test_results[test_name_msg] = f"{call.excinfo.typename} - {call.excinfo.value}"
else:
test_results[test_name] = "Success"
test_results[test_name_msg] = ''
def pytest_unconfigure(config):
"""Called when pytest is about to end. Can be used to print the result dict or
to pipe the data into a file"""
print(test_results)
推荐阅读
- sql - 将 SQL 查询转换为使用 Microsoft Access
- java - 如何在不加载数据的情况下知道 RecyclerView 中可以看到的最大 ItemView 数量?
- vb.net - 在 vb.net 中使用颜色作为变量
- mysql - 将mac os升级到Mojave后MySql数据库被删除
- node.js - 如何使用 csurf 返回 404 而不是 403 的空路径参数处理 expressjs 休息路线?
- python - 在这个作业中,您将要求用户输入一个英文单词,将该单词翻译成“Pig Latin”,然后打印这两个单词
- python - QPushButton 不显示按钮图标
- mongodb - MongoDB数据集:对不减少或脚本问题
- android - 如何实现跟随滑动/触摸的交互式垂直片段过渡?
- python - 如何将一个数据帧附加到另一个数据帧而不重复