Testing ViewSets with Fixtures using Django’s Test Suite (Example)

kelsey farnell
2 min readJan 8, 2020

--

Django version 3.0.2| djangorestframework version 3.11.0

Getting started

mkdir tutorial
cd tutorial
python3 -m venv env
source env/bin/activate
pip install django
pip install djangorestframework
django-admin startproject test_tutuorial
cd test_tutorial
django-admin startapp api

add ‘api’ and ‘restframework’ to /test_tutorial/settings.py

INSTALLED_APPS = [
...
'rest_framework',
'api'
]

Navigate to your test_tutorial folder that contains manage.py

cd test_tutorialpython manage.py migratepython manage.py createsuperuser

The Models

Here are my api/models.py for this example:

Put this in your api/admin.py:

___

The Serializer

Create a file: api/serializers.py

___

The ViewSet

api/views.py

___

test_tutorial/urls.py:

Create a file: api/urls.py:

___

Populate your database

python manage.py makemigrations
python manage.py migrate
python manage.py runserver

Navigate to http://127.0.0.1:8000/admin and use your superuser name and password to login to the admin panel. You should see ‘Dogs’, ‘Breeds’, and ‘BreedTypes’ there. Fill in with some data, for example:

Dogs
Breeds
Breed Types

You can also create these models via the command line, but it is easier to create them with the admin panel.

Create the Fixtures

cd tutorialmkdir fixturespython manage.py dumpdata api.dog > api/fixtures/dogs.json
python manage.py dumpdata api.breed > api/fixtures/breeds.json
python manage.py dumpdata api.breedtype > api/fixtures/breedtypes.json

___

Write Your Tests

___

python manage.py test

Then fix your errors, or you should see:

Creating test database for alias 'default'...
System check identified no issues (0 silenced).
..
----------------------------------------------------------------------
Ran 2 tests in 0.335s
OK
Destroying test database for alias 'default'...

--

--