#test_sample.py
import requests
def test_api_1():
"""测试第一个接口,检查状态码是否为 200"""
response = requests.get('https://jsonplaceholder.typicode.com/todos/1')
assert response.status_code == 200
#conftest.py
def test_api_2():
"""测试第二个接口,检查状态码是否为 200"""
response = requests.get('https://jsonplaceholder.typicode.com/todos/2')
assert response.status_code == 200
def pytest_terminal_summary(terminalreporter, exitstatus, config):
"""
pytest_terminal_summary 钩子函数,在测试结束后执行,用于统计测试结果并生成报告
:param terminalreporter: pytest 的终端报告对象,包含了测试结果的相关信息
:param exitstatus: 测试的退出状态码
:param config: pytest 的配置对象
"""
# 获取测试结果统计信息
stats = terminalreporter.stats
# 统计测试用例总数
total = sum(len(stats[key]) for key in stats)
# 统计通过的测试用例数量
passed = len(stats.get('passed', []))
# 统计失败的测试用例数量
failed = len(stats.get('failed', []))
# 计算通过率
pass_rate = passed / total * 100 if total > 0 else 0
# 打印测试报告
print("\n自定义测试报告:")
print("-" * 30)
print(f"测试用例总数: {total}")
print(f"通过数: {passed}")
print(f"失败数: {failed}")
print(f"通过率: {pass_rate:.2f}%")
print("-" * 30)
#run_test.py
import pytest
if __name__ == "__main__":
# 指定 HTML 报告的保存路径和文件名
html_report_path = "test_report.html"
# 调用 pytest 的 API 来执行测试,并生成 HTML 报告
pytest.main(["test_sample.py", f"--html={html_report_path}"])
# 打印 HTML 报告的链接信息
print(f"\n测试完成,你可以通过以下链接查看详细的 HTML 测试报告:")
print(f"file://{html_report_path}")