软件测试中,pytest 运行完成后,如何自动发送邮件?

回答重点

在软件测试中,我们可以利用 pytest 和邮件发送库(例如 smtplib )结合,实现 pytest 运行完成后自动发送邮件的功能。主要思路是通过 pytest 的钩子函数 pytest_terminal_summary 来检测测试结果是否有错误或故障,然后利用 Python 的 smtplib 库编写发送邮件的逻辑。

具体步骤如下:

1)安装 pytest,如果还没有安装的话:

复制代码
pip install pytest

2)创建一个 conftest.py 文件,定义 pytest_terminal_summary 钩子函数,同时设置发送邮件的功能。下面是一个基本的实现示例:

复制代码
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def pytest_terminal_summary(terminalreporter, exitstatus, config):
    total = terminalreporter._numcollected
    passed = len(terminalreporter.stats.get('passed', []))
    failed = len(terminalreporter.stats.get('failed', []))
    errors = len(terminalreporter.stats.get('error', []))
    skipped = len(terminalreporter.stats.get('skipped', []))

    body = f"""
    Testing Summary:
    Total: {total}
    Passed: {passed}
    Failed: {failed}
    Errors: {errors}
    Skipped: {skipped}
    """

    print(body)  # 选装步骤:打印在终端上

    send_email(subject="Pytest Results", body=body)

def send_email(subject, body):
    sender_email = "sender@example.com"
    receiver_email = "receiver@example.com"
    password = "your_password"

    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = subject

    msg.attach(MIMEText(body, 'plain'))

    with smtplib.SMTP_SSL("smtp.example.com", 465) as server:
        server.login(sender_email, password)
        server.sendmail(sender_email, receiver_email, msg.as_string())

3)在终端运行 pytest:

复制代码
pytest

扩展知识

不仅限于 pytest 的 pytest_terminal_summary ,我们还可以使用其他钩子函数进行更细粒度的控制,如 pytest_sessionstartpytest_sessionfinish ,它们分别在测试会话开始和结束时执行。

另外,需要注意到邮件发送过程中,可能会遇到各种安全和配置问题。例如,某些邮箱服务商会对第三方登录作限制,需要加上专用密码或调整安全设置。对于更加复杂邮件内容(如带附件、富文本),可以使用 MIMEImageMIMEApplication 等。

我们也可以利用 pytest 插件如 pytest-html 生成测试报告,并将生成的 HTML 报告作为附件发送。在企业环境下,这样做会使得报告更直观,方便大家查看和分析。

相关推荐
weixin_580614003 小时前
如何提取SQL日期中的年份_使用YEAR或EXTRACT函数
jvm·数据库·python
2301_813599553 小时前
SQL生产环境规范_数据库使用最佳实践
jvm·数据库·python
李可以量化3 小时前
QMT 量化实战:用 Python 实现线性回归通道,精准识别趋势中的支撑与压力(下)
python·qmt·量化 qmt ptrade
a9511416423 小时前
Go 中通过 channel 传递切片时的数据竞争与深拷贝解决方案
jvm·数据库·python
Dxy12393102163 小时前
Python 使用正则表达式将多个空格替换为一个空格
开发语言·python·正则表达式
qq_189807033 小时前
如何修改RAC数据库名_NID工具在集群环境下的改名步骤
jvm·数据库·python
zhangchaoxies4 小时前
如何检测SQL注入风险_利用模糊测试技术发现漏洞
jvm·数据库·python
Luca_kill4 小时前
MCP数据采集革命:从传统爬虫到智能代理的技术进化
爬虫·python·ai·数据采集·mcp·webscraping·集蜂云
zhangchaoxies4 小时前
CSS如何实现响应式弹性网格布局_配合media query修改flex-wrap属性
jvm·数据库·python
故事和你915 小时前
洛谷-数据结构1-1-线性表1
开发语言·数据结构·c++·算法·leetcode·动态规划·图论