Sub topic 12
Built-in fixtures: tmp_path, monkeypatch, and capsys
This chapter assumes you can write pytest tests, use plain assert, and request a fixture by naming it as a test argument. pytest ships with fixtures that need no definition and no import. You request them by name, and pytest sets them up and cleans them up for you. Three of them cover most isolation needs: tmp_path, monkeypatch, and capsys.
tmp_path: a private temporary directory
tmp_path gives each test a fresh, empty directory as a pathlib.Path. You can write files freely without touching your project or leaking state between tests.
# notes.py
from pathlib import Path
def save_note(folder, name, text):
path = Path(folder) / f"{name}.txt"
path.write_text(text)
return path# test_notes.py
from notes import save_note
def test_save_note_writes_file(tmp_path):
path = save_note(tmp_path, "todo", "buy milk")
assert path.read_text() == "buy milk"
assert list(tmp_path.iterdir()) == [path]pytest keeps the directories of the most recent test runs, so you can inspect them after a failure.
monkeypatch: temporary changes
monkeypatch changes an environment variable, attribute, or dictionary item for one test. When the test ends, pytest undoes every change.
# weather.py
import os
def api_url():
return os.environ.get("WEATHER_URL", "https://example.com")# test_weather.py
import weather
def test_api_url_reads_environment(monkeypatch):
monkeypatch.setenv("WEATHER_URL", "http://localhost:8000")
assert weather.api_url() == "http://localhost:8000"
def test_api_url_default(monkeypatch):
monkeypatch.delenv("WEATHER_URL", raising=False)
assert weather.api_url() == "https://example.com"The raising=False argument matters. Without it, delenv raises KeyError when the variable is not set, and the test fails on a machine that never defined it.
The main methods are:
| Method | Effect |
|---|---|
| `setenv(name, value)` | Sets an environment variable |
| `delenv(name, raising=True)` | Removes an environment variable |
| `setattr(obj, name, value)` | Replaces an attribute, such as a function in a module |
| `setitem(mapping, key, value)` | Sets a dictionary entry |
| `chdir(path)` | Changes the working directory |
capsys: capturing printed output
capsys captures what the code writes to standard output and standard error. Call readouterr() to get both as text.
# greeter.py
import sys
def greet(name):
print(f"Hello, {name}!")
print("greeting sent", file=sys.stderr)# test_greeter.py
from greeter import greet
def test_greet_prints_message(capsys):
greet("Ada")
captured = capsys.readouterr()
assert captured.out == "Hello, Ada!\n"
assert captured.err == "greeting sent\n"Each readouterr() call returns what was written since the previous call, then clears the buffer. Output includes the trailing newline from print, so compare against "...\n" or use .strip().
How the fixtures combine
A single test can request several built-in fixtures. Here tmp_path supplies a directory and monkeypatch points the program at it.
# settings.py
import os
from pathlib import Path
def config_path():
return Path(os.environ["APP_HOME"]) / "config.ini"# test_settings.py
from settings import config_path
def test_config_path_uses_app_home(tmp_path, monkeypatch):
monkeypatch.setenv("APP_HOME", str(tmp_path))
assert config_path() == tmp_path / "config.ini"Common errors
- Patching the wrong name. If
app.pydoesfrom time import sleep, patchapp.sleep, nottime.sleep. - Forgetting that
capsysonly sees output written during the test, not output at import time. - Using
tmp_pathfor data that must outlive the test. It is for scratch files only.
Exercise
A function reads the environment variable MODE and returns "debug" when it is unset. Which fixture and method would you use to test the unset case, and why pass raising=False?
Show answer
Use monkeypatch.delenv("MODE", raising=False). The raising=False argument stops delenv from raising KeyError when MODE is already absent, so the test passes whether or not the variable exists on the machine running it.