在Django中测试用户注销失败
我需要测试我的用户是否正确注销。当我尝试注销时,测试失败。
def test_user_logout(self):
"""Test user logout."""
user = User.objects.create_user(username="test", password="test")
self.logged_in = self.client.force_login(user=user)
response = self.client.post(path=reverse("logout"), follow=True)
self.assertEqual(response.status_code, 200)
self.assertRedirects(response, reverse("login"))
self.assertTrue(user.is_anonymous) # this fails
我的查看方法是:
def user_logout(request):
logout(request)
return redirect("login")
I need to test if my user is logged out correctly. When I tried to logout, the test fails.
def test_user_logout(self):
"""Test user logout."""
user = User.objects.create_user(username="test", password="test")
self.logged_in = self.client.force_login(user=user)
response = self.client.post(path=reverse("logout"), follow=True)
self.assertEqual(response.status_code, 200)
self.assertRedirects(response, reverse("login"))
self.assertTrue(user.is_anonymous) # this fails
My view method is:
def user_logout(request):
logout(request)
return redirect("login")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果用户已登录(在任何会话中),则
User
对象不会保留。登录是面向会话,而不是面向用户,因此这意味着对于给定会话,如果会话变量引用用户,则您已登录。因此,一个用户
可以同时在多个会话中登录。对于
用户
模型[Django-doc] 对象,is_authenticated
[Django-doc] 始终为True
,并且is_anonymous
[Django-doc]将始终为False
,无论是否有任何会话 但是 Django已经有一个
LogoutView
视图[Django-doc]。 Django 开发人员有责任有效地测试此视图。因此,您的logout_view
可以替换为该视图。您可以设置LOGOUT_REDIRECT_URL
设置[Django-doc]
为:
然后使用
LogoutView.as_view()
在 url 中作为视图注销。通常最好使用 Django 已经实现的逻辑组件,这将实现、测试、维护和错误修复的负担从您转移到 Django 开发人员身上,并且由于很多用户使用这些视图,因此很可能会出现错误将更有效地检测和修复。
A
User
object does not hold if that user is logged in (in any session). Logged in is session-oriented, not user-oriented, so that means that for a given session you are logged in, if the session variables refer to a user. AUser
can thus be logged in in multiple sessions at the same time.For a
User
model [Django-doc] object,is_authenticated
[Django-doc] will always beTrue
, andis_anonymous
[Django-doc] will always beFalse
, regardless whether there is any session where you have logged in.Django however has already a
LogoutView
view [Django-doc]. It is the responsibility of the developers of Django to test this view effectively. Yourlogout_view
can thus be replaced with this view. You can set theLOGOUT_REDIRECT_URL
setting [Django-doc] to:and then use
LogoutView.as_view()
in the urls as view to log out.Usually it is better to work with logical components that are already implemented by Django, this moves the burden of implementing, testing, maintaining and bugfixing from you to the Django developers, and since a lot of users use these views, it is likely that mistakes will be detected and fixed more effectively.