If you want to write a test that sets one or more environment variables, overriding existing values, you can use mock.patch.dict like this:
You can apply this to all tests in a TestCase by applying it as a class decorator:
Note this wraps only methods starting test_, so setUp(), tearDown(), setUpClass(), etc. will use the unmocked environment.
If you want to wrap the test case execution from start to end, you’ll want to create and start the mocker in setUpClass(), and stop it tearDownClass():
If you don’t know the keys or values you want to mock at import time, you’ll need to use the context manager form of mock.patch.dict within your test method:
If you want to clear everything from os.environ so only the given variables are set, you can do so by passing clear=True to mock.patch.dict:
If you want to remove only a few variables, it gets a little more tricky.
mock.patch.dict doesn’t have a way of removing select keys, so you need to build a dictionary of the keys to preserve, and use that with clear=True:
I hope this helps you with your testing journey,
Working on a Django project?
Check out my book Speed Up Your Django Tests which covers loads of best practices so you can write faster, more accurate tests.
One summary email a week, no spam, I pinky promise.