Getting started with pytest and pytest-django


pytest and pytest-django are compatible with standard Django test suites and Nose test suites. They should be able to pick up and run existing tests without any or little configuration. This section describes how to get started quickly.

Talks, articles and blog posts

For general information and tutorials on pytest, see the pytest tutorial page.

Step 1: Installation

pytest-django can be obtained directly from PyPI, and can be installed with pip:

pip install pytest-django

Installing pytest-django will also automatically install the latest version of pytest. pytest-django uses pytest’s plugin system and can be used right away after installation, there is nothing more to configure.

Step 2: Point pytest to your Django settings

You need to tell pytest which Django settings should be used for test runs. The easiest way to achieve this is to create a pytest configuration file with this information.

Create a file called pytest.ini in your project root directory that contains:

DJANGO_SETTINGS_MODULE = yourproject.settings

Another options for people that use pyproject.toml is add the following code:

DJANGO_SETTINGS_MODULE = "yourproject.settings"

You can also specify your Django settings by setting the DJANGO_SETTINGS_MODULE environment variable or specifying the --ds=yourproject.settings command line flag when running the tests. See the full documentation on Configuring Django settings.

Optionally, also add the following line to the [pytest] section to instruct pytest to collect tests in Django’s default app layouts, too. See the FAQ at My tests are not being found. Why? for more infos.

python_files = test_*.py *

Step 3: Run your test suite

Tests are invoked directly with the pytest command, instead of test, that you might be used to:


Do you have problems with pytest not finding your code? See the FAQ I see an error saying “could not import myproject.settings”.

Next steps

The Usage and invocations section describes more ways to interact with your test suites.

pytest-django also provides some Django helpers to make it easier to write Django tests.

Consult the pytest documentation for more information on pytest itself.

Stuck? Need help?

No problem, see the FAQ on How can I use test with pytest-django? for information on how to get help.