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?
The test.support.EnvironmentVarGuard
is an internal API that might be changed from version to version with breaking (backward incompatible) changes. In fact, the entire test
package is internal use only. It was explicitly stated on the test package documentation page that it's for internal testing of core libraries and NOT a public API. (see links below)
You should use patch.dict()
in python's standard lib unittest.mock
. It can be used as a context manager, decorator or class decorator. See example code below copied from the official Python documentation.
import os
from unittest.mock import patch
with patch.dict('os.environ', {'newkey': 'newvalue'}):
print(os.environ['newkey']) # should print out 'newvalue'
assert 'newkey' in os.environ # should be True
assert 'newkey' not in os.environ # should be True
Update: for those who doesn't read the documentation thoroughly and might have missed the note, read more test
package notes at