Sub topic 12
Built-in fixtures: tmp_path, monkeypatch, and capsys
This chapter assumes you can write basic pytest tests, know how a test requests a fixture by naming it as a parameter, and know how to read a failing assertion. It covers three fixtures that ship with pytest: tmp_path, monkeypatch, and capsys. Each one isolates a test from something outside the code under test: the file system, the process environment, and the terminal output.
What built-in fixtures give you
A built-in fixture works like one you write yourself. You add its name to the test function's parameters, and pytest creates it before the test and cleans it up afterwards. You don't import anything. Run pytest --fixtures to list every fixture available in your project, including those from plugins and your own conftest.py.
The three fixtures in this chapter share a property: all are function-scoped by default. Every test gets a fresh instance, and whatever the test changed is undone when it ends. That is what keeps tests independent of each other.
tmp_path: a private directory per test
tmp_path is a pathlib.Path pointing to a new, empty directory unique to the test. Use it whenever code reads or writes files, so tests never touch your real project files or collide with each other.
# report.py
from pathlib import Path
def save_lines(path, lines):
path = Path(path)
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
return path
def load_lines(path):
return Path(path).read_text(encoding="utf-8").splitlines()# test_report.py
from report import load_lines, save_lines
def test_round_trip(tmp_path):
target = tmp_path / "out.txt"
save_lines(target, ["alpha", "beta"])
assert target.exists()
assert load_lines(target) == ["alpha", "beta"]
def test_each_test_gets_its_own_directory(tmp_path):
assert list(tmp_path.iterdir()) == []The second test passes even when it runs after the first, because the first test's file lives in a different directory.
Details worth knowing:
- The directory lives under the system temp location, in a folder such as
pytest-of-<user>. By default pytest keeps the directories from the last three runs, so you can inspect files after a failure. tmp_pathis function-scoped. If a session-scoped fixture needs a directory, usetmp_path_factoryand calltmp_path_factory.mktemp("name").- Older code uses
tmpdir, which returns apy.path.localobject. Prefertmp_path, which gives you the standardpathlibAPI.
monkeypatch: temporary changes that always get undone
monkeypatch modifies an attribute, dictionary item, environment variable, or working directory for the duration of one test. When the test ends, pytest restores every change in reverse order, even if the test failed.
Environment variables
# 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 does not exist, for example on a machine where nobody set it. The test then fails for the wrong reason.
Replacing a function or attribute
monkeypatch.setattr(target, name, value) swaps an attribute. This is how you remove time, randomness, or network calls from a test.
# clock.py
from datetime import datetime
def current_hour():
return datetime.now().hour
def greeting():
return "Good morning" if current_hour() < 12 else "Good afternoon"# test_clock.py
import clock
def test_greeting_in_the_morning(monkeypatch):
monkeypatch.setattr(clock, "current_hour", lambda: 9)
assert clock.greeting() == "Good morning"
def test_greeting_in_the_afternoon(monkeypatch):
monkeypatch.setattr(clock, "current_hour", lambda: 15)
assert clock.greeting() == "Good afternoon"greeting() looks up current_hour in the clock module each time it runs, so the replacement takes effect. The test result no longer depends on when you run it.
Patch where the name is looked up
The most common monkeypatch mistake is patching the wrong place. Suppose another module does from clock import current_hour. That import copies a reference into the other module's namespace. Patching clock.current_hour then has no effect on the copy. Patch the name in the module that uses it, for example monkeypatch.setattr(other_module, "current_hour", ...).
Other useful methods
| Method | Effect |
|---|---|
| `setenv(name, value)` / `delenv(name, raising=True)` | Set or remove an environment variable |
| `setattr(obj, name, value)` | Replace an attribute; fails if it does not exist unless `raising=False` |
| `delattr(obj, name)` | Remove an attribute |
| `setitem(mapping, key, value)` / `delitem(mapping, key)` | Change a dictionary or other mapping |
| `chdir(path)` | Change the working directory, restored afterwards |
| `syspath_prepend(path)` | Add a directory to `sys.path` |
monkeypatch.chdir(tmp_path) is a good partner for tmp_path. It lets you test code that writes to relative paths without littering your project.
capsys: checking what code prints
capsys captures text written to sys.stdout and sys.stderr during a test. Call capsys.readouterr() to get a named tuple with out and err strings.
# greeter.py
import sys
def greet(name):
print(f"Hello, {name}!")
print("Remember to be kind.", file=sys.stderr)# test_greeter.py
from greeter import greet
def test_greet_writes_to_stdout_and_stderr(capsys):
greet("Ada")
captured = capsys.readouterr()
assert captured.out == "Hello, Ada!\n"
assert captured.err == "Remember to be kind.\n"
def test_readouterr_resets_the_buffer(capsys):
print("first")
assert capsys.readouterr().out == "first\n"
print("second")
assert capsys.readouterr().out == "second\n"Each readouterr() call returns only what was written since the previous call, then clears the buffer. Print statements end with \n, so compare against the newline or use .strip().
Pytest already captures output for every test and shows it only when the test fails. capsys is for the case where the output is the behavior you want to verify.
Related fixtures:
capfdcaptures at the file-descriptor level, so it also sees output from subprocesses and C extensions.caplogcaptures records from theloggingmodule.capsysbinaryreturns bytes instead of text.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| A patch has no effect | The name was patched in the wrong module | Patch the module where the name is looked up |
| `AttributeError` from `setattr` | The attribute does not exist, often a typo | Fix the name, or pass `raising=False` if absence is expected |
| `KeyError` from `delenv` | The variable was not set | Pass `raising=False` |
| `capsys` output is empty | Output went through a subprocess or a logger | Use `capfd` or `caplog` |
| Test sees leftover files | Code wrote to a fixed path instead of `tmp_path` | Pass `tmp_path / "name"` into the code, or use `monkeypatch.chdir` |
| Using `monkeypatch` in a wider-scoped fixture fails | `monkeypatch` is function-scoped | Create a `pytest.MonkeyPatch()` context yourself, or use `with pytest.MonkeyPatch.context() as mp:` |
Exercise
A function load_config() reads the file config.ini from the current working directory and returns its text. Using only built-in fixtures, how would you test it without touching any real file? Name the fixtures and describe the steps.
Show answer
Use tmp_path and monkeypatch. Write the sample text with (tmp_path / "config.ini").write_text("debug=true\n"). Then call monkeypatch.chdir(tmp_path) so the relative path resolves inside the temporary directory. Call load_config() and assert that it returns "debug=true\n". Pytest removes the working-directory change when the test ends, and the temporary directory is separate from every other test's.
Exercise
A test calls a function that does print("done"). The test uses capsys and checks capsys.readouterr().out == "done". It fails. What is the problem?
Show answer
print appends a newline, so the captured output is "done\n". Compare against "done\n", or compare .out.strip() with "done".