I am new to unittesting. I want to read some env vars in django unittests, but I am having some troubles when trying to read the env var from django.conf.settings, but I can read the env var using os.environ.get(). How can I access the current env var from django.conf.settings?
The test code looks like the following:
from unittest.mock import patch
def test_functionality_in_non_production_environments(self):
with patch.dict('os.environ', {
'ENVIRONMENT': 'local',
'ENV_VALUE': 'test_env_value',
}):
from django.conf import settings
print(settings.ENV_VALUE) # --> DOES NOT PRINT 'test_env_value'
print(os.environ.get('ENV_VALUE')) # --> PRINTS 'test_env_value'
In settings.py:
ENV_VALUE = os.environ.get('ENV_VALUE', 'some other value')
I am trying to test the correct behaviour of the code depending on the env var.
In some parts of the code there is some logic like:
if settings.ENV_VALUE and setting.ENVIRONMENT == 'local':
# do some stuff
You can override django settings using override_settings
decorator:
from django.test import TestCase, override_settings
@override_settings(ENV_VALUE='test_env_value', ENVIRONMENT='local')
def test_functionality_in_non_production_environments(self):
from django.conf import settings
print(settings.ENV_VALUE)
print(os.environ.get('ENV_VALUE'))