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:
Get hands-on with 1400+ tech skills courses.