DEV Community

Hasanul Islam
Hasanul Islam

Posted on

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
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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:
[pytest]
env =
    USER=hasan
    TOKEN=xxx
Enter fullscreen mode Exit fullscreen mode
  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'
Enter fullscreen mode Exit fullscreen mode

Top comments (0)