结合 pytest
和 Allure
可以生成详细而美观的测试报告,帮助测试人员和开发者更好地理解测试结果。这包括测试的执行情况、步骤、附件(如截图)、分类以及优先级标记。下面是如何在 pytest
中使用 Allure
生成测试报告的步骤:
安装 Allure 和相关插件
安装
pytest
和pytest-allure-adaptor
:pip install pytest pip install allure-pytest
安装 Allure 命令行工具:
- 根据操作系统,从 Allure releases 下载最新的 Allure 命令行工具,并进行安装。
- 确保将 Allure 的
bin
目录添加到环境变量PATH
中。
编写测试代码
在测试函数中,你可以使用 Allure 的 API 来定义测试步骤、附件等。
import pytest
import allure
@allure.feature("Feature1")
@allure.story("Story1")
@allure.step("Test the addition functionality")
def test_addition():
assert 1 + 1 == 2
@allure.step("Test the subtraction functionality")
def test_subtraction():
with allure.step("Perform subtraction"):
result = 5 - 2
allure.attach(str(result), name="result", attachment_type=allure.attachment_type.TEXT)
assert result == 3
运行测试并生成报告
运行测试生成结果文件:
- 使用
pytest
运行测试,并将结果输出到指定目录:
pytest --alluredir=./allure-results
上述命令会在项目目录下生成一个
allure-results
文件夹,包含测试结果。- 使用
生成并查看 Allure 报告:
- 使用 Allure 命令行工具生成 HTML 格式报告,并启动本地服务器查看:
allure serve ./allure-results
该命令会在本地启动一个服务器并自动打开浏览器查看报告。
报告内容
- 功能 (Feature) 和故事 (Story): 可以对测试进行功能和故事层面的分类。
- 步骤 (Step): 详细记录测试的各个步骤,协助问题定位。
- 附件 (Attachment): 自动将相关的上下文、输出信息等附加到报告中。
额外配置
标记和等级: 可以使用
allure.label
将测试标记为重要级别或其他。常用标签包括severity
(阻止插件、关键、正常等等)。测试分类和分组: 使用
pytest.mark
提供的功能在测试全局范围内定义更复杂的标签和分组。
通过 pytest
和 Allure 的结合,你能够生成全面而细致的测试报告,使得不仅能看到测试结果,还能帮助团队诊断问题,了解测试覆盖情况,便于测试改进与分析。