• python pytest测试框架介绍四----pytest-html插件html带错误截图及失败重测机制


    一、html报告错误截图

    这次介绍pytest第三方插件pytest-html

    这里不介绍怎么使用,因为怎么使用网上已经很多了,这里给个地址给大家参考,pytest-html生成html报告

    今天在这里介绍pytest生成的报告怎么带有截图,这在web自动化测试非常有用。

    需求是测试用例错误就截图,方法如下:

    我们要新建一个关于截图的插件文件conftest.py,注意,文件名不能变,因为pytest-html会自动找这个自己写的插件,内容如下:

    from selenium import webdriver
    import pytest
    driver = None
    
    
    @pytest.mark.hookwrapper
    def pytest_runtest_makereport(item):
        """
        Extends the PyTest Plugin to take and embed screenshot in html report, whenever test fails.
        :param item:
        """
        pytest_html = item.config.pluginmanager.getplugin('html')
        outcome = yield
        report = outcome.get_result()
        extra = getattr(report, 'extra', [])
    
        if report.when == 'call' or report.when == "setup":
            xfail = hasattr(report, 'wasxfail')
            if (report.skipped and xfail) or (report.failed and not xfail):
                file_name = report.nodeid.replace("::", "_")+".png"
                _capture_screenshot(file_name)
                if file_name:
                    html = '<div><img src="%s" alt="screenshot" style="304px;height:228px;" ' 
                           'onclick="window.open(this.src)" align="right"/></div>' % file_name
                    extra.append(pytest_html.extras.html(html))
            report.extra = extra
    
    
    def _capture_screenshot(name):
        driver.get_screenshot_as_file(name)
    
    
    @pytest.fixture(scope='session', autouse=True)
    def browser():
        global driver
        if driver is None:
            driver = webdriver.Firefox()
        return driver

    关于conftest.py文件怎么应用,可以查看文档:conftest.py how to put

    接下来,就是写用例了,在与conftest当前文件夹下写用例文件test_aa.py,如下

    def test_screenshot_on_test_failure(browser):
        browser.get("https://www.baidu.com")
        assert False

    然后再次用pytest运行,运行方式如下:

    E:>pytest -s -v test_aa.py --html=report.html

    然后我们可以在E盘下看到生成了report.html文件及测试用例为名的png截图文件

    打开html文件,详情如下:

     参考:

    https://pypi.python.org/pypi/pytest-html

    二、失败重试

    使用的插件是pytest-rerunfailures,官网这里

    使用方法:

    在测试时加入--rerun参数

    py.test --rerun 2
    
    用例失败再重测2次
  • 相关阅读:
    【BZOJ 1579】 1579: [Usaco2009 Feb]Revamping Trails 道路升级 (最短路)
    有限广播地址与直接广播地址
    人生苦短之我用Python篇(线程/进程、threading模块:全局解释器锁gil/信号量/Event、)
    SQL基础二
    Ubuntu命令:sudo、shutdown、apt-get、vim
    SQL基础一
    MPLS基础一
    第一章 Linux系统入门
    P4简介:数据平面的编程语言
    人生苦短之我用Python篇(安装第三方库、正则表达式)
  • 原文地址:https://www.cnblogs.com/landhu/p/7463631.html
Copyright © 2020-2023  润新知