lollercoaster lollercoaster - 1 year ago 180
Python Question

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
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
file I run with

foreman start -e .env web

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

How can I get around this?

Answer Source

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

from test.test_support import EnvironmentVarGuard
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 ... #

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download