Efrin
Efrin

Reputation: 2423

Django tests - simulate that user is logged in

In my tests I have a following bit of code:

def setUp(self):
    self.client.defaults['HTTP_AUTHORIZATION'] = 'Basic ' + base64.b64encode(
        '{username}:{password}'.format(**self.login_data)
    )

def test_list_view(self):
    response = self.client.get(reverse('data_list'))
    self.assertEqual(response.status_code, 200)

My problem is that this check has to go through basic http authentication which uses ldap and it's pretty slow.

Is there a way I can simulate that user is logged in?

Upvotes: 1

Views: 1797

Answers (2)

simopopov
simopopov

Reputation: 852

You should create user because tests create test database (not your) everytime.

User.objects.create_user(username=<client_username>, password=<client_password>)

Now create Client and login

self.c = django.test.client.Client()
self.c.login(username=<client_username>, password=<client_password>)

Upvotes: 2

Mounir
Mounir

Reputation: 11726

You can override request headers for every client request like this example:

def test_report_wrong_password(self):
    headers = dict()
    headers['HTTP_AUTHORIZATION'] = 'Basic ' + base64.b64encode('user_name:password')
    response = self.client.post(
        '/report/',
        content_type='application/json',
        data=json.dumps(JSON_DATA),
        **headers)
    self.assertEqual(response.status_code, 401)

Upvotes: 0

Related Questions