Configuring the Client for Testing with Pytest and Django REST
I am a software engineer with 4 years of professional experience, currently specializing in full-stack development.
I work a lot with HTML, CSS, JavaScript, and Python and regularly use React, Vue, and Django to build single-page applications and marketing landing pages.
I also work with React Native to build mobile applications with optimized experiences and for businesses who want to ship products in the market quickly.
Currently, I am a part of a team of 8 as a full-stack engineer where I focus on accessibility, component-driven approaches, and building systems that can scale with ease.
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()
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)
Article posted using bloggu.io. Try it for free.




