『德不孤』Pytest框架 — 9、Pytest测试报告

1、pytest-html插件

Pytest可以通过命令行方式,生成xml/html格式的测试报告,并存储于用户指定路径。

需要用到pytest-html插件。

安装方式:执行命令pip install pytest-html

(1)插件使用方式:

命令格式:--html=用户路径/report.html

运行方式:

  1. main()函数方式:
    pytest.main(['--html=./report/report_01.html'])(不好使,可能配置了pytest.ini文件)
  2. 命令行方式:
    report目录中生成report.html测试报告。
    pytest ./pytest_demo/test_pytest_01.py --html=./report/report.html
  3. 使用pytest.ini文件方式:
    addopts属性后追加--html参数配置,在report目录中生成report.html测试报告。
    addopts = -s --html=../report/report.html

(2)执行结果:

在指定目录中会生成assets文件夹(css文件)和report.html文件。

如下图所示:

image

提示:若要生成xml文件,可将--html=./report.html改成--junitxml= report/report.xml

2、Allure测试报告

(1)Allure框架说明

Allure生成的测试报告与上面pytest-html插件生成的测试报告对比,简直完美!

Allure是一个Report框架,是一种灵活的轻量级,支持多语言的测试报告工具,它不仅能够以简洁的WEB报告形式显示已测试的内容,并带有失败用例截图、测试步骤和测试说明信息,也可以集成到Jenkins上展示高大上的报告界面。

而且允许参与开发过程的每个人从测试的日常执行中提取最大限度的有用信息。

Allure框架支持的语言包括:

  • Java
  • Python
  • JavaScript
  • Ruby
  • Groovy
  • PHP
  • .Net
  • Scala

Allure帮助文档:

(2)Allure框架的使用

步骤1:下载Allure框架,并配置到环境变量中。

Allure框架下载地址:https://github.com/allure-framework/allure2/releases

点击下图位置,进行下载。

image

然后解压Allure框架文件,放到自己指定的目录中。

Allure框架的bin目录配置到Path环境变量中。

image

步骤2:验证Allure框架是否安装成功。

使用命令:allure --version

需要在CMD命令行和PyCharm的Terminal中,都需要验证一下。

因为CMD可以验证通过,但是PyCharm中验证失败,如下:

J:\PyCharmWorkSpace\Pytest_d>allure --version
'allure' 不是内部或外部命令,也不是可运行的程序
或批处理文件。

解决方式:需要重启PyCharm。

步骤3:下载allure-pytest库(插件)。

执行安装命令:pip install allure-pytest

步骤4:设置生成的Json格式临时报告的存放位置。

配置pytest.ini文件,在pytest.ini全局配置文件中的addopts属性中添加:

--alluredir ../report/temp_jsonreport

例如:addopts = -vs --alluredir ../report/temp_jsonreport

然后我们执行测试用例就可以了,当然--alluredir参数也可以不配置在pytest.ini文件,比如在执行测试的命令行或者mian()函数中填写都可以。(主要是生成Json格式的测试报告,是多个Json文件)

提示:

  • 命令行参数:pytest --alluredir report,是在执行命令目录生成report文件夹,文件夹下包含xml文件。
  • pytest.ini文件中的生成报告的命令替换成--alluredir report,在命令行中运行pytest即可生成报告格式为Json格式,保存在项目文件的report文件夹中。

步骤5:生成Allure测试报告。

原理是:使用第一步下载的Allure框架把Json格式的测试报告,转换成精美的HTML测试报告。

将上面/report/temp_jsonreport文件夹中的Json格式的测试报告转化为HTML格式的测试报告。

执行命令:allure generate ./report/temp_jsonreport -o ./report/html --clean

注意:以执行命令的目录为相对路径。

说明:

  • allure generate: 固定命令。
  • ./report/temp_jsonreport:生成的Json格式的临时报告的路径。
  • -o:输出output
  • ./report/html:生成的Allure报告的路径。
  • --clean:清空./report/html路径中原来的Allure测试报告。

提示:main()函数中执行如上命令。

if __name__ == '__main__':
    pytest.main()
    os.system("allure generate ./report/temp_jsonreport -o ./report/html --clean")

# 或者直接用main函数调用,哪种方式都可以。
# (直接执行测试文件, 而不用pytest的方式执行,就可以执行)
pytest.main(["testCase_demo1.py","-sv","--alluredir","../report/temp_jsonreport"])
os.system("allure generate ./report/temp_jsonreport -o ./report/html --clean")

说明:找不到路径的话,可以在Python Console窗口调试。

最后,生成的Allure测试报告如下图:

image

提示:Allure测试报告支持自定义修改。

posted @ 2022-03-10 14:31  繁华似锦Fighting  阅读(497)  评论(0编辑  收藏  举报