Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to read env vars from settings in django unittest?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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'))  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading