Python Tutorial

Testing Your Django App With pytest : A Beginner’s Guide (Part 1)

“Testing leads to failure, and failure leads to understanding.”

Burt Rutan

You may have heard of and used unit testing to test your projects with Python and Django unittest module. But pytest suggests much more pythonic tests without boilerplate. pytest is a very mature testing tool for testing Python and Django based projects.

Let’s dive into pytest.

It has the following features:

pytest finds all the files in test_*.py or * format in your project. From those files, collects test prefixed test functions outside of class and test prefixed test methods inside Test prefixed test classes.

Fixtures are used to provide a fixed baseline upon which tests can reliably and repeatedly execute. pytest fixtures offer dramatic improvements over the classic setUp/tearDown methods.

pytest in Django


For testing our Django applications with pytest, we will use pytest-django. It can be installed with pip.

pip install pytest-django
Configuring Django Project
├── blog
│   ├──
│   ├──
│   ├──
│   ├──
│   ├── migrations
│   │   ├──
│   │   └──
│   ├──
│   ├── tests
│   │   ├──
│   │   ├──
│   │   ├──
│   │   └──
│   ├──
│   └──
├── db.sqlite3
├── media
├── proj
│   ├──
│   ├──
│   ├──
│   └──
├── pytest.ini
├── static
├── templates
│   └── blog
│       └── index.html

First, we have to create a different settings file for pytest, we naming it In this settings file, we just changed the database name for the test, and using all settings from proj/ The file looks like this:

from proj.settings import *

    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'test_db.sqlite3'),

We need to tell pytest which Django settings should be used for running tests. Create a pytest.ini configuration file with this information.

python_files = test_*.py *

Last line in the [pytest] section instructs pytest to collect tests in Django’s default app layouts too. These two files should be in the project root directory as you can see in the project structure.

Running Tests

In pytest, tests can be invoked directly with the pytest command.

pytest                          # tests whole project
pytest app_name                 # tests the app
pytest app/    # tests a single file of an app

The source code of the project is available on GitHub:

In my next blog post, I will cover how to write tests with pytest and Django. Stay Tuned!


Adnan Alam

Self-taught programmer | Pythonista | Love to solve problems!
Dreamcatcher IT
Github | Website | Linkedin