Using Basic HTTP access authentication in Django testing framework
Here's how I did it:
from django.test import Clientimport base64auth_headers = { 'HTTP_AUTHORIZATION': 'Basic ' + base64.b64encode('username:password'),}c = Client()response = c.get('/my-protected-url/', **auth_headers)
Note: You will also need to create a user.
In your Django TestCase you can update the client defaults to contain your HTTP basic auth credentials.
import base64from django.test import TestCaseclass TestMyStuff(TestCase): def setUp(self): credentials = base64.b64encode('username:password') self.client.defaults['HTTP_AUTHORIZATION'] = 'Basic ' + credentials
For python3, you can base64-encode your username:password
string:
base64.b64encode(b'username:password')
This returns bytes, so you need to transfer it into an ASCII string with .decode('ascii')
:
Complete example:
import base64from django.test import TestCaseclass TestClass(TestCase): def test_authorized(self): headers = { 'HTTP_AUTHORIZATION': 'Basic ' + base64.b64encode(b'username:password').decode("ascii") } response = self.client.get('/', **headers) self.assertEqual(response.status_code, 200)