Python, run test, send email if it fails

python

Solution

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)

Problem

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.

Original source