pytest-datafiles

3.0.1 · active · verified Fri Apr 17

pytest-datafiles is a pytest plugin that simplifies testing by providing a convenient way to make files and directories available to your tests within a temporary directory (leveraging pytest's `tmp_path` fixture). It uses a decorator to specify which files or directories from your source tree should be copied. The current version is 3.0.1, with releases typically happening for bug fixes, new features, or breaking changes in underlying dependencies like pytest or Python versions.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the `@pytest.mark.datafiles` decorator to specify files to be copied into a temporary directory for your test. The `datafiles` fixture, a `pathlib.Path` object, is then used within the test function to access these files. The example sets up temporary dummy data files for demonstration purposes.

import pytest
from pathlib import Path
import os

# Create a dummy 'data' directory and files for the example
# In a real project, these would be part of your test resources
data_dir = Path(__file__).parent / "data"
data_dir.mkdir(exist_ok=True)
(data_dir / "hello.txt").write_text("Hello, pytest-datafiles!")
(data_dir / "config.json").write_text('{"key": "value"}')

@pytest.mark.datafiles(data_dir / "hello.txt", data_dir / "config.json")
def test_read_datafile(datafiles: Path):
    # datafiles is a pathlib.Path object pointing to the temporary directory
    # where your specified files have been copied.
    assert datafiles.is_dir()

    hello_file = datafiles / "hello.txt"
    assert hello_file.exists()
    assert hello_file.read_text() == "Hello, pytest-datafiles!"

    config_file = datafiles / "config.json"
    assert config_file.exists()
    assert config_file.read_text() == '{"key": "value"}'

    # To run this example, save it as a .py file, create a 'data' directory
    # next to it, and run `pytest` in that directory.

view raw JSON →