Python,运行测试,如果测试失败则发送电子邮件

6

我想运行一个测试,如果测试失败,则发送电子邮件。 请问是否可以使用任何传统的框架(如 UnitTest)来实现此操作。但我尚未找到在测试失败时修改其行为的方法。


2
您可以编写一个脚本,根据测试是否失败发送电子邮件。 - Simeon Visser
6个回答

5
你可以提供自己的unittest.TestResult实现来发送类似以下邮件的邮件:
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)

1
由于某种原因,@GabiMe的回答并没有完全适用于我。相反,我使用了以下内容:
def sendmail(from_who, to, msg):
    s = smtplib.SMTP('localhost')
    s.sendmail(from_who, [to], msg)
    s.quit()

class TestResults(unittest.TestResult):

    def addError(self, test, err):
        super(TestResults, self).addError(test, err)  
        error = self._exc_info_to_string(err, test)
        sendmail(from_who, to, err_desc)

    def addFailure(self, test, err):
        super(TestResults, self).addFailure(test, err)
        error = self._exc_info_to_string(err, test)
        sendmail(from_who, to, err_desc)

if __name__ == '__main__':

    suite = unittest.TestSuite(
        unittest.TestLoader().discover('tests')
    )
    results = TestResults()
    suite.run(results)

其中tests是包含我的测试的文件夹的名称。


1
你可以使用fabric来处理测试结果和发送电子邮件。这种方法的好处是,你可以保持单元测试不变。也就是说,在本地开发环境中,你仍然可以运行python mytest.py而不会发送不必要的电子邮件。
假设你有一个名为mytest.py的单元测试文件:
class MyTest(unittest.TestCase):
     def test_spam(self):
         ...
         self.assertTrue(condition) 

if __name__ == '__main__':
    unittest.main()

在你的fabfile.py中添加以下内容:
 def test(from_email="server@mydomain.com",
                 to_email="test@mydomain.com"):
    with settings(warn_only=True):
        result=local('python mytest.py', capture=True)
        if result.failed:
            # prepare message
            msg = MIMEText(result)
            msg['From'] = from_email
            msg['To'] = to_email
            msg['Subject'] = "Tests failed"
            # send email
            s = smtplib.SMTP('localhost')
            s.sendmail(from_email, [to_email], msg.as_string())

然后你可以简单地按照以下方式调用你的测试:
# send to default email address
fab test
# send to another email address
fab test:to_email="other@mydomain.com"

请在-1处进行评论,以便我改进答案。 - miraculixx

1

0
import smtplib

from email.mime.text import MIMEText

msg = MIMEText('todi si tho lift karade :P')

me = 'from_mail@gmail.com'

to = 'to_mail@gmail.com'

pswd = 'abcderfyqwerpokl'

#(if 2 factor-auth is active for your mail, visit https://myaccount.google.com/apppasswords select your app device and generate your  12 letter app password, Give those credentials to signin when you are writing the code)

msg['Subject'] = "lift_karade"

msg['From'] = me

msg['To'] = to

s = smtplib.SMTP('smtp.gmail.com', 587)

s.starttls()

s.login(me,pswd)

s.sendmail(me, [to], msg.as_string())

-2

你可以使用try, except块

import script

try:
   script()
except Exception, e:
   import smtplib
   from email.mime.text import MIMEText
   msg['Subject'] = 'Script failed!!'
   msg['From'] = me
   msg['To'] = you
   s = smtplib.SMTP('localhost')
   s.sendmail(me, [you], e.message)
   s.quit()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接