pythondjangopytestpytest-django

Pytest doesn't found my settings directory


I tried to start pytest but the settings file cannot be found by pytest

I'm in virtualenv with Python 3.11.9 and pytest 8.3.2

ImportError: No module named 'drf.settings'
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.

here the structure of my project

├── README.md
├── drf
│   ├── drf
│   │   ├── __init__.py
│   │   ├── production_settings.py
│   │   ├── settings.py
│   │   ├── urls.py
│   │   └── wsgi.py
│   ├── manage.py
│   └── tests
│       ├── __pycache__
│       │   └── test_auth.cpython-311-pytest-8.3.2.pyc
│       ├── factory_boy
│       │   ├── __pycache__
│       │   │   └── factory_models.cpython-311.pyc
│       │   └── factory_models.py
│       └── test_auth.py
├── drf-uwsgi.ini
├── pytest.ini
├── requirements.in
├── requirements.txt

and here the content of pytest.ini

[pytest]
DJANGO_SETTINGS_MODULE = drf.settings
python_files = test_*.py
django_debug_mode = true
pythonpath = .venv/bin/python

What I have tried so far:

edit: at this moment I can run pytest with any problem, but I use a conftest for that and search a solution with pytest.ini

If you have any suggestions ;)


Solution

  • You need to add pythonpath within the pytest.ini as follows:

    [pytest]
    pythonpath = drf
    DJANGO_SETTINGS_MODULE = drf.settings
    python_files = test_*.py
    

    Or you can change the layout of the tests and move the pytest.ini from the project's root to the tests folder like this SO post.


    Note: use drf.settings instead of drf.settings.py