brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: python pytest's monkeypatch.setenv changes an env var for one test only

Python
~/tips/tip-python-pytest-monkeypatch-setenv

import os

Test code that reads environment variables without leaking the change into other tests.

Code that reads os.environ is awkward to test, because setting a variable in one test quietly changes every test after it. pytest’s monkeypatch fixture undoes the change for you.

import os

def get_level():
    return os.environ.get("LOGLEVEL", "INFO")

def test_level_from_env(monkeypatch):
    monkeypatch.setenv("LOGLEVEL", "DEBUG")
    assert get_level() == "DEBUG"

def test_level_default(monkeypatch):
    monkeypatch.delenv("LOGLEVEL", raising=False)
    assert get_level() == "INFO"

setenv sets the variable and delenv removes it, and when the test ends both go back to whatever they were before. The raising=False on delenv means it doesn’t complain when the variable wasn’t set to begin with, which is what I want for a default test.

I included the second test on purpose. If your own shell happens to have LOGLEVEL set, a default test without delenv passes on CI and fails on your laptop, or the other way round.

The same fixture can replace attributes with monkeypatch.setattr and change the working directory with monkeypatch.chdir.

Timing matters. If your module reads the variable once at import time and stores it in a constant, changing the environment inside the test is too late. Read it inside a function, like get_level above, and the problem goes away.

Further reading: pytest: monkeypatch

Going deeper: Guide: advanced tmux, a config that grows with you, formats, layouts and more

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link