Test Environment Variables in Python
Intro
If you are working with environment variables you need to set, change or delete the values from the system for testing purposes. So how can we test them?
Let’s assume that we have a function that gets a “secret” key from os
environment:
|  |  | 
One way for testing would be put an env var into config files of test like
tox.ini or pytest.ini
# tox.ini
[testenv]
setenv = SECRET=top_secret
Another way would be using pytest-env plugin and adding it into pytest.ini:
# pytest.ini
[pytest]
env =
    HOME=~/tmp
    SECRET=top_secret
However these methods are not preferred since it violates isolating tests.
Monkeypatching environment variables
Recommended way comes from pytest itself: monkeypatch. pytest provides
a mechanism which gives the setenv and delenv methods.
First we set SECRET env var and test it, then testing OSError when SECRET not
set. Since as we know; we always should test both “normal” and “failure” cases:
|  |  | 
You can also use fixture structures and share across them tests. For more info
please go to: pytest:testing env vars.
All done!