Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, run test, send email if it fails

Tags:

python

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.

like image 849
Viacheslav Avatar asked Jan 30 '14 13:01

Viacheslav


People also ask

Is it possible to run Python mytest without sending off emails?

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 ()

How do I send emails using SMTP in Python?

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.

What does “this message is from Python” mean?

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.

Is it possible to automate sending emails with Python?

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


2 Answers

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)
like image 167
GabiMe Avatar answered Oct 23 '22 03:10

GabiMe


You can override run() method of unittest.TestSuite/TestCase to notify test result via email or any other channels. Check these out:

  • http://docs.python.org/2/library/unittest.html#unittest.TestSuite.run
  • http://docs.python.org/2/library/unittest.html#unittest.TestResult
like image 37
yoloseem Avatar answered Oct 23 '22 03:10

yoloseem