最近在整理allure生成测试报告的内容,现在将学习到的点进行整理。
前期准备工作
需要在项目所在的环境中安装软件包pytest-html
安装的方法有:
1.pip install pytest-html
2.打开pycharm,打开项目,在项目设置处点击解析器,添加pytest-html
基础知识准备:
在执行测试用例命令行后面添加参数: pytest 文件名.py --html=目录。(该目录为测试结果存放的目录地址,如果要清除以前的测试结果,那么在命令后面添加【–clean-alluredir】即可)
在main文件中,代码可以直接写成
import pytest
import os
def test01():
print("hello everyboday")
if __name__=="__main__":
pytest.main(["--html=report/report.html"])
–html指定生成的文件格式是html,pytest.main([“–html=report/report.html”])该代码的含义是在当前测试脚本所在的文件夹下新建一个report文件夹,在report文件夹下生成report.html的文件
生成结果如下图展示:
查看生成的测试报告:
测试报告展示的内容有:1.测试使用的环境信息2测试结果概要,运行的测试数量,通过的测试数量,失败的测试数量,还可以显示所有的
测试用例表,显示每个用例的名称,状态,执行时间
错误和失败详情:提供错误的具体信息,提供错误追踪
图表和图形化进行信息统计
pytest获取测试用例结果流
需要在整个测试项目的配置文件conftest.py文件中下面这写代码:
file name:conftest.py
import pytest
@pytest.hookimpl(hookwrapper=True) #固定写法、写死的
def pytest_runtest_makereport(item,call): #固定写法、写死的
outcome = yield
report = outcome.get_result()
if report.when == "call": #过滤 前置、后置,只保留运行中的状态
print("用例执行结果:",report.outcome)
将输出测试结果流和添加图片结合到一起的代码内容:
file name:conftest.py
import base64
import pytest
from pytest_html import extras
@pytest.hookimpl(hookwrapper=True) #固定写法、写死的
def pytest_runtest_makereport(item, call): #固定写法、写死的
# 将图片转化为base64数据
def image_to_base64(image_path):
with open(image_path,"rb") as image_file:
encoded_string = base64.b64encode(image_file.read())
return encoded_string.decode("utf-8")
outcome = yield
report = outcome.get_result()
extra = getattr(report,"extra",[])
if report.when == "call": # 过滤 前置、后置,只保留运行中的状态
print("用例执行结果:", report.outcome)
if report.outcome != "passed":
#失败截图数据
image_path = "D:\pycharm\HC\pytest_demo\m8_1\列图1.jpg"
base64_data = image_to_base64(image_path)
extra.append(extras.image(base64_data))
report.extra = extra