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.
Top comments (0)