Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 38 ยท Fixtures

Built-in Fixtures

Tour the fixtures that ship with pytest: tmp_path and tmp_path_factory for temporary files, request, pytestconfig, monkeypatch basics, recwarn, capsys and record_property.

You do not have to write every fixture yourself. pytest ships with a set of built-in fixtures that solve common testing chores: creating a clean temporary directory, capturing output, patching environment variables, and finding out which test is running. You request them like any other fixture, by name.

Run pytest --fixtures to see the complete list for your installed version. This lesson covers the ones you will use most.

tmp_path: a fresh temporary directory

Code that reads and writes files is hard to test if it touches real folders. The tmp_path fixture gives each test its own empty directory, as a pathlib.Path, and pytest manages it for you. It is unique per test, so tests cannot interfere with each other.

Python tmp_path

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Because tmp_path is a Path, you can use / to build paths, .mkdir(), .write_text(), .read_text(), .glob() and everything else from pathlib. pytest keeps the last few test runs' directories on disk (so you can inspect them after a failure) and deletes older ones automatically.

An older fixture called tmpdir returns a py.path.local object. It still exists, but new tests should use tmp_path.

tmp_path_factory: for wider scopes

tmp_path has function scope. If you want a temporary directory inside a module- or session-scoped fixture, use tmp_path_factory, which is session-scoped itself:

Python tmp_path_factory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The expensive file is built once per module and shared, which is safe because the tests only read it.

monkeypatch: change things temporarily

monkeypatch changes attributes, dictionary items and environment variables for one test and restores the originals afterwards, even if the test fails. A brief look here; the whole mocking chapter builds on it.

Python monkeypatch basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The main methods are setattr, delattr, setitem, delitem, setenv, delenv, syspath_prepend and chdir.

request: information about the running test

The request fixture is a window into pytest itself. In a fixture or test it reveals the current test's name, markers, the fixture's scope, and the parameter value in a parametrized fixture:

Python request.node and request.fixturename

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Useful attributes include request.node (the test item), request.function, request.cls, request.module, request.config, request.param (for parametrized fixtures), request.addfinalizer(...) and request.getfixturevalue("name"), which fetches a fixture dynamically by name at run time.

recwarn: all warnings at once

recwarn records every warning raised in a test. It complements pytest.warns when you need to inspect them freely:

Python recwarn

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

pytestconfig and config options

pytestconfig (session-scoped) gives access to the configuration: command-line options with getoption, ini values with getini, and the root directory with rootpath.

Python
def test_root(pytestconfig):
    print(pytestconfig.rootpath)
    print(pytestconfig.getoption("verbose"))

Capturing: capsys, capfd, caplog

You met these in Testing Warnings, Output and Logs. They are also built-in fixtures, along with capsysbinary, capfdbinary and the newer capteesys, which captures output and still lets it through to the terminal.

Recording extra data

record_property(name, value) adds a property to the test's entry in the JUnit XML report (see CI lessons later), and record_testsuite_property adds one to the whole suite. They are handy for traceability data such as ticket numbers or build ids.

The family at a glance

Fixture Scope Gives you
tmp_path function a unique empty Path
tmp_path_factory session mktemp() for wider-scoped temp dirs
monkeypatch function temporary attribute/env/dict changes
capsys / capfd function captured stdout and stderr
caplog function captured log records
recwarn function all warnings raised
request function info about the requesting test or fixture
pytestconfig session the pytest Config object
cache function key-value store persisted between runs (.pytest_cache)
record_property function extra data in XML reports

Overriding a built-in fixture

Because lookup goes from your code outward, you can override a built-in by defining a fixture with the same name in a conftest. A common example is wrapping tmp_path:

Python
@pytest.fixture
def tmp_path(tmp_path):
    (tmp_path / "config").mkdir()
    return tmp_path

Use that sparingly. A differently named fixture such as workspace(tmp_path) is usually clearer.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What type of object is the value of the tmp_path fixture?

    tmp_path is a pathlib.Path; every test gets its own fresh directory.
  2. 2. You need a temporary directory inside a module-scoped fixture. Which fixture should you use?

    tmp_path is function-scoped, so a wider-scoped fixture cannot use it. tmp_path_factory is session-scoped and offers mktemp().
  3. 3. What happens to a monkeypatch.setenv change after the test?

    monkeypatch undoes all its changes at the end of each test, even if the test failed.
  4. 4. Which fixture tells you the name of the running test?

    request exposes the test item, its name, markers, function and more.

Summary

  • pytest ships built-in fixtures; list them with pytest --fixtures.
  • tmp_path and tmp_path_factory give isolated temporary directories as pathlib paths.
  • monkeypatch safely changes attributes, dicts and environment variables for one test.
  • request reveals the running test and lets fixtures fetch others dynamically.
  • recwarn, capsys, capfd and caplog capture warnings, output and logs.
  • Define a fixture with the same name closer to the test to override a built-in.

Next: Fixture Factories, Autouse and Parameters