How can I test environment variables using pytest and tox?
validate.py
ENV_VAR = os.environ['ENV_VAR']
def validate_env_var(value):
if value != ENV_VAR:
raise Exception
test_validate.py
class TestValidateEnvVar:
def test_validate_env_var_pass(self):
value = 'valid_env_value'
os.environ["ENV_VAR"] = value
validate.validate_env_var(value)
If I set the environment variables in the tox.ini
file:
[testenv]
setenv = ENV_VAR=valid_env_value
The test passes, but I would like to keep the test isolated.
The environment variables should be provided by your test, not by your test runner. One option is to use mock and patch
os.environ
. Alternatively you can just provide the environment variables in your test case'ssetUp()
and reset them intearDown()
.