Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Pytest: Mocking environment variables

Just some simple application that uses environment variables.

import os

def add():
    a = os.environ.get("INPUT_A")
    b = os.environ.get("INPUT_B")
    if a is None:
        raise Exception("missing INPUT_A")
    if b is None:
        raise Exception("missing INPUT_B")

    a = int(a)
    b = int(b)
    return a + b

Use the module on the command line:

$ INPUT_A=23 INPUT_B=19 python use_app.py
42
import app

result = app.add()
print(result)

Test the module setting the envrionment variable.

import app
import pytest

def test_app_1(monkeypatch):
    monkeypatch.setenv('INPUT_A', '19')
    monkeypatch.setenv('INPUT_B', '23')
    result = app.add()
    assert result == 42


# We can also test the cases when the environment variables
# are not set or only some of them are set.
def test_app_no_a(monkeypatch):
    with pytest.raises(Exception) as err:
        app.add()
    assert str(err.value) == 'missing INPUT_A'

def test_app_no_b(monkeypatch):
    monkeypatch.setenv('INPUT_A', '0')
    with pytest.raises(Exception) as err:
        app.add()
    assert str(err.value) == 'missing INPUT_B'