pytest html将图像从测试文件传递到conftest.py中的钩子

2024-05-12 19:32:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个通过pytest HTML生成HTML输出的测试

我得到了报告,但我想添加一个失败和预期形象的参考;我将它们保存在主test.py文件中,并将钩子添加到conftest.py

现在,我不知道如何将这些图像传递给函数;试验完成后调用吊钩;目前我正在对输出文件进行硬编码,并将其附在附件中;但是我希望通过测试来传递图像的路径,特别是因为我需要编写更多的测试,这些测试可能保存在我常用文件夹的其他地方,并且可能有不同的名称

这是我在conftest.py中的钩子

@pytest.mark.hookwrapper
def pytest_runtest_makereport(item, call):

    timestamp = datetime.now().strftime('%H-%M-%S')

    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()
    extra = getattr(report, 'extra', [])
    if report.when == 'call':
        # Attach failure image, hardcoded...how do I pass this from the test?
        extra.append(pytest_html.extras.image('/tmp/image1.png'))

        # test report html
        extra.append(pytest_html.extras.url('http://www.theoutput.com/'))
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):
            # only add additional data on failure
            # Same as above, hardcoded but I want to pass the reference image from the test
            extra.append(pytest_html.extras.image('/tmp/image2.png'))
            extra.append(pytest_html.extras.html('<div>Additional HTML</div>'))
        report.extra = extra

如何从pytest文件传递到hook,一个包含要附加的图像路径的变量


Tags: 文件thepytest图像imagereportextras
1条回答
网友
1楼 · 发布于 2024-05-12 19:32:26

我找到了一个解决办法,尽管它并不漂亮

在我的测试文件中添加模块级别的变量,允许我使用item.module.varname,因此如果我在模块测试中设置varname,然后在测试中分配它;我可以在pytest_runtest_makereport中访问它

在testfile.py中

import pytest

myvar1 = None
myvar2 = None

class VariousTests(unittest.TestCase):

    def test_attachimages():

        global myvar1
        global myvar2

        myvar1 = "/tmp/img1.png"
        myvar2 = "/tmp/img2.png"

在conftest.py中

@pytest.mark.hookwrapper
def pytest_runtest_makereport(item, call):

    timestamp = datetime.now().strftime('%H-%M-%S')

    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()
    extra = getattr(report, 'extra', [])
    if report.when == 'call':
        # Attach failure image
        img1 = item.module.myvar1
        img2 = item.module.myvar2
        extra.append(pytest_html.extras.png(img1))
        # test report html
        extra.append(pytest_html.extras.url('http://www.theoutput.com/'))
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):
            # only add additional data on failure
            # Same as above, hardcoded but I want to pass the reference image from the test
            extra.append(pytest_html.extras.png(img2))
            extra.append(pytest_html.extras.html('<div>Additional HTML</div>'))
        report.extra = extra

相关问题 更多 >