How to Mock Environment Variables in pytest2020-10-13
Sometimes tests need to change environment variables.
This is fairly straightforward in pytest, thanks to
os.environ quacking like a
dict, and the
unittest.mock.patch.dict decorator/context manager.
(If you’re not using pytest, or use
TestCase classes with pytest, see the
unittest edition of this post.)
pytest comes with a
monkeypatch fixture which does some of the same things as
This post uses
mock.patch, since it’s a more powerful and general purpose tool.
But you might prefer
monkeypatch - check out the monkeypatch documentation for environment variables.
Adding Environment Variables
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 module by creating a local auto-used pytest fixture that uses
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 function:
If you want to clear everything from
os.environ so only the given variables are set, you can do so by passing
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
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.
© 2021 All rights reserved.