使用 pytest.hookimpl 将 pytest 测试函数返回值写入文件

Leo*_*aus 3 python benchmarking return return-value pytest

我正在寻找一种方法来访问测试函数的返回值,以便将该值包含在测试报告文件中(类似于http://doc.pytest.org/en/latest/example/simple.html#post -process-test-reports-failures)。

我想使用的代码示例:

# modified example code from http://doc.pytest.org/en/latest/example/simple.html#post-process-test-reports-failures

import pytest
import os.path

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    # execute all other hooks to obtain the report object
    outcome = yield
    rep = outcome.get_result()

    if rep.when == "call" and rep.passed:
        mode = "a" if os.path.exists("return_values") else "w"
        with open("return_values.txt", mode) as f:
            # THE FOLLOWING LINE IS THE ONE I CANNOT FIGURE OUT
            # HOW DO I ACCESS THE TEST FUNCTION RETURN VALUE?
            return_value = item.return_value
            f.write(rep.nodeid + ' returned ' + str(return_value) + "\n")
Run Code Online (Sandbox Code Playgroud)

我希望将返回值写入文件“return_values.txt”。相反,我得到了一个 AttributeError。

背景(如果您可以推荐一种完全不同的方法):

我有一个 Python 库,用于对给定问题进行数据分析。我有一组标准的测试数据,我经常运行我的分析来生成关于分析算法质量的各种“基准”指标。例如,一个这样的度量是由分析代码生成的归一化混淆矩阵的迹线(我希望它尽可能接近 1)。另一个指标是产生分析结果的 CPU 时间。

我正在寻找一种很好的方法将这些基准测试结果包含到 CI 框架(目前是 Jenkins)中,这样就可以轻松查看提交是提高还是降低了分析性能。由于我已经在 CI 序列中运行 pytest,并且由于我想将 pytest 的各种功能用于我的基准测试(夹具、标记、跳过、清理),我想简单地在 pytest 中添加一个后处理钩子(参见http: //doc.pytest.org/en/latest/example/simple.html#post-process-test-reports-failures ) 收集测试函数运行时间和返回值并报告它们(或仅标记为基准的那些)到一个文件中,该文件将被我的 CI 框架收集并存档为测试工件。

我对解决这个问题的其他方法持开放态度,但我的谷歌搜索结论是 pytest 是最接近已经提供我需要的框架。

hoe*_*ing 6

pytest忽略测试函数的返回值,如代码所示:

@hookimpl(trylast=True)
def pytest_pyfunc_call(pyfuncitem):
    testfunction = pyfuncitem.obj
    ...
    testfunction(**testargs)
    return True
Run Code Online (Sandbox Code Playgroud)

但是,您可以在测试函数中存储所需的任何内容;我通常使用该config对象来实现此目的。示例:将以下代码片段放入您的conftest.py

import pathlib
import pytest


def pytest_configure(config):
    # create the dict to store custom data
    config._test_results = dict()


@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    # execute all other hooks to obtain the report object
    outcome = yield
    rep = outcome.get_result()

    if rep.when == "call" and rep.passed:
        # get the custom data
        return_value = item.config._test_results.get(item.nodeid, None)
        # write to file
        report = pathlib.Path('return_values.txt')
        with report.open('a') as f:
            f.write(rep.nodeid + ' returned ' + str(return_value) + "\n")
Run Code Online (Sandbox Code Playgroud)

现在将数据存储在测试中:

def test_fizz(request):
    request.config._test_results[request.node.nodeid] = 'mydata'
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!这对我来说并不明显,所以仅供参考 - 您需要将第二块代码放入 conftest.py 文件中。 (2认同)

Ita*_*viv 6

分享同样的问题,这是我想出的不同解决方案:

record_property在测试中使用夹具:

def test_mytest(record_property):
    record_property("key", 42)
Run Code Online (Sandbox Code Playgroud)

然后conftest.py我们可以使用pytest_runtest_teardown 钩子

#conftest.py
def pytest_runtest_teardown(item, nextitem):
    results = dict(item.user_properties)
    if not results:
        return
    with open(f'{item.name}_return_values.txt','a') as f:
        for key, value in results.items():
            f.write(f'{key} = {value}\n')
Run Code Online (Sandbox Code Playgroud)

然后是内容test_mytest_return_values.txt

key = 42
Run Code Online (Sandbox Code Playgroud)

两个重要的注意事项:

  1. 即使测试失败,也会执行此代码。我找不到获得测试结果的方法。
  2. 这可以与heofling的答案结合使用results = dict(item.user_properties)以获取在测试中添加的键和值,而不是将 dict 添加到 config 然后在测试中访问它。