Not allowed in unittest
I have a page with a login_required
decorator that I want to check if the correct template is being used. On stackoverflow I found an authorization method for unit test, but it doesn't work for me for some reason. Here's my test:
from django.test import TestCase
from django.test import Client
import base64
class TestUsingCorrectTemplates(TestCase):
def test_correct_classroom_template_used(self):
auth_headers = {'HTTP_AUTHORIZATION': 'Basic '+base64.b64encode('admin@dot.com:admin')}
c = Client()
response = c.get('/classroom/', **auth_headers)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response,'classroom.html')
Also would like to mention that authorization handled with OpenId / AllAuth and no page exists /login
, user logs into start page/
The content of the variable is as response
follows:
Vary: Cookie
X-Frame-Options: SAMEORIGIN
Content-Type: text/html; charset=utf-8
Location: http://testserver/?next=/classroom/
Test error:
self.assertEqual(response.status_code, 200)
AssertionError: 302 != 200
What am I doing wrong?
source to share
HTTP code 302 means that your server is sending a redirect response. You have to inform your client of the redirect to deal with the actual login page. You can change your call get
like this:
response = c.get('/classroom/', follow=True, **auth_headers)
If you want to check the intermediate redirect steps you can check response.redirect_chain
. All of this is documented here .
source to share
Have you tried creating a user and calling a method onlogin
your instance Client
?
import base64
from django.test import TestCase
class TestUsingCorrectTemplates(TestCase):
def setUp(self):
# Create your user here
# self.user = ...
def test_correct_classroom_template_used(self):
self.client.login('admin@dot.com', 'admin')
response = self.client.get('/classroom/') # XXX: You should use url reversal here.
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'classroom.html')
source to share