login() in Django testing framework

前端 未结 3 502
感动是毒
感动是毒 2021-02-01 02:15

I have started using Django\'s testing framework, and everything was working fine until I started testing authenticated pages.

For the sake of simplicity, let\'s say tha

3条回答
  •  忘了有多久
    2021-02-01 02:53

    The problem is that you're not passing RequestContext to your template.

    Also, you probably should use the login_required decorator and the client built in the TestCase class.

    I'd rewrite it like this:

    #views.py
    from django.contrib.auth.decorators import login_required
    from django.shortcuts import render
    from django.contrib.auth import get_user_model
    
    @login_required(login_url='/users/login')
    def secure(request):
        user = request.user
        return render(request, 'secure.html', {'email': user.email})
    
    
    
    #tests.py
    class SimpleTest(TestCase):
        def setUp(self):
            User = get_user_model()
            user = User.objects.create_user('temporary', 'temporary@gmail.com', 'temporary')
    
        def test_secure_page(self):
            User = get_user_model()
            self.client.login(username='temporary', password='temporary')
            response = self.client.get('/manufacturers/', follow=True)
            user = User.objects.get(username='temporary')
            self.assertEqual(response.context['email'], 'temporary@gmail.com')
    

提交回复
热议问题