在测试失败时自动截图并附加到 Allure 报告中,需要在 conftest.py 文件中添加以下代码:
python
import allure
import pytest
from selenium import webdriver
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
rep = outcome.get_result()
# 仅在测试失败时处理
if rep.when == "call" and rep.failed:
# 获取 fixture 中的 driver 对象
driver = item.funcargs.get("driver")
if driver:
# 截图并附加到 allure 报告中
screenshot = driver.get_screenshot_as_png()
allure.attach(screenshot, name="失败截图", attachment_type=allure.attachment_type.PNG)
代码可以直接复制使用
运行测试并生成报告
直接在命令行运行:
python
pytest tests/ --alluredir=allure-results --clean-alluredir
然后生成并打开报告:
python
allure generate allure-results -o allure-report --clean
allure open allure-report