Environment variables with pytest and tox

10.5k views Asked by At

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.

2

There are 2 answers

0
emulbreh On BEST ANSWER

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's setUp() and reset them in tearDown().

0
JohnBoy On

I had a problem with the ENV_VAR variable getting set before the test would run. The validate module had to be reloaded within the test to work properly using imp.reload

test_validate.py

import mock
from imp import reload
class TestValidateEnvVar:
    @mock.patch.dict(os.environ, {"ENV_VAR": "env_value"})
    def test_validate_env_var_pass(self):
        reload(validate)
        value = 'env_value'
        os.environ["ENV_VAR"] = value
        validate.validate_env_var(value)