Django测试返回登录重定向302,即使用户已登录 [英] Django tests returning login redirect 302, even though user is logged in

查看:76
本文介绍了Django测试返回登录重定向302,即使用户已登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于如何测试需要登录的页面,我感到非常困惑.我的响应始终是302而不是200,在检查pdb中的响应时,我肯定会重定向到登录页面.如果相关的话,我正在使用登录中间件而不是装饰器.

I'm extremely confused as to how to test pages that require a login. I keep getting a 302 instead of a 200 in my response, and in inspecting the response in pdb I am definitely redirecting to a login page. I am using login middleware instead of the decorator, if that's relevant.

class SimplePageLoadsTestCase(TestCase):

    def setUp(self):
        self.client = Client()
        self.user = User.objects.create_user('test_user')
        self.client.login(username='test_user', password='test_user')

    def test_login(self):
        self.assertTrue(self.user.is_authenticated())

    def test_index(self):
        self.client.login(username='test_user', password='test_user')
        response = self.client.get(reverse('index'))
        self.assertEqual(response.status_code, 200)

test_login 测试通过.我不确定是否需要通过每次测试重新登录用户(我认为不需要,因为我不需要 test_login ,但是我已经尝试过使用相同的方法结果.我在视图中添加了一些打印语句,但它们没有输出,所以我知道我根本不会像我所怀疑的那样击中视图.

The test_login test passes. I wasn't sure whether or not I needed to re-login the user per test (I think not, since I didn't need in test_login, but I've tried it both ways with the same result. I threw a few print statements in my view, and they do not output, so I know I'm not hitting the view at all, like I suspected.

我可以提供相关的视图或中间件.

I can provide the view or middleware if they're relevant.

我禁用了中间件,并用@login_required装饰器替换了中间件,并且有相同的问题.

I disabled the middleware and replaced it with the @login_required decorator, and had the same problem.

再次只是为了检查,我拿出了所有登录检查,一切正常(如我所料).因此,我对self.client根本不知道自己已登录表示肯定.

EDIT AGAIN: Just to check, I took out all login checks, and everything worked (as I expected). So I'm nearly positive that the self.client just doesn't know I've logged in.

推荐答案

您似乎不是无法登录.为 create_user 提供密码应该可以解决

It doesn't look like you are creating your user with a password. Without providing a password it is considered a user that cannot be logged in. Providing a password to create_user should fix it

self.client = Client()
self.user = User.objects.create_user('test_user', password='test_user')
self.client.login(username='test_user', password='test_user')

这篇关于Django测试返回登录重定向302,即使用户已登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆