【pytest】pytest-html报告报错截图conftest中配置(通用)

背景

做web自动化的小伙伴应该都希望在html报告中展示失败后的截图,提升报告的档次,pytest-html也可以生成带截图的报告。

 

遇到问题

 1-conftest结合fixture的使用

conftest中fixture的scope参数为session,所有测试.py文件执行前执行一次

conftest中fixture的scope参数为module,每一个测试.py文件执行前都会执行一次conftest文件中的fixture

conftest中fixture的scope参数为class,每一个测试文件中的测试类执行前都会执行一次conftest文件中的fixture

conftest中fixture的scope参数为function,所有文件的测试用例执行前都会执行一次conftest文件中的fixture

2-fixture参数autouse=True:

每次执行.py用例都是执行此配置下的方法---启动浏览器

3-测试用例类和函数使用conftest

 

 

代码


conftest.py


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 and screen_img is not None:
# 当失败用例,截图返回的是None时,不会添加到报告中
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:
"""
if driver is not None:
return driver.get_screenshot_as_base64()
else:
print("browser autose设置为false,driver获取异常")


@pytest.fixture(scope='session', autouse=True)
# scope="session" 以实现多个.py跨文件使用一个session来完成多个用例
# 参数:autouse=True时,每个用例实例都会调用下面函数
def browser(request):
global driver
if driver is None:
driver = webdriver.Chrome()

def end():
driver.quit()

request.addfinalizer(end)
return driver

test.py

# !/usr/bin/env python
# !-*-conding:uft-8 -*-
# !@Time :2021/2/27 18:41
# !@Author : hjt

import time


def test_01(browser):
browser.get("https://home.cnblogs.com/u/juntaohuang/")
time.sleep(2)
t = browser.title
assert t == "xxx"

class Test001():
def test_01(self, browser):
browser.get("https://home.cnblogs.com/u/juntaohuang/")
        time.sleep(2)
t = browser.title
assert t == "xxx"

posted on 2021-02-27 21:05  为什么我还是学渣  阅读(561)  评论(0)    收藏  举报