在之前的文章中,我们讨论了如何使用Pytest-BDD框架、Selenium和Requests库来统一UI和接口自动化测试,同事利用Gherkin语音编写测试用例,还有日志工具、断言工具的封装。本文将进一步介绍如何生成测试报告,和怎样去管理运行测试。
测试报告
测试报告的生成,我们主要讲三种方法:
-
使用pytest的插件
pytest-html
-
使用第三方库
Allure
-
自定义测试报告
pytest-html
安装
pip install pytest-html
在pytest命令中使用
运行测试时,通过指定插件选项来生成报告。比如,使用 pytest-html
生成报告的命令如下:
pytest --html=report.html
这里会在当前目录下生成一个名为 report.html
的测试报告文件,报告中会包含测试用例的执行情况、结果、时间等详细信息
Allure
Allure
是一个功能强大的测试报告框架,可以与 pytest-bdd
结合使用来生成美观且详细的测试报告。
首先,安装 allure-pytest
插件:
pip install allure-pytest
在运行测试时,添加 --alluredir
选项指定报告生成的目录。例如:
pytest --alluredir=allure_results
然后,你可以使用 allure
命令来生成最终的报告文件并查看报告。例如,在命令行中进入到项目目录,执行以下命令:
allure serve allure_results
自定义测试报告
在项目根目录下,创建conftest.py文件,使用pytest的钩子函数来实现。每执行一次用例,钩子函数会获取执行结果,根据执行结果来封装自己的测试报告。
import pytest
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
# 执行默认的钩子
outcome = yield
report = outcome.get_result()
返回的report中,包含了测试结果信息,根据report的数据,来封装自己的测试报告。
运行测试
通过标记(Marks)自定义执行
在pytest - bdd
中,可以使用pytest
的标记功能来标记特定的功能(Feature)、场景(Scenario)或者步骤(Step)。
例如,在.feature
文件中:
@slow
Feature: Slow Feature
Scenario: Slow Scenario
Given some condition
Then some result
这里使用了@slow
标记来标记一个功能。在对应的步骤定义文件中,可以对相关的步骤函数也进行标记:
import pytest
from pytest_bdd import given, then
@pytest.mark.slow
@given('some condition')
def some_condition():
pass
@pytest.mark.slow
@then('some result')
def some_result():
pass
可以在运行pytest
时,使用-m
选项来根据标记选择执行特定的测试。例如,只执行被标记为slow
的测试:
pytest -m slow
自定义命令行选项
在conftest.py
文件中,可以使用pytest_addoption
钩子函数来定义自定义的命令行选项。
例如,定义一个选项来指定执行特定类型的功能:
def pytest_addoption(parser):
parser.addoption("--feature - type", action="store", default=None, help="Specify the type of feature to execute")
发送测试报告
以下是一个使用 Python 发送测试报告的邮件的示例代码:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
# 邮件配置信息
sender_email = "your_email@gmail.com"
receiver_email = "recipient_email@gmail.com"
password = "your_password"
subject = "Allure Test Report"
body = "Please find attached the Allure test report."
# 附件路径(Allure 报告生成的目录中的 index.html 文件)
attachment_path = "results/index.html"
# 创建一个带附件的邮件对象
msg = MIMEMultipart()
msg["From"] = sender_email
msg["To"] = receiver_email
msg["Subject"] = subject
msg.attach(MIMEText(body, "plain"))
# 添加附件
with open(attachment_path, "rb") as attachment:
part = MIMEApplication(attachment.read(), Name="index.html")
part["Content-Disposition"] = f'attachment; filename="{attachment_path}"'
msg.attach(part)
# 发送邮件
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, msg.as_string())
print("Email sent successfully!")
except Exception as e:
print(f"Error sending email: {e}")
finally:
server.quit()