I want to run a test and if it fails, send an email. Please suggest can I do this with any conventional frameworks like UnitTest. I haven't found a way to modify its behavior when it fails.
That is, you can still run python mytest.py without sending off unnecessary emails, e.g. in your local dev environment. class MyTest (unittest.TestCase): def test_spam (self): ... self.assertTrue (condition) if __name__ == '__main__': unittest.main ()
Getting Started Python comes with the built-in smtplib module for sending emails using the Simple Mail Transfer Protocol (SMTP). smtplib uses the RFC 821 protocol for SMTP. The examples in this tutorial will use the Gmail SMTP server to send emails, but the same principles apply to other email services.
It takes in the source email address, destination email address, and the content of the email message to send. and “this message is from python” is the content of the email message. to terminate the connection between our client and the SMTP server.
Sending emails manually is a time-consuming and error-prone task, but it’s easy to automate with Python. Send emails with HTML content and attachments using the email package
You can provide your own unittest.TestResult implementation to send email like this:
import smtplib
import unittest
def sendmail(from_who, to, msg):
s = smtplib.SMTP('localhost')
s.sendmail(from_who, [to], msg)
s.quit()
class MyTestResult(unittest.TestResult):
def addError(self, test, err):
self.super(MyTestResult, self).addError(test, err)
err_desc = self._exc_info_to_string(err, test)
sendmail(from_who, to, err_desc)
def addFailure(self, test, err):
self.super(MyTestResult, self).addFailure(test, err)
err_desc = self._exc_info_to_string(err, test)
sendmail(from_who, to, err_desc)
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromModule()
results = MyTestResult()
suite.run(results)
You can override run()
method of unittest.TestSuite
/TestCase
to notify test result via email or any other channels. Check these out:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With