Authentication in Tests with DRF

Mangabo Kolawole - Apr 15 '22 - - Dev Community

Writing tests with Django and Django REST is made easier with the tools and classes provided.
And if you are writing tests to test the endpoints of your API, using the APIClient class from Django REST is a simple way to write the tests and make requests.

And if you are looking to test a protected resource, you can directly use the .login(**kwargs) method.

client = APIClient()
client.login(username='john', password='12345')
Enter fullscreen mode Exit fullscreen mode

And if you want to bypass the authentication process without having to provide a username or password, you can use the .force_authenticate(user=None)

user = User.objects.first()
client = APIClient()
client.force_authenticate(user=user)
Enter fullscreen mode Exit fullscreen mode

Article posted using bloggu.io. Try it for free.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player