2
使用Django 1.7和Python 2.7。如何在Django中测试send_mail?
我想测试邮件是否被发送以及邮件的内容是否正确。
我试过使用从django.core.mail发件箱,但无济于事。 也可以只是得到stdout(因为我可以在运行我的测试时看到控制台中的邮件)?
models.py
class User(AbstractBaseUser, PermissionsMixin):
USERNAME_FIELD = 'email'
email = models.EmailField(max_length=255, unique=True)
is_staff = models.BooleanField(default=False)
org = models.ForeignKey('Org', null=True, blank=True,
on_delete=models.SET_NULL)
def __unicode__(self):
return self.email
@staticmethod
def send_password_token(email):
user = get_object_or_404(User, email=email)
token = Token.objects.get(user=user)
message_body = 'Your password reset token:\n\n\t%s' % token.key
send_mail('Password reset:', message_body,
settings.FROM_EMAIL, [email], fail_silently=False)
tests.py
class UserModelTest(TestCase):
def setUp(self):
self.user = User.objects.create_user(email='[email protected]',
password='0000')
@override_settings(EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend')
def test_send_password_token(self):
"""
Sends a password reset mail with users authentication token.
"""
token = Token.objects.get(user=self.user)
User.send_password_token(self.user.email)
你见过[在docs示例](https://docs.djangoproject.com/en/1.9/topics/testing/tools/#email-services)?你应该删除'override_settings'装饰器。然后,Django将自动使用'locmem'电子邮件后端并将电子邮件放入发件箱供您检查。 – Alasdair
当您使用控制台后端时,邮件只会被发送到标准输出,并且不能从django.core.mail邮箱使用。使用locmem后端。 https://docs.djangoproject.com/en/1.9/topics/email/#in-memory-backend –