如何通过pytest或其他Python包自动邮件发送测试失败报告?
需求说明
我有一个测试页面和如下测试类:
import unittest import pytest import logging @pytest.mark.usefixtures("setup") class BigRandomTest(unittest.TestCase): log = cl.testogger(logging.DEBUG) @pytest.fixture(autouse=True) def classSetup(self): self.synMax = CarMaxSyndicated() # Standard set of tests @pytest.mark.run(order=1) def test_column_uniqueness_dealership(self): pass self.log.debug('List of all column duplicate counts: \n' + str(result[1])) assert result[0].empty, 'Test failed. Columns with a suspect amount of duplicates: \n {}'.format(result[0]) @pytest.mark.run(order=2) def test_column_uniqueness_consistency_dealership(self): pass self.log.debug('List of all column duplicates differences: \n' + str(result[1])) assert result[0].empty, 'Test failed. Columns with significantly different duplicate counts between collections: \n {}'.format(result[0])
执行命令pytest -s -v path_to_test --html=result.html --self-contained-html可生成测试报告,现需实现仅在测试失败时自动发送该报告邮件,支持SMTP配置或使用合适的Python工具包。
解决方案
方法一:自定义pytest钩子 + 原生SMTP实现
通过pytest的pytest_sessionfinish钩子判断测试结果,仅在失败时触发邮件发送逻辑。
- 在项目根目录创建
conftest.py文件,添加以下代码:
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders import pytest # SMTP配置项 SMTP_SERVER = "smtp.example.com" SMTP_PORT = 587 SMTP_USER = "your_email@example.com" SMTP_PASSWORD = "your_password" TO_EMAILS = ["recipient1@example.com", "recipient2@example.com"] EMAIL_SUBJECT = "Pytest测试失败报告" @pytest.hookimpl(tryfirst=True) def pytest_sessionfinish(session, exitstatus): # exitstatus不为0表示存在测试失败 if exitstatus != 0: send_test_report_email() def send_test_report_email(): # 构建邮件主体 msg = MIMEMultipart() msg['From'] = SMTP_USER msg['To'] = ", ".join(TO_EMAILS) msg['Subject'] = EMAIL_SUBJECT # 邮件正文内容 body = "本次Pytest测试出现失败,附件为测试报告,请查看。" msg.attach(MIMEText(body, 'plain')) # 添加测试报告附件 filename = "result.html" with open(filename, "rb") as attachment: part = MIMEBase('application', 'octet-stream') part.set_payload(attachment.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', f"attachment; filename= {filename}") msg.attach(part) # 发送邮件 try: server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) server.starttls() server.login(SMTP_USER, SMTP_PASSWORD) server.sendmail(SMTP_USER, TO_EMAILS, msg.as_string()) server.quit() print("测试失败报告邮件已发送") except Exception as e: print(f"邮件发送失败: {str(e)}")
- 正常执行原pytest命令即可,当有测试失败时会自动触发邮件发送。
方法二:使用第三方库pytest-mail
借助封装好的第三方库简化邮件发送逻辑,仅需配置命令行参数即可实现失败触发。
- 安装依赖库:
pip install pytest-mail
- 执行pytest命令时添加邮件配置参数:
pytest -s -v path_to_test --html=result.html --self-contained-html \ --mail-host=smtp.example.com --mail-port=587 \ --mail-user=your_email@example.com --mail-password=your_password \ --mail-to=recipient1@example.com,recipient2@example.com \ --mail-subject="Pytest测试失败报告" \ --mail-on-failure
其中--mail-on-failure参数指定仅在测试失败时发送报告邮件。
注意事项
- 若使用Gmail、Outlook等公共邮箱,需使用对应平台的应用专用密码而非登录密码;
- 确保测试报告文件
result.html生成在执行命令的当前工作目录下; - 企业邮箱需确认SMTP服务器地址、端口及认证方式是否符合要求。
内容的提问来源于stack exchange,提问作者Ronron
相关产品推荐
相关产品推荐

