pythondjangoenvironment-variablesforeman

django setting environment variables in unittest tests


I want to be able to set environment variables in my Django app for tests to be able to run. For instance, my views rely on several API keys.

There are ways to override settings during testing, but I don't want them defined in settings.py as that is a security issue.

I've tried in my setup function to set these environment variables, but that doesn't work to give the Django application the values.

class MyTests(TestCase):
    def setUp(self):
        os.environ['TEST'] = '123'  # doesn't propogate to app

When I test locally, I simply have an .env file I run with

foreman start -e .env web

which supplies os.environ with values. But in Django's unittest.TestCase it does not have a way (that I know) to set that.

How can I get around this?


Solution

  • As @schillingt noted in the comments, EnvironmentVarGuard was the correct way.

    from test.test_support import EnvironmentVarGuard # Python(2.7 < 3)
    from test.support import EnvironmentVarGuard # Python >=3
    from django.test import TestCase
    
    class MyTestCase(TestCase):
        def setUp(self):
            self.env = EnvironmentVarGuard()
            self.env.set('VAR', 'value')
    
        def test_something(self):
            with self.env:
                # ... perform tests here ... #
                pass
    

    This correctly sets environment variables for the duration of the context object with statement.