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.

Using monkeypatch

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'

Using unittest.mock module

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'

Using pytest-env plugin

We can use this plugin to set environment variables that don't really matter to the function implementations.

  1. Install pytest-env plugin using pip install pytest-env.
  2. Add the following portion to pytest.ini, setup.cfg etc files:
env =
  1. 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'