使用Django 1.7和Python 2.7。
我想测试邮件是否已发送以及邮件内容是否正确。
我尝试过使用django.core.mail中的outbox,但无济于事。 我也可以获得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='user@info.com',
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)
答案 0 :(得分:9)
感谢@Alasdair提供的解决方案。事实证明这很简单。只需删除override_settings并导入发件箱即可。
tests.py
from django.core.mail import outbox
class UserModelTest(TestCase):
def setUp(self):
self.user = User.objects.create_user(email='user@info.com',
password='0000')
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)
self.assertEqual(len(outbox), 1)
self.assertEqual(outbox[0].subject, 'Password reset:')
self.assertEqual(outbox[0].from_email, <insert_from_email>)
self.assertEqual(outbox[0].to, [<insert_list_of_to_emails>])
self.assertEqual(outbox[0].body,
'Your password reset token:\n\n\t%s' % token.key)