写点什么

实用指南: 使用 Pytest Allure 测试框架添加用例失败截图

  • 2024-04-10
    江西
  • 本文字数:1150 字

    阅读完需:约 4 分钟

前言

在我们进行软件测试的过程中,我们提交的测试报告缺少一些详细的附件,尤其是用例失败时候的截图,更方便我们去查看具体的情况,我们在进行测试时会使用allure+pytest来生成测试报告,本文我们就来介绍一下在 allure 测试报告中添加用例失败截图。

获取更多技术资料,请点击!

钩子函数准备

我们可以使用pytest_runtest_makereport来获取获取用例执行结果,因此我们可以先在conftest.py写一下我们的钩子函数,如下:


# coding=utf-8import pytest, os, allurefrom selenium import webdriverimport xlrd

# 用例失败后自动截图@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(), "失败截图", allure.attachment_type.PNG)

@pytest.fixture(scope='session', autouse=True)def browser():
global driver driver = webdriver.Chrome() return driver
复制代码

测试用例

我们以登录豆瓣为例,写一下我们的测试代码,如下:


import pytest, osfrom selenium import webdriverimport allure

def test_login(browser): with allure.step("step1:打开登录首页"): browser.get("https://accounts.douban.com/passport/login") with allure.step("step2:输入账号"): browser.find_element_by_name("username").send_keys("xxxxxxx") with allure.step("step2:输入密码"): browser.find_element_by_name("password").send_keys("xxxxxx")

if __name__ == "__main__": pytest.main(['--alluredir', '../report', 'test_2.py::test_login']) # allure转换成---html并打开测试报告 os.system('cd D:/se_frame/Reports/allure_data') os.system('allure generate ../report -o report/html --clean')
复制代码

总结

通过结合 Pytest 和 Allure 框架,我们可以轻松地为测试用例添加失败时的截图功能,从而更好地理解测试结果并加快故障排查的速度。希望本文能够帮助大家更好地利用 Pytest 和 Allure 框架进行测试,并提高软件质量。

用户头像

社区:ceshiren.com 微信:ceshiren2021 2019-10-23 加入

微信公众号:霍格沃兹测试开发 提供性能测试、自动化测试、测试开发等资料,实时更新一线互联网大厂测试岗位内推需求,共享测试行业动态及资讯,更可零距离接触众多业内大佬。

评论

发布
暂无评论
实用指南:使用Pytest Allure测试框架添加用例失败截图_霍格沃兹测试开发学社_InfoQ写作社区