python+selenium(8)---pytest+allure用例执行失败截图并展示在报告中

本文介绍了如何在Python的pytest框架结合Allure报告中,当测试用例执行失败时自动截取屏幕快照并显示在报告中。通过在conftest.py文件中设置hook函数,确保driver的正确使用,实现了失败截图功能。
摘要由CSDN通过智能技术生成

实现该功能要用到pytest中的hook函数(钩子函数),如下:

可直接使用该代码

# 用例失败后自动截图
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    """
    获取用例执行结果的钩子函数
    :param item:
    :param call:
    :return:
    """
    outcome = yield
    report = outcome.get_result()
    if report.when == "call" and report.failed:
        mode = "a" if os.path.exists("failures") else "w"
        with open("failures", mode)as f:
            if "tmpir" in item.fixturenames:
                extra = " (%s)" % item.funcargs["tmpdir"]
            else:
                extra = ""
                f.write(report.nodeid + extra + "\n")
            with allure.step('添加失败截图...'):
                allure.attach(driver.get_screenshot_as_png(), "失败截图",
作为AI语言模型,我无法在计算机上执行任何操作,因此无法提供pytest allure用例执行失败截图。但是,以下是如何在使用pytest allure时自动截取用例执行失败截图的示例代码: ```python import allure import pytest from selenium import webdriver @pytest.fixture(scope="function") def browser(): driver = webdriver.Chrome() yield driver driver.quit() @allure.step("Open website '{url}'") def open_website(browser, url): browser.get(url) @allure.step("Click on element '{locator}'") def click_element(browser, locator): element = browser.find_element(*locator) element.click() @allure.step("Verify element '{locator}' is present") def verify_element_present(browser, locator): assert browser.find_element(*locator).is_displayed() @allure.step("Enter text '{text}' into element '{locator}'") def enter_text(browser, locator, text): element = browser.find_element(*locator) element.send_keys(text) @allure.step("Verify text '{text}' is present in element '{locator}'") def verify_text_present(browser, locator, text): assert text in browser.find_element(*locator).text def test_login_failure(browser): with allure.step("Given the user is on the login page"): open_website(browser, "https://www.example.com/login") with allure.step("When the user enters invalid credentials"): enter_text(browser, (By.ID, "username"), "invalid_username") enter_text(browser, (By.ID, "password"), "invalid_password") click_element(browser, (By.NAME, "login_button")) with allure.step("Then an error message is displayed"): verify_element_present(browser, (By.CSS_SELECTOR, ".error_message")) verify_text_present(browser, (By.CSS_SELECTOR, ".error_message"), "Invalid username or password") # Take screenshot on failure allure.attach( browser.get_screenshot_as_png(), name="Screenshot", attachment_type=allure.attachment_type.PNG, ) ``` 在测试用例失败时,pytest allure将自动捕获失败截图并将其添加到测试报告
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值