为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

狐的传说 2022-12-06 15:31:57
我有一个通过 pytest-html 生成 HTML 输出的测试。我收到了报告,但我想添加对失败和预期图像的引用;我将它们保存在我的主 test.py 文件中,并将钩子添加到conftest.py.现在,我不知道如何将这些图像传递给函数;执行测试后调用挂钩;目前我正在对输出文件进行硬编码并附加它们;但我想从测试中传递图像的路径,特别是因为我需要编写更多测试,这些测试可能保存在我常用文件夹的其他地方,并且可能有不同的名称。这是我在 conftest.py 中的钩子@pytest.mark.hookwrapperdef 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 测试文件传递给钩子,一个包含要附加的图像路径的变量?
查看完整描述

1 回答

?
慕姐8265434

TA贡献1813条经验 获得超2个赞

我找到了一个解决方法,虽然它并不漂亮。


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


在测试文件.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


查看完整回答
反对 回复 2022-12-06
  • 1 回答
  • 0 关注
  • 242 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号