PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 21, 2022

[FIXED] How to read env vars from settings in django unittest?

 August 21, 2022     django, django-unittest, environment-variables, python, python-unittest     No comments   

Issue

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

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'))  


Answered By - neverwalkaloner
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing