我有一个页面和测试类,测试类如下所示
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--自包含-html时,它会生成报告,但我想做的是在测试失败时给报告发电子邮件,我可以设置一些stmp,或者如果有一个包可以使用,这将是有帮助的。
发布于 2022-10-04 21:42:31
在这种情况下,conftest.py的完整代码如下所示:
conftest.py
import pytest
import smtplib
import ssl
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
failed: bool = False
def send_email():
"""
function to send an email with attachment after all test are run and a failure was detected
"""
subject: str = "subject"
body: str = "body"
sender_email: str = "email"
receiver_email: str = "email"
password: str = "password" # Recommended for mass emails# This should obviously be an input or some other stronger protection object other than a string
smtp: str = "smtp"
filename: str = "result.html"
port: int = 587
# Attachments need to be multipart
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message["Bcc"] = receiver_email
# Add body to email
message.attach(MIMEText(body, "plain"))
# Open html file in binary mode
# This will only work if HTML file is located within the same dir as the script
# If it is not, then you will need to modify this to the right path
with open(filename, "rb") as attachment:
# Add file as application/octet-stream
# Email client can usually download this automatically as attachment
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
# Encode file in ASCII characters to send by email
encoders.encode_base64(part)
# Add header as key/value pair to attachment part
part.add_header(
"Content-Disposition",
f"attachment; filename= {filename}",
)
# Add attachment to message and convert message to string
message.attach(part)
text = message.as_string()
# Log in to server using secure context and send email
context = ssl.create_default_context()
with smtplib.SMTP(smtp, port) as server:
server.starttls(context=context)
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, text)
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
global failed
report = yield
result = report.get_result()
if result.when == 'call' and result.outcome == "failed":
failed = True
print("FAILED")
def pytest_sessionfinish(session, exitstatus):
if failed is True:
send_email()
该文件中有两个关键功能。
pytest_runtest_makereport将在每个测试之后运行,只需检查测试是否失败。如果任何测试失败,那么failed
标志将被设置为True。
然后,在整个脚本的末尾,pytest_session将运行并检查是否将标志更改为True。如果是的话,就会发送一封电子邮件,并附上result.html文件。
我想强调这部分问题之前已经回答过了,请参阅下面的链接:How to send pytest coverage report via email?
给定链接的问题/答案不包含任何关于如何只在测试失败时运行的信息。我决定在这里回答是值得的。
https://stackoverflow.com/questions/73887692
复制相似问题