django setting environment variables in unittest tests

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

https://docs.python.org/2/library/test.html or

https://docs.python.org/3/library/test.html

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)