I have a django project and I'm setting up my testing environment with pytest and pytest-django.

Previously, I have set up my environment variables like DB_HOST using decouple module. These variables work fine when they are used by regular django Python files.

However, when I run pytest on tests which use the same files, these variables are not found.

decouple.UndefinedValueError: DB_HOST not found. Declare it as envvar or define a default value.

My pytest.ini file:

[pytest]
DJANGO_SETTINGS_MODULE = bapi_django.settings

The error suggests to declare these variables, but it seems anti-DRY to me.

Is there anyway I can use my django project level env variables or do I have to redefine them from scratch?

1

There are 1 best solutions below

0
Hans Bambel On

Do you set the DB_HOST in your settings.py?

I have not used decouple, instead I am using a .env-file with the environ module and have the following in my settings.py:

import environ

env = environ.Env(DEBUG=(bool, False))

BASE_DIR = Path(__file__).resolve().parent.parent

# Take environment variables from .env file
environ.Env.read_env(os.path.join(BASE_DIR, ".env"))

Looking through the decouple readme something like this should work in your settings.py:

from decouple import config

DB_HOST = config("DB_HOST")