'pytest-django could not find a Django project

Trying to configure pytest with django, the project already has a lot of test not written with pytest (written with unittest) but I am trying to get them run with pytest so I can write pytest tests and get it work with old tests.

I know pytest-django checks for the manage.py file in the root dir of a django project but this project the manage.py file is not in the root dir so I guess that's why the error below is thrown when I run pytest however running pytest and supplying a particular file works. How do I specify where manage.py is? As I can't find this in the documentation

pytest-django could not find a Django project (no manage.py file could be found). 
You must explicitly add your Django project to the Python path to have it picked up.


Solution 1:[1]

you can define a python path to python commands that you want to run:

PYTHONPATH=/your/path/to/your/django/project/ pytest

or export your pythonpath before you run the pytest command:

export PYTHONPATH=/your/path/to/your/django/project/

pytest

Solution 2:[2]

As a standard practice, you should add a setup.cfg file to your root, with the following block -

[tool:pytest]
DJANGO_SETTINGS_MODULE=<package_name>.settings.py

You can later use the same file for linters by adding specific blocks for them.

Solution 3:[3]

In my case, I created a configure file named pytest.ini in the tests folder with the following content:

[pytest]
pythonpath = ../bitpin
DJANGO_SETTINGS_MODULE = bitpin.settings
python_files = tests.py test_*.py *_tests.py

Repository tree:

bitpin-repo
??? bitpin
?   ??? bitpin
?   ?   ??? asgi.py
?   ?   ??? __init__.py
?   ?   ??? settings.py
?   ?   ??? urls.py
?   ?   ??? wsgi.py
?   ??? __init__.py
?   ??? manage.py
??? tests
?   ??? test_models.py
?   ??? pytest.ini
?   ??? conftest.py
??? setup.py

[NOTE]

  • If the tests/ is next to the project, replace bitpin with .:
[pytest]
pythonpath = .

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 matyas
Solution 2 iamkhush
Solution 3