Complete worked example
python
import os
def app_mode():
return os.getenv("APP_MODE", "development")
def test_explicit_mode(monkeypatch):
monkeypatch.setenv("APP_MODE", "production")
assert app_mode() == "production"
def test_missing_mode(monkeypatch):
monkeypatch.delenv("APP_MODE", raising=False)
assert app_mode() == "development"- Reasoning
- The worked function reads a synthetic APP_MODE setting at call time, defaulting to development. One test sets production and checks the returned value; another removes the key and checks the documented fallback. Both use monkeypatch so they do not leak state into each other. Reading at call time is important here. If the application stores os.getenv in a module-level constant during import, changing the environment afterward does not rewrite that constant. Test the actual lookup boundary or deliberately structure configuration loading as an explicit function.