Environment variables with pytest and tox

1232
January 03, 2017, at 00:56 AM

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.

Answer 1

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().

Answer 2

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": "valid_env_value"}
    def test_validate_env_var_pass(self):
        reload(validate)
        value = 'valid_env_value'
        os.environ["ENV_VAR"] = value
        validate.validate_env_var(value)
Rent Charter Buses Company
READ ALSO
Load CSV to .mdb using pyodbc and pandas

Load CSV to .mdb using pyodbc and pandas

Background story: I work on finance (not a developer, so help is very appreciated), my department currently relies heavily on excel and vba to automate as much as possible of our tasksThe company just validated a python distribution and we're now allowed...

955
Is there any dns toolkit for python better than dnspython? [on hold]

Is there any dns toolkit for python better than dnspython? [on hold]

I'm looking for a dns toolkit for python, DNSPython looks powerful, but I must say its documents it very poor, is there any other similar package with well-document so I don't need to dig it for how to use it

347
Adding to session dictionary

Adding to session dictionary

I'm trying to create a view function which updates the users cart (session) on add and removal

388