前言
做web自动化的小伙伴应该都希望在html报告中展示失败后的截图,提升报告的档次,pytest-html也可以生成带截图的报告。
conftest.py
1.失败截图可以写到conftest.py文件里,这样用例运行时,只要检测到用例实例,就调用截图的方法,并且把截图存到html报告上
# conftest.py文件
# coding:utf-8 from selenium import webdriver import pytest driver = None @pytest.mark.hookwrapper def pytest_runtest_makereport(item): """ 当测试失败的时候,自动截图,展示到html报告中 :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" screen_img = _capture_screenshot() if file_name: html = ‘<div><img src="data:image/png;base64,%s" alt="screenshot" style="width:600px;height:300px;" ‘ ‘onclick="window.open(this.src)" align="right"/></div>‘ % screen_img extra.append(pytest_html.extras.html(html)) report.extra = extra def _capture_screenshot(): ‘‘‘ 截图保存为base64,展示到html中 :return: ‘‘‘ return driver.get_screenshot_as_base64() @pytest.fixture(scope=‘session‘, autouse=True) def browser(): global driver if driver is None: driver = webdriver.Chrome() return driver
2.用例部分如下:
# test_01.py文件
from selenium import webdriver import time def test_yoyo_01(browser): browser.get("https://www.cnblogs.com/lixy-88428977/") time.sleep(2) t = browser.title assert t == "含笑半步颠√"
# test_02.py文件
from selenium import webdriver import time def test_yoyo_01(browser): browser.get("https://www.cnblogs.com/lixy-88428977/") time.sleep(2) t = browser.title assert "含笑半步颠√" in t
报告展示
1.cmd打开,cd到用例的目录,执行指令
$ pytest --html=report.html --self-contained-html / python3 -m pytest --html=report.html --self-contained-html
2.生成报告如下
失败重试
用例失败再重测1次,命令行加个参数就行了
$ py.test --rerun 1 --html=report.html --self-contained-html
作者:含笑半步颠√
博客链接:https://www.cnblogs.com/lixy-88428977
声明:本文为博主学习感悟总结,水平有限,如果不当,欢迎指正。如果您认为还不错,欢迎转载。转载与引用请注明作者及出处。
原文地址:https://www.cnblogs.com/lixy-88428977/p/9614259.html
时间: 2024-10-30 10:21:13