我在测试中捕获异常时遇到问题。我知道引发异常的事实(我可以在Celery终端中看到我的自定义错误消息)。
发送确认邮件时出错:[Errno 111]拒绝连接
如何在测试中捕获该异常?
tests.py
from socket import error as socket_error
def test_email_sent(self):
"""
Checks if the email was sent.
"""
with self.assertRaises(socket_error):
self.newsletter.send(self.request)
models.py
class Newsletter(models.Model):
...
def send(self, req):
newsletter_mail.delay(params)
self.save()
tasks.py
from celery import Celery
from .utils import htmlmail
from socket import error as socket_error
app = Celery('newsletter.tasks', broker='redis://localhost/')
@app.task
def newsletter_mail(title, user, ctx, template, images, ignore_result=True):
try:
htmlmail(title, user, ctx, template, images)
except socket_error as serror:
print 'Error sending confirmation mail: ' + str(serror)
utils.py
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
charset='utf-8'
smtp_server = settings.EMAIL_HOST
smtp_user = settings.EMAIL_HOST_USER
smtp_pass = settings.EMAIL_HOST_PASSWORD
def htmlmail(sbj,recip,msg,template='',texttemplate='',textmsg='',images=(), recip_name='',sender=settings.DEFAULT_FROM_EMAIL,sender_name=settings.DEFAULT_FROM_SENDER_NAME,charset=charset):
...
if settings.EMAIL_BACKEND == "django.core.mail.backends.smtp.EmailBackend":
smtp = SMTP()
smtp.connect(smtp_server)
if smtp_user: smtp.login(smtp_user, smtp_pass)
smtp.sendmail(sender, recip, msgRoot.as_string())
smtp.quit()
else:
print "Email for:", recip
print text
def render(context,template):
if template:
t = loader.get_template(template)
return t.render(Context(context))
return context
def named(mail,name):
if name: return '%s <%s>' % (name,mail)
return mail
回溯:
[2015-12-04 15:10:22,970: ERROR/MainProcess] Task newsletter.tasks.newsletter_mail[a68161d1-919d-4a9f-90d5-6359d42ccb83] raised unexpected: error(111, 'Connection refused')
Traceback (most recent call last):
File "/home/sasa/.virtualenvs/konceptich2/local/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task
R = retval = fun(*args, **kwargs)
File "/home/sasa/.virtualenvs/konceptich2/local/lib/python2.7/site-packages/celery/app/trace.py", line 438, in __protected_call__
return self.run(*args, **kwargs)
File "/home/sasa/Projects/konceptich2/web/newsletter/tasks.py", line 10, in newsletter_mail
htmlmail(title, user, ctx, template, images)
File "/home/sasa/Projects/konceptich2/web/newsletter/utils.py", line 75, in htmlmail
smtp.connect(smtp_server)
File "/usr/lib/python2.7/smtplib.py", line 316, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python2.7/smtplib.py", line 291, in _get_socket
return socket.create_connection((host, port), timeout)
File "/usr/lib/python2.7/socket.py", line 571, in create_connection
raise err
error: [Errno 111] Connection refused