</>
How to authenticate while testing Django REST Framework
Before I used to authenticate using the following method while testing DRF.
Afterwards, everything works as expected.
import unittestfrom django.contrib.auth import get_user_modelfrom django.test import TestCasefrom rest_framework import statusfrom rest_framework.test import APIClientUser = get_user_model()class ExampleTestCase(TestCase):def setUp(self):User.objects.create_user(username='test', password='test-pass')self.client = APIClient()self.client.login(username='test', password='test-pass')def test_some_api_endpoint(self):response = self.client.get(f'/api/jobs/')# check statusself.assertEqual(response.status_code, status.HTTP_200_OK)
However, there is more elegant solution that doesn't require you to come up with mocked passwords.
import unittestfrom django.contrib.auth import get_user_modelfrom django.test import TestCasefrom rest_framework import statusfrom rest_framework.test import APIClientUser = get_user_model()class ExampleTestCase(TestCase):def setUp(self):self.u1 = User.objects.create_user(username='test')self.client = APIClient()self.client.force_authenticate(self.u1)def test_some_api_endpoint(self):response = self.client.get(f'/api/jobs/')# check statusself.assertEqual(response.status_code, status.HTTP_200_OK)