17
Testing Environment variable in pytest
Suppose, we have a method that uses environment variables.
import os
def get_env_vars():
user = os.environ['USER']
token = os.environ['TOKEN']
return user, token
We need to test this method. We will see 3 ways to test this method.
def test_get_env_vars_with_monkeypatch(monkeypatch):
monkeypatch.setenv('USER', 'hasan')
monkeypatch.setenv('TOKEN', 'xxx')
u, t = get_env_vars()
assert u == 'hasan'
assert t == 'xxx'
from unittest import mock
def test_get_env_vars_with_mock_module():
with mock.patch.dict(os.environ, {'USER': 'hasan', 'TOKEN': 'xxx'}):
u, t = get_env_vars()
assert u == 'hasan'
assert t == 'xxx'
We can use this plugin to set environment variables that don't really matter to the function implementations.
- Install
pytest-env
plugin usingpip install pytest-env
. - Add the following portion to
pytest.ini
,setup.cfg
etc files:
[pytest]
env =
USER=hasan
TOKEN=xxx
- Then write test as following:
def test_get_env_vars_with_pytest_env_plugin():
u, t = get_env_vars()
assert u == 'hasan'
assert t == 'xxx'
17