I am using pytest framework and pytest-cov plugin to get the coverage report generated, which generates a coverage report file inside htmlcov directory after the test cases are executed, is there a way where I can also send this report file as an attachment while the test cases are executed?
Asked
Active
Viewed 1,924 times
1
-
What exactly do you mean by "while the test cases are executed"? You could generically use python's smtplib (https://docs.python.org/3/library/smtplib.html) to send an email of the html report after the execution is done. – Jack Thomson Mar 12 '20 at 04:14
-
@JackThomson I meant after the test cases are executed when the coverage Html report is generated, can I make a provision to send the generated report via mail, that when the test case are executed the coverage report is added as an attachment and sent via mail – Junior Mar 12 '20 at 05:16
1 Answers
3
You can put a teardown script in your conftest.py file. This is where you can put your pytest fixtures as well as generic pytest options. See the API reference here.
pytest_session_finish
is the function you're looking for. Your conftest.py
could look something like this. This heavily references this answer for the smtplib section with an attachment:
import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
def send_mail(send_from, send_to, subject, text, files=None,
server="127.0.0.1"):
assert isinstance(send_to, list)
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(MIMEText(text))
for f in files or []:
with open(f, "rb") as fil:
part = MIMEApplication(
fil.read(),
Name=basename(f)
)
# After the file is closed
part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
msg.attach(part)
smtp = smtplib.SMTP(server)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()
def pytest_sessionfinish(session, exitstatus):
send_mail('myemail', 'theiremail', 'Your Coverage Report', 'My Text',
files="coveragereport.html", server="myserver")

Jack Thomson
- 450
- 4
- 9