[Answered ]-Pytest-django Use env vars in settings.py

1๐Ÿ‘

I was having the same issue. The suggestion of calling dotenv.read_dotenv() from pytest_sessionstart() in conftest.py did not work for me. I also tried the pytest-dotenv library that was linked. It made pytest work, but broke my manage.py module (due to a namespace conflict between django-dotenv [which my manage.py is using to read the .env file], and python-dotenv [which is a dependency of pytest-dotenv]).

Ultimately I ended up finding
pytest-django-dotenv
, which seems to be doing the trick.

๐Ÿ‘คGlenVaughan

0๐Ÿ‘

For anyone passing by, pytest-django-dotenv is deprecated and is not actively maintained. A simple fix is simply to create a conftest.py in your tests folder and to add:

import dotenv

def pytest_sessionstart(session):
    dotenv.load_dotenv("[TEST_ENV_FILE_PATH]")

Hope it helped ๐Ÿ˜‰

๐Ÿ‘คGaspard Merten

0๐Ÿ‘

The mentioned solution with conftest.py to load the environment variables did not work for me if DJANGO_SETTINGS_MODULE was set in the pytest.ini. Somehow it would still try to load the settings before pytest_sessionstart.

So my solution was to define that variable in my .env file instead, which rendered my pytest.ini useless and i removed it.

With that, my conftest.py looks as follows:

import dotenv
import django

def pytest_sessionstart(session):
    dotenv.load_dotenv()
    django.setup()

My .env file and my conftest.py reside in the root folder, my tests are placed like app_name/tests/test_model.py

๐Ÿ‘คkesslmar

Leave a comment