# Fixtures and Temporary Files

A pytest fixture builds the setup several tests share and hands each test a fresh copy, tmp_path gives each test its own empty folder to write files in, and capsys lets a test read what a function printed.

Journeyman · Python · Updated November 19, 2026

By Gregor Dzierzon

## After this lesson you can

- Share setup between tests with a pytest fixture, named as the test's parameter
- Test code that writes a file with tmp_path, and code that prints with capsys

## Key takeaways

- A fixture is a function marked with the fixture decorator, and a test gets what it returns by naming the fixture as a parameter.
- Every test gets a fresh copy of a fixture's value, so one test changing it can't spoil the next test.
- tmp_path is a fixture pytest has built in, a new empty folder for each test, so a test can write files without touching your project.
- capsys is the fixture for printed output, and capsys.readouterr().out is everything the code printed, as one string.

Some code can't be tested with one line. It needs a sample cart built first, or it writes a file, or it prints instead of returning. You'll meet all three as soon as you test a real program: a report that saves to a file, a script that prints a receipt. pytest has a tool for each, called a fixture.

The example is Crafty Corner, an online craft shop, where a cart is a dictionary of each item and its price, and orders of $50 or more ship free.

## The same cart in every test

Two functions in `shipping.py` work on a cart:

```python
def cart_total(cart):
    """Add up a cart: a dictionary of each item and its price."""
    return round(sum(cart.values()), 2)


def ships_free(cart):
    """Orders of $50 or more ship free."""
    return cart_total(cart) >= 50
```

Every test of them needs a cart. Copy the same dictionary into each test, and the copies drift apart the day someone changes one of them and forgets the others.

A **fixture** is the setup, written once. It's a function marked with `@pytest.fixture` (read "at pytest fixture") that returns what the tests need. A test asks for it by naming it as a parameter, and pytest calls the fixture and passes in what it returned:

```python
import pytest

from shipping import cart_total, ships_free


@pytest.fixture
def yarn_cart():
    return {"yarn": 12.50, "knitting needles": 8.00, "buttons": 3.25}


def test_cart_total_adds_every_price(yarn_cart):
    assert cart_total(yarn_cart) == 23.75


def test_a_23_75_cart_pays_shipping(yarn_cart):
    assert not ships_free(yarn_cart)


def test_a_pattern_book_makes_it_ship_free(yarn_cart):
    yarn_cart["pattern book"] = 30.00
    assert ships_free(yarn_cart)
```

`python -m pytest` ends with *3 passed*. The last test adds a $30 pattern book to its cart, and that changes nothing for the others: pytest calls the fixture again for every test, so each one gets a fresh cart. Run the tests in any order and they still pass. That's called **test isolation**: no test depends on what another one did.

## A fresh folder for every test: tmp_path

Crafty Corner prints a shipping label for every order. This function writes it to a file:

```python
def save_label(path, order_id, pounds, zone):
    """Write an order's shipping label to the file at path."""
    with open(path, "w", encoding="utf-8") as label:
        label.write(f"Crafty Corner order {order_id}\n")
        label.write(f"{pounds} lb to zone {zone}\n")
```

A test that writes `label-1042.txt` into your project folder leaves the file behind after every run, and could overwrite a real one with the same name. pytest has a fixture built in for this, **`tmp_path`**: a new, empty folder made for that one test, inside your computer's folder for temporary files. Name it as a parameter and use it like any folder's path:

```python
from shipping import save_label


def test_label_names_the_order_and_weight(tmp_path):
    label = tmp_path / "label-1042.txt"
    save_label(label, 1042, 3, 2)
    assert label.read_text(encoding="utf-8") == "Crafty Corner order 1042\n3 lb to zone 2\n"
```

`tmp_path / "label-1042.txt"` (read "tmp path slash label") is the path of a file in that folder, and `open()` takes it like a file name. After the function writes the label, `.read_text()` reads the whole file back as one string, `\n` for each line's end, so one `assert` checks every character. pytest keeps the folders of your last three runs, so you can open one and look, and deletes older ones by itself.

## Checking what was printed: capsys

A function that prints hands back `None`, so there's no return value to compare:

```python
def print_quote(pounds):
    """Print what a parcel costs to send: $4.50 for the first pound, $1.25 for each one after it."""
    cost = 4.50 + (pounds - 1) * 1.25
    print(f"{pounds} lb: ${cost:.2f}")
```

The built-in fixture **`capsys`** (read "cap sys": it captures the output that Python's `sys` module sends to the screen) catches what the code prints while the test runs. `capsys.readouterr()` hands back what was caught so far, and its `.out` is the printed text as one string:

```python
from shipping import print_quote


def test_quote_prints_the_price_with_cents(capsys):
    print_quote(3)
    printed = capsys.readouterr().out
    assert printed == "3 lb: $7.00\n"
```

The string ends with `\n` because `print()` ends every line it prints. With the three test files side by side, the whole run ends with *5 passed*.

| You need | Use |
|---|---|
| The same setup in several tests | your own `@pytest.fixture` |
| A folder to write files in | `tmp_path` |
| What the code printed | `capsys` |

## Check yourself

2 questions to try on the lesson page.

## So what

Setup that lives in one fixture, files that land in a folder made for the test, and printed output a test can read let you test the parts of a program that do real work, not only the ones that return a number.

## Key terms

- [Test Fixture](https://www.ask-codey.com/glossary/test-fixture)
- [Test Isolation](https://www.ask-codey.com/glossary/test-isolation)
- [tmp_path](https://www.ask-codey.com/glossary/tmp-path)
- [capsys](https://www.ask-codey.com/glossary/capsys)

## Related

- [Your First Tests with pytest](https://www.ask-codey.com/lessons/python-testing-first-tests)
- [Testing Edge Cases and Errors](https://www.ask-codey.com/lessons/python-testing-edge-cases-and-errors)
- [Reading and Writing Text Files](https://www.ask-codey.com/lessons/python-files-reading-and-writing)

Source: https://www.ask-codey.com/lessons/python-testing-fixtures-and-tmp-path
