DEV Community

Hasanul Islam
Hasanul Islam

Posted on

3

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs