pytest-生命周期钩子函数

1、增加自定义参数

def pytest_addoption(parser):
    # pytest的钩子函数,自动执行
    # 增加自定义参数
    parser.addoption(
        "--browser_type",
        action="store",
        default="chrome",
        help="浏览器类型"
    )

2、定制化自带的html报告

def pytest_html_results_summary(prefix, summary, postfix):
    # 在Summary中增加项目名称
    prefix.extend([html.p("项目名称: xxxx")])

def pytest_html_report_title(report):
    report.title = "UI测试报告"

def pytest_html_results_table_header(cells):
    # 表头增加列和删除列
    cells.insert(2, html.th('Description'))
    cells.insert(3, html.th('Time', class_='sortable time', col='time'))
    cells.pop(-1)  # 删除link列


@pytest.mark.optionalhook
def pytest_html_results_table_row(report, cells):
    # 表格内容增加列和删除列
    cells.insert(2, html.td(report.description))
    cells.insert(3, html.td(datetime.utcnow(), class_='col-time'))
    cells.pop(-1)  # 删除link列

@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item):
    """
    报告列表中添加描述信息
    当测试失败的时候,自动截图,展示到html报告中
    """
    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()
    report.description = str(item.function.__doc__)
    # report.nodeid = report.nodeid.encode("utf-8").decode("unicode_escape")  # 设置编码显示中文
    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):
            screen_img = _capture_screenshot()
            if screen_img:
                html = '<div><img src="data:image/png;base64,%s" alt="screenshot" style="width:1024px;height:768px;" ' \
                       'onclick="window.open(this.src)" align="right"/></div>' % screen_img
                extra.append(pytest_html.extras.html(html))
        report.extra = extra


def _capture_screenshot():
    """截图保存为base64"""
    
    now_time, screen_file = cm.screen_path
    driver.save_screenshot(screen_file)
    allure.attach.file(screen_file, "失败截图{}".format(now_time), allure.attachment_type.PNG)
    with open(screen_file, 'rb') as f:
        imagebase64 = base64.b64encode(f.read())
    return imagebase64.decode()

3、收集测试结果

def pytest_terminal_summary(terminalreporter, exitstatus, config):
    """
    收集测试结果,用于jenkins发送邮件
    """
    # print('==================收集测试结果')
    total = terminalreporter._numcollected
    passed = len([i for i in terminalreporter.stats.get('passed', []) if i.when != 'teardown'])
    failed = len([i for i in terminalreporter.stats.get('failed', []) if i.when != 'teardown'])
    error = len([i for i in terminalreporter.stats.get('error', []) if i.when != 'teardown'])
    skipped = len([i for i in terminalreporter.stats.get('skipped', []) if i.when != 'teardown'])
    successful = (len(terminalreporter.stats.get('passed', [])) / terminalreporter._numcollected * 100)
    duration = time.time() - terminalreporter._sessionstarttime
    failed_cases_list = [{'name': i.location[-1], 'desc': i.description} for i in terminalreporter.stats.get('failed', []) if i.when != 'teardown']
    error_cases_list = [{'name': i.location[-1], 'desc': i.description} for i in terminalreporter.stats.get('error', []) if i.when != 'teardown']

    # 将结果保存在本地,供jenkins调用
    with open("result.txt", "w", encoding="utf-8") as fp:
        fp.write("TOTAL=%s" % total + "\n")
        fp.write("PASSED=%s" % passed + "\n")
        fp.write("FAILED=%s" % failed + "\n")
        fp.write("ERROR=%s" % error + "\n")
        fp.write("SKIPPED=%s" % skipped + "\n")
        fp.write("SUCCESSFUL=%.2f%%" % successful + "\n")
        fp.write("TOTAL_TIMES=%.2fs" % duration + "\n")

版权声明:本文为weixin_44153651原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
THE END
< <上一篇
下一篇>>