我想运行一个测试,如果测试失败,则发送电子邮件。 请问是否可以使用任何传统的框架(如 UnitTest)来实现此操作。但我尚未找到在测试失败时修改其行为的方法。
我想运行一个测试,如果测试失败,则发送电子邮件。 请问是否可以使用任何传统的框架(如 UnitTest)来实现此操作。但我尚未找到在测试失败时修改其行为的方法。
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)
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
是包含我的测试的文件夹的名称。
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"
unittest.TestSuite
/TestCase
的 run()
方法,通过电子邮件或其他渠道通知测试结果。请查看以下内容:
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())
你可以使用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()