2

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
  • Do you need to override settings? This might help: https://docs.djangoproject.com/en/4.0/topics/testing/tools/#overriding-settings. Have you imported `django.conf.settings` somewhere before? If so, it was configured, and I suppose that `django.conf.settings.ENV_VALUE` have `ENV_VALUE` cached (in form of str/list/...) and not as `os.getenv(...)`, thus environment modification doesn't affect settings. – STerliakov Jan 24 '22 at 14:23

1 Answers1

0

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'))  
neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100
  • Yes, overriding settings directly works ok. In my case I will also need to use patch.dict in case the code access the the env var direcly and not through conf.settings because overriding django settings does not seem to also modify the environment variable. – David Emanuel Sandoval Jan 24 '22 at 14:48