...

/

Writing Tests for Django Viewsets

Writing Tests for Django Viewsets

Write tests for the User, Post, and Comment viewsets using Pytest.

Viewsets or endpoints are the interfaces of the business logic that the external clients will use to fetch data and create, modify, or delete data. It’s always a great habit to have tests to make sure that the whole system, starting from a request to the database, is working as intended.

Before starting to write the tests, let’s configure the Pytest environment to use the API client from DRF.

The API client is a class that handles different HTTP methods, as well as features such as authentication in testing, which can be very helpful for directly authenticating without a username and password to test some endpoints. Pytest provides a way to add configurations in a testing environment.

Create a file named conftest.py at the root of the project. Inside the file, we’ll create a fixture function for our custom client:

Press + to interact
import pytest
from rest_framework.test import APIClient
@pytest.fixture
def client():
return APIClient()

Great! We can now directly call this client in the next tests.

Let’s start by testing the authentication endpoints.

Writing tests for authentication

Inside the core/auth directory, create a file named tests.py. Instead of writing test functions directly, we write a class that will contain the testing methods as follows:

Press + to interact
import pytest
from rest_framework import status
from core.fixtures.user import user
class TestAuthenticationViewSet:
endpoint = '/api/auth/'

Let’s add the test_login method to ...