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