41-pytest-报告中添加失败用例截图

报告中添加失败用例截图


前言

  • 在UI自动化测试中,经常需要在用例失败时保存截图,那么本篇来学习下在allure和html报告中添加失败用例的截图。

allure报告

  • conftset.py
# -*-coding:utf-8一*-
# @Time:2022/10/13
# @Author: 大海
import os
import allure
import pytest
from selenium import webdriver

driver = None

@pytest.mark.hookwrapper
def pytest_runtest_makereport(item, call):
    outcome = yield
    res = outcome.get_result()
    if res.when == "call" and res.failed:
        mode = "a" if os.path.exists("failures") else "w"
        with open("failures", mode) as f:
            # let's also access a fixture for the fun of it
            if "tmpdir" in item.fixturenames:
                extra = " (%s)" % item.funcargs["tmpdir"]
            else:
                extra = ""
            f.write(res.nodeid + extra + "\n")
        # 添加allure报告截图
        if hasattr(driver, "get_screenshot_as_png"):
            with allure.step('添加失败截图...'):
                allure.attach(driver.get_screenshot_as_png(), "失败截图", allure.attachment_type.PNG)


@pytest.fixture(scope='session')
def browser():
    global driver
    if driver is None:
        # chromedriver 路径已添加到系统环境变量中,所以此处可省略chromedriver路径参数
        driver = webdriver.Chrome()
    yield driver
    driver.quit()
  • 编写case
# -*-coding:utf-8一*-
# @Time:2022/10/13
# @Author: 大海

import allure
import os
from selenium.webdriver.common.by import By


@allure.title("测试搜索页title")
def test_search(browser):
    """测试搜索页title"""
    with allure.step("step1:打开百度首页"):
        browser.get("https://www.baidu.com/")
    with allure.step("step2:搜索自动化测试"):
        browser.find_element(By.ID, "kw").send_keys("pytest")
    # 断言失败,验证是否截图
    print(browser.title)
    assert browser.title == "百度"


if __name__ == '__main__':
    os.system('pytest -s test_72.py --alluredir=./allure-data --clean-alluredir')
    # 打开allure报告 (目录与上面生成结果目录需一致)
    os.system('allure generate -c -o ./allure-report ./allure-data')
    os.system('allure open ./allure-report')
  • 查看报告

在这里插入图片描述

html报告

  • conftest.py
# -*-coding:utf-8一*-
# @Time:2022/10/13
# @Author: 大海

import pytest
from selenium import webdriver

@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
    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;" ' \
                       'οnclick="window.open(this.src)" align="right"/></div>' % screen_img
                extra.append(pytest_html.extras.html(html))
        report.extra = extra
      


@pytest.fixture(scope='session')
def browser():
    global driver
    if driver is None:
        driver = webdriver.Chrome()
    yield driver
    driver.quit()


def _capture_screenshot():
    """截图"""
    return driver.get_screenshot_as_base64()
  • 编写case
# -*-coding:utf-8一*-
# @Time:2022/10/13
# @Author: 大海

import allure
import os
from selenium.webdriver.common.by import By


@allure.title("测试搜索页title")
def test_search(browser):
    """测试搜索页title"""
    with allure.step("step1:打开百度首页"):
        browser.get("https://www.baidu.com/")
    with allure.step("step2:搜索自动化测试"):
        browser.find_element(By.ID, "kw").send_keys("pytest")
    # 断言失败,验证是否截图
    print(browser.title)
    assert browser.title == "百度"


if __name__ == '__main__':
    os.system('pytest -s -v test_72.py --html=report.html --self-contained-html')
  • 查看报告

在这里插入图片描述

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Pytest,可以使用pytest-rerunfailures插件来实现失败用例的重跑。安装该插件的方式是通过pip install pytest-rerunfailures命令进行安装。安装完成后,可以通过两种方式来实现失败用例的重跑。 方式一是在命令行或者main()函数使用pytest.main(\['-vs','test_a.py','--reruns=2'\])命令来执行测试脚本,并通过--reruns参数指定重跑次数。例如,pytest -vs ./test_a.py --reruns 2 --reruns-delay 2表示失败重试2次,在每次重试前会等待2秒。 方式二是在pytest.ini配置文件使用。在pytest.ini文件,可以通过addopts参数来添加--reruns参数,并指定重跑次数和重跑间隔时间。例如,\[pytest\] addopts = -s --reruns 2 --reruns-delay 2可以实现失败重试2次,在每次重试前等待2秒。 需要注意的是,使用pytest-rerunfailures插件时,可以在测试用例上使用@pytest.mark.flaky(reruns=3)装饰器来指定重跑次数。例如,@pytest.mark.flaky(reruns=3) def test01(): assert randint(1, 10) == 6可以实现失败重试3次。 总结起来,要实现pytest命令行重跑失败用例,可以通过命令行参数或者pytest.ini配置文件来指定重跑次数和重跑间隔时间。 #### 引用[.reference_title] - *1* *3* [四、Pytest框架 — pytest.ini文件和用例执行的顺序以及跳过测试和失败重试](https://blog.csdn.net/m0_59868866/article/details/125002374)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [pytest系列教程——12、用例执行失败后重跑](https://blog.csdn.net/bo_mask/article/details/126761257)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱学习de测试小白

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值