Configuring the Client for Testing with Pytest and Django REST

koladev

Mangabo Kolawole

Posted on May 16, 2022

Configuring the Client for Testing with Pytest and Django REST

Django REST framework provides a class called APIClient based on the client class from the Django Testing but is very useful when making requests to the API when running tests.

If you have also worked with pytest, you'll find that writing tests are quite fun and very fast.

How do you use now use the testing client from DRF in your pytest tests when testing the API endpoints?

You need to add this piece of code to the conftest.py file.

import pytest
from rest_framework.test import APIClient

@pytest.fixture
def client():
    return APIClient()
Enter fullscreen mode Exit fullscreen mode

And you can call the client in your tests like this. I am using a class structure to run tests.

class TestUserViewSet:

    endpoint = '/api/user/'

    def test_list(self, client, user):
        client.force_authenticate(user=user)
        response = client.get(self.endpoint)
Enter fullscreen mode Exit fullscreen mode

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

πŸ’– πŸ’ͺ πŸ™… 🚩
koladev
Mangabo Kolawole

Posted on May 16, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related