我正在尝试使用 django-rest-auth 测试电子邮件确认 View 。 这是我所拥有的:
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 是否有效,如果这以某种方式发生变化,也许它应该破坏您的测试。如果您更改其他一些文本,例如问候语、介绍等,它不会影响您的链接和 token 的正则表达式。
无论如何,我将如何构建该测试:
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)
您甚至可以断言该链接路径的正确性,因此如果有人更改了该链接,您将有一个失败的测试表明某些东西可能会损坏。
关于django - 如何测试邮件确认?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57032616/