我正在尝试为密码重置流程实施集成测试,但我仍然停留在“ password_reset_confirm ”视图中。我已经手动测试了流量,它工作正常。不幸的是,Django单元测试客户端似乎无法正确遵循此视图中所需的重定向。
from django.contrib.auth import views as auth_views
url(r"^accounts/password_change/$",
auth_views.PasswordChangeView.as_view(),
name="password_change"),
url(r"^accounts/password_change/done/$",
auth_views.PasswordChangeDoneView.as_view(),
name="password_change_done"),
url(r"^accounts/password_reset/$",
auth_views.PasswordResetView.as_view(email_template_name="app/email/accounts/password_reset_email.html",
success_url=reverse_lazy("app:password_reset_done"),
subject_template_name="app/email/accounts/password_reset_subject.html"),
name="password_reset"),
url(r"^accounts/password_reset/done/$",
auth_views.PasswordResetDoneView.as_view(),
name="password_reset_done"),
url(r"^accounts/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$",
auth_views.PasswordResetConfirmView.as_view(
success_url=reverse_lazy("app:password_reset_complete"),
form_class=CustomSetPasswordForm),
name="password_reset_confirm"),
url(r"^accounts/reset/complete/$",
auth_views.PasswordResetCompleteView.as_view(),
name="password_reset_complete"),
import re
from django.urls import reverse, NoReverseMatch
from django.test import TestCase, Client
from django.core import mail
from django.test.utils import override_settings
from django.contrib.auth import authenticate
VALID_USER_NAME = "username"
USER_OLD_PSW = "oldpassword"
USER_NEW_PSW = "newpassword"
PASSWORD_RESET_URL = reverse("app:password_reset")
def PASSWORD_RESET_CONFIRM_URL(uidb64, token):
try:
return reverse("app:password_reset_confirm", args=(uidb64, token))
except NoReverseMatch:
return f"/accounts/reset/invaliduidb64/invalid-token/"
def utils_extract_reset_tokens(full_url):
return re.findall(r"/([\w\-]+)",
re.search(r"^http\://.+$", full_url, flags=re.MULTILINE)[0])[3:5]
@override_settings(EMAIL_BACKEND="anymail.backends.test.EmailBackend")
class PasswordResetTestCase(TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.myclient = Client()
def test_password_reset_ok(self):
# ask for password reset
response = self.myclient.post(PASSWORD_RESET_URL,
{"email": VALID_USER_NAME},
follow=True)
# extract reset token from email
self.assertEqual(len(mail.outbox), 1)
msg = mail.outbox[0]
uidb64, token = utils_extract_reset_tokens(msg.body)
# change the password
response = self.myclient.post(PASSWORD_RESET_CONFIRM_URL(uidb64, token),
{"new_password1": USER_NEW_PSW,
"new_password2": USER_NEW_PSW},
follow=True)
self.assertIsNone(authenticate(username=VALID_USER_NAME,password=USER_OLD_PSW))
现在,断言失败:用户使用旧密码进行身份验证。从日志中我能够检测到未执行更改密码。
一些额外的有用信息:
post
会返回成功的HTTP 200
; response.redirect_chain
是[('/accounts/reset/token_removed/set-password/', 302)]
,我认为这是错误的,因为它应该有另一个循环(在手动情况下我看到另一个调度方法); 有关如何正确测试此方案的任何想法?我需要这个以确保电子邮件和日志记录正确执行(并且永远不会删除)。
非常感谢!
通过公认的解决方案解释,这里是测试用例的工作代码:
def test_password_reset_ok(self):
# ask for password reset
response = self.myclient.post(PASSWORD_RESET_URL,
{"email": VALID_USER_NAME},
follow=True)
# extract reset token from email
self.assertEqual(len(mail.outbox), 1)
msg = mail.outbox[0]
uidb64, token = utils_extract_reset_tokens(msg.body)
# change the password
self.myclient.get(PASSWORD_RESET_CONFIRM_URL(uidb64, token), follow=True)
response = self.myclient.post(PASSWORD_RESET_CONFIRM_URL(uidb64, "set-password"),
{"new_password1": USER_NEW_PSW,
"new_password2": USER_NEW_PSW},
follow=True)
self.assertIsNone(authenticate(username=VALID_USER_NAME,password=USER_OLD_PSW))
答案 0 :(得分:2)
这非常有趣;所以看起来Django在密码重置页面中实现了一个安全功能,以防止令牌泄露在HTTP Referrer header中。详细了解推荐人标题泄漏here.
Django基本上是从URL中获取敏感令牌并将其放入Session并执行内部重定向(同一域),以防止您点击其他站点并通过Referer标题。
/accounts/reset/uidb64/token/
(你应该在这里进行GET,但是你在测试用例中进行POST)时,Django第一次从URL中提取令牌并将其设置为session并重定向你到/accounts/reset/uidb64/set-password/
。 /accounts/reset/uidb64/set-password/
页面,您可以在其中设置密码并执行 POST token
URL参数可以处理令牌和字符串set-password
。 set-password
访问它而不是令牌,因此它希望从会话中提取您的实际令牌,然后更改密码。这里的流程如图:
获取
/reset/uidb64/token/
- &gt;在会话中设置令牌 - &gt; 302重定向到/reset/uidb64/set-token/
- &gt; POST密码 - &gt;从Session获取令牌 - &gt;令牌有效吗? - &GT;重置密码
以下是代码!
INTERNAL_RESET_URL_TOKEN = 'set-password'
INTERNAL_RESET_SESSION_TOKEN = '_password_reset_token'
@method_decorator(sensitive_post_parameters())
@method_decorator(never_cache)
def dispatch(self, *args, **kwargs):
assert 'uidb64' in kwargs and 'token' in kwargs
self.validlink = False
self.user = self.get_user(kwargs['uidb64'])
if self.user is not None:
token = kwargs['token']
if token == INTERNAL_RESET_URL_TOKEN:
session_token = self.request.session.get(INTERNAL_RESET_SESSION_TOKEN)
if self.token_generator.check_token(self.user, session_token):
# If the token is valid, display the password reset form.
self.validlink = True
return super().dispatch(*args, **kwargs)
else:
if self.token_generator.check_token(self.user, token):
# Store the token in the session and redirect to the
# password reset form at a URL without the token. That
# avoids the possibility of leaking the token in the
# HTTP Referer header.
self.request.session[INTERNAL_RESET_SESSION_TOKEN] = token
redirect_url = self.request.path.replace(token, INTERNAL_RESET_URL_TOKEN)
return HttpResponseRedirect(redirect_url)
# Display the "Password reset unsuccessful" page.
return self.render_to_response(self.get_context_data())
请注意代码中发生此魔法的评论:
将令牌存储在会话中并重定向到 密码重置表单在没有令牌的URL处。那 避免在令牌中泄漏令牌的可能性 HTTP Referer标题。
我认为这清楚地说明了如何修复单元测试;在PASSWORD_RESET_URL
上进行GET,它会为您提供重定向网址,然后您可以POST到此redirect_url并执行密码重置!