一、 pytest-html报告没有日志
- 解决办法 执行命名的时候加上
--capture=sys
- 或者直接在pytest.ini 配置
addopts=-vsq --reruns 1 --reruns-delay 2 --html=output/report/html/report.html --self-contained-html --alluredir=output/report/allure_report --capture=sys
二、增加pytest-html报告的描述信息,失败发送邮件。
import pytest
import allure
import base64
import os
import sys
from datetime import datetime
import time
from testdatas import Comm_Datas as CD
from tools.send_mail import send_report
from py.xml import html
from common.constants import ENV_WEB_TXT_FILE, IMG_REPORT as img_dir, IMG_SCREEN_DIR
file_name = IMG_SCREEN_DIR + "{}{}_{}.png".format(os.sep, datetime.strftime(datetime.now(), "%Y%m%d%H%M%S"), "失败截图")
# 定义一个driver全局变量
driver:WebDriver = None
def pytest_html_results_table_header(cells):
cells.insert(1, html.th('用例名称'))
cells.insert(2, html.th('Test_nodeid'))
cells.pop(2)
def pytest_html_results_table_row(report, cells):
cells.insert(1, html.td(report.description))
cells.insert(2, html.td(report.nodeid))
cells.pop(2)
def pytest_html_results_table_html(report, data):
if report.passed:
del data[:]
data.append(html.div('通过的用例未捕获日志输出.', class_='empty log'))
def pytest_html_report_title(report):
report.title = "pytest示例项目测试报告"
def pytest_configure(config):
config._metadata.clear()
config._metadata['测试项目'] = "测试webui自动化"
config._metadata['测试地址'] = CD._base_url
def pytest_html_results_summary(prefix, summary, postfix):
# prefix.clear() # 清空summary中的内容
prefix.extend([html.p("所属部门: XX公司测试部")])
prefix.extend([html.p("测试执行人: 阿登")])
# 测试用例执行失败或者有错误发送邮件
def pytest_terminal_summary(terminalreporter, exitstatus, config):
"""收集测试结果"""
result = {
"total": terminalreporter._numcollected,
'passed': len(terminalreporter.stats.get('passed', [])),
'failed': len(terminalreporter.stats.get('failed', [])),
'error': len(terminalreporter.stats.get('error', [])),
'skipped': len(terminalreporter.stats.get('skipped', [])),
# terminalreporter._sessionstarttime 会话开始时间
'total times': time.time() - terminalreporter._sessionstarttime
}
print(result)
if result['failed'] or result['error']:
send_report()
@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
"""
当测试失败的时候,自动截图,展示到html报告中
:param item:
"""
pytest_html = item.config.pluginmanager.getplugin('html')
outcome = yield
report = outcome.get_result()
# 下面两行代码解决:AttributeError: ‘TestReport’ object has no attribute ‘description’
report.description = str(item.function.__doc__)
report.nodeid = report.nodeid.encode("utf-8").decode("unicode_escape") # 设置编码显示中文
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;" ' \
'onclick="window.open(this.src)" align="right"/></div>' % screen_img
extra.append(pytest_html.extras.html(html))
report.extra = extra
def _capture_screenshot():
"""截图保存为base64"""
now_time = datetime.strftime(datetime.now(), "%Y%m%d%H%M%S")
screen_file = f".{os.sep}output{os.sep}report{os.sep}screenshots"+f"{os.sep}{now_time}.png"
print(now_time, screen_file)
driver.save_screenshot(screen_file)
allure.attach.file(screen_file,
"失败截图{}".format(now_time),
allure.attachment_type.PNG)
with open(screen_file, 'rb') as f:
imagebase64 = base64.b64encode(f.read())
return imagebase64.decode()
@pytest.fixture(autouse=True)
def init_driver(request):
global driver
driver = webdriver.Chrome(chrome_options=browser_option(is_local=True))
def close_driver():
driver.quit()
# 执行后置
request.addfinalizer(close_driver)
return driver
allure失败用例截图 一
@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:
# 判断用例是失败状态则进行截图
driver.get_screenshot_as_file(file_name)
with open(file_name, mode='rb') as f:
file = f.read()
allure.attach(file, f"失败截图{datetime.strftime(datetime.now(), "%Y%m%d%H%M%S"}", allure.attachment_type.PNG)