如何测试邮件确认?

How to test email confirmation?

我正在尝试使用 django-rest-auth 测试电子邮件确认视图。 这是我拥有的:

def test_verify_email(self):
    # Verify email address
    username = 'userTest'
    payload = {
        'email': 'test@example.com',
        'password1': 'TestpassUltra1',
        'password2': 'TestpassUltra1',
        'username': username,
    }
    res = self.client.post(REGISTER_USER_URL, payload)

    self.assertEqual(res.status_code, status.HTTP_201_CREATED)
    user = get_user_model().objects.get(email='test@example.com')
    # TODO retrieve the confirmation key from the user
    resp = self.client.post(VERIFY_USER_URL, {'key': ''})
    self.assertEqual(resp.status_code, status.HTTP_200_OK)

self.client.post(REGISTER_USER_URL, payload) 将发送一封包含确认码的电子邮件,虽然我知道我可以在代码中使用 django.core.mail.outbox 检索该代码,但我宁愿不这样做,因为我将不得不解析电子邮件内容以查找确认代码(如果电子邮件更改,这可能会终止我的测试)。我在数据库的任何地方都找不到这段代码,它似乎只存在于发送的电子邮件正文中。

我的问题是:是否可以在不解析邮件的情况下在我的测试中恢复此验证码?我只想取回它来启动我的 self.client.post(VERIFY_USER_URL, {'key': ''})

以下是电子邮件内容的示例:

Hello from example.com!

You're receiving this e-mail from NomadSpeed because user detro1 has given yours as an e-mail address to connect their account.

To confirm this is correct, go to http://127.0.0.1:8000/registration/account-confirm-email/Mg:1hmqdS:J-2jGV028nd4qZQ3lPmFgXGFhsM/

Thank you from example.com!
example.com

我需要的是Mg:1hmqdS:J-2jGV028nd4qZQ3lPmFgXGFhsM。 谢谢。

我认为解决这个问题的最佳方法是使用正则表达式来匹配预期的 link,然后从中解析您想要的位。担心电子邮件的更改可能会破坏测试是公平的,但在这种情况下,您正在测试电子邮件中的 link 是否有效,如果这在某些方面发生了变化方式,也许它应该打破你的测试。如果您更改其他一些文本,如问候语、介绍等,它不会影响您的 link 和令牌的正则表达式。

无论如何,我将如何构建该测试:

import re

def test_verify_email(self):
    # Verify email address
    username = 'userTest'
    payload = {
        'email': 'test@example.com',
        'password1': 'TestpassUltra1',
        'password2': 'TestpassUltra1',
        'username': username,
    }
    response = self.client.post(REGISTER_USER_URL, payload)
    self.assertEqual(response.status_code, status.HTTP_201_CREATED)
    user = get_user_model().objects.get(email='test@example.com')

    # Get token from email
    token_regex = r"registration\/account-confirm-email\/([A-Za-z0-9:\-]+)\/"
    email_content = django.core.mail.outbox[0].body
    match = re.search(token_regex, email_content)
    assert match.groups(), "Could not find the token in the email" # You might want to use some other way to raise an error for this
    token = match.group(1)

    # Verify 
    response = self.client.post(VERIFY_USER_URL, {'key': token})
    self.assertEqual(response.status_code, status.HTTP_200_OK)

您甚至可以断言 link 的路径的正确性,因此如果有人更改了 link 您将有一个失败的测试表明某些东西可能会损坏。