Skip to content

tmp_path and tmp_path_factory

NOTE

tmp_path is a function-scoped fixture that internally uses tmp_path_factory. If you need a temporary directory for a broader scope, use tmp_path_factory instead.

The tmp_path fixture provides a unique temporary directory for each test. It’s useful for creating files or folders without affecting the real filesystem. The directory is automatically cleaned up after the test run.

tmp_path_factory works similarly but is intended for creating temporary directories at broader scopes (e.g., module or session level), allowing multiple tests to share the same temporary structure when needed.

python
# conftest.py
@pytest.fixture(scope="session")
def shared_file(tmp_path_factory):
    path = tmp_path_factory.mktemp("data") / "sample.txt"
    path.write_text("hello")
    return path

# test_example.py
def test_read(shared_file):
    assert shared_file.read_text() == "hello"

NOTE

tmp_path and tmp_path_factory replace older tmpdir and tmpdir_factory fixtures, which uses the legacy py.path API. The newer fixtures use the modern pathlib.Path API and are recommended for all new tests.