Skip to content

pytest_fixtures_fixtures

pytest_fixtures_fixtures

Handy fixtures to access your fixtures.

Classes

FixturePath

Bases: Protocol

A callable that constructs paths inside the fixtures directory.

Source code in src/pytest_fixtures_fixtures/protocols.py
class FixturePath(Protocol):
    """A callable that constructs paths inside the fixtures directory."""

    def __call__(self, *fixture_name: str | os.PathLike[str], must_exist: bool = True) -> Path:
        """
        Construct a path to a fixture file.

        This method creates a path to a fixture file within the fixtures directory.
        It's used by the `path_for_fixture` fixture to provide a consistent interface
        for accessing test fixture files.

        Args:
            *fixture_name: One or more path components (e.g., "data", "sample.json").
                Can be strings or path-like objects.
            must_exist: If True (default), raise FileNotFoundError if the file does not exist.

        Returns:
            The constructed fixture path.

        Raises:
            FileNotFoundError: If must_exist=True and the fixture file doesn't exist.

        Example:
            Using the FixturePath protocol in a test:

            ```python
            def test_fixture_path(path_for_fixture: FixturePath):
                # Construct a path to a fixture file
                data_path = path_for_fixture("data", "sample.json")
                assert data_path.suffix == ".json"

                # Check if a file exists without raising an error
                optional_path = path_for_fixture("optional", "file.txt", must_exist=False)
            ```

        """
        ...
Functions
__call__(*fixture_name: str | os.PathLike[str], must_exist: bool = True) -> Path

Construct a path to a fixture file.

This method creates a path to a fixture file within the fixtures directory. It's used by the path_for_fixture fixture to provide a consistent interface for accessing test fixture files.

Parameters:

Name Type Description Default
*fixture_name str | PathLike[str]

One or more path components (e.g., "data", "sample.json"). Can be strings or path-like objects.

()
must_exist bool

If True (default), raise FileNotFoundError if the file does not exist.

True

Returns:

Type Description
Path

The constructed fixture path.

Raises:

Type Description
FileNotFoundError

If must_exist=True and the fixture file doesn't exist.

Example

Using the FixturePath protocol in a test:

def test_fixture_path(path_for_fixture: FixturePath):
    # Construct a path to a fixture file
    data_path = path_for_fixture("data", "sample.json")
    assert data_path.suffix == ".json"

    # Check if a file exists without raising an error
    optional_path = path_for_fixture("optional", "file.txt", must_exist=False)
Source code in src/pytest_fixtures_fixtures/protocols.py
def __call__(self, *fixture_name: str | os.PathLike[str], must_exist: bool = True) -> Path:
    """
    Construct a path to a fixture file.

    This method creates a path to a fixture file within the fixtures directory.
    It's used by the `path_for_fixture` fixture to provide a consistent interface
    for accessing test fixture files.

    Args:
        *fixture_name: One or more path components (e.g., "data", "sample.json").
            Can be strings or path-like objects.
        must_exist: If True (default), raise FileNotFoundError if the file does not exist.

    Returns:
        The constructed fixture path.

    Raises:
        FileNotFoundError: If must_exist=True and the fixture file doesn't exist.

    Example:
        Using the FixturePath protocol in a test:

        ```python
        def test_fixture_path(path_for_fixture: FixturePath):
            # Construct a path to a fixture file
            data_path = path_for_fixture("data", "sample.json")
            assert data_path.suffix == ".json"

            # Check if a file exists without raising an error
            optional_path = path_for_fixture("optional", "file.txt", must_exist=False)
        ```

    """
    ...

ReadCsvDictFixture

Bases: Protocol

A callable that reads and parses CSV fixture files as dictionaries.

Source code in src/pytest_fixtures_fixtures/protocols.py
class ReadCsvDictFixture(Protocol):
    """A callable that reads and parses CSV fixture files as dictionaries."""

    def __call__(
        self,
        *fixture_name: str | os.PathLike[str],
        encoding: str = "utf-8",
    ) -> Generator[dict[str, str], None, None]:
        """
        Read and parse a CSV fixture file as dictionaries.

        This method reads CSV fixture files using Python's built-in csv.DictReader.
        The result is a generator of dictionaries, one for each row in the file.
        Each row is returned as a dictionary with column headers as keys and
        row values as string values.

        Args:
            *fixture_name: Components of the CSV fixture file path. Can be strings or path-like objects.
            encoding: Text encoding to use when reading the file (default: "utf-8").

        Returns:
            A generator of dictionaries, one for each row in the CSV file.

        Raises:
            FileNotFoundError: If the fixture file doesn't exist.
            csv.Error: If the file contains malformed CSV data.

        Example:
            Using the ReadCsvDictFixture protocol in a test:

            ```python
            def test_user_data(read_csv_dict_fixture: ReadCsvDictFixture):
                users = read_csv_dict_fixture("data", "users.csv")
                first_user = next(users)
                assert first_user["name"] == "Alice"
            ```

        """
        ...
Functions
__call__(*fixture_name: str | os.PathLike[str], encoding: str = 'utf-8') -> Generator[dict[str, str], None, None]

Read and parse a CSV fixture file as dictionaries.

This method reads CSV fixture files using Python's built-in csv.DictReader. The result is a generator of dictionaries, one for each row in the file. Each row is returned as a dictionary with column headers as keys and row values as string values.

Parameters:

Name Type Description Default
*fixture_name str | PathLike[str]

Components of the CSV fixture file path. Can be strings or path-like objects.

()
encoding str

Text encoding to use when reading the file (default: "utf-8").

'utf-8'

Returns:

Type Description
None

A generator of dictionaries, one for each row in the CSV file.

Raises:

Type Description
FileNotFoundError

If the fixture file doesn't exist.

Error

If the file contains malformed CSV data.

Example

Using the ReadCsvDictFixture protocol in a test:

def test_user_data(read_csv_dict_fixture: ReadCsvDictFixture):
    users = read_csv_dict_fixture("data", "users.csv")
    first_user = next(users)
    assert first_user["name"] == "Alice"
Source code in src/pytest_fixtures_fixtures/protocols.py
def __call__(
    self,
    *fixture_name: str | os.PathLike[str],
    encoding: str = "utf-8",
) -> Generator[dict[str, str], None, None]:
    """
    Read and parse a CSV fixture file as dictionaries.

    This method reads CSV fixture files using Python's built-in csv.DictReader.
    The result is a generator of dictionaries, one for each row in the file.
    Each row is returned as a dictionary with column headers as keys and
    row values as string values.

    Args:
        *fixture_name: Components of the CSV fixture file path. Can be strings or path-like objects.
        encoding: Text encoding to use when reading the file (default: "utf-8").

    Returns:
        A generator of dictionaries, one for each row in the CSV file.

    Raises:
        FileNotFoundError: If the fixture file doesn't exist.
        csv.Error: If the file contains malformed CSV data.

    Example:
        Using the ReadCsvDictFixture protocol in a test:

        ```python
        def test_user_data(read_csv_dict_fixture: ReadCsvDictFixture):
            users = read_csv_dict_fixture("data", "users.csv")
            first_user = next(users)
            assert first_user["name"] == "Alice"
        ```

    """
    ...

ReadCsvFixture

Bases: Protocol

A callable that reads and parses CSV fixture files.

Source code in src/pytest_fixtures_fixtures/protocols.py
class ReadCsvFixture(Protocol):
    """A callable that reads and parses CSV fixture files."""

    def __call__(
        self,
        *fixture_name: str | os.PathLike[str],
        encoding: str = "utf-8",
    ) -> Generator[list[str], None, None]:
        """
        Read and parse a CSV fixture file.

        This method reads CSV fixture files using Python's built-in csv.reader.
        The result is a generator of lists, one for each row in the file.
        Each row is returned as a list of strings.

        Args:
            *fixture_name: Components of the CSV fixture file path. Can be strings or path-like objects.
            encoding: Text encoding to use when reading the file (default: "utf-8").

        Returns:
            A generator of lists, one for each row in the CSV file.

        Raises:
            FileNotFoundError: If the fixture file doesn't exist.
            csv.Error: If the file contains malformed CSV data.

        Example:
            Using the ReadCsvFixture protocol in a test:

            ```python
            def test_user_data(read_csv_fixture: ReadCsvFixture):
                rows = read_csv_fixture("data", "users.csv")
                header = next(rows)  # First row is typically headers
                assert header == ["name", "age", "email"]
            ```

        """
        ...
Functions
__call__(*fixture_name: str | os.PathLike[str], encoding: str = 'utf-8') -> Generator[list[str], None, None]

Read and parse a CSV fixture file.

This method reads CSV fixture files using Python's built-in csv.reader. The result is a generator of lists, one for each row in the file. Each row is returned as a list of strings.

Parameters:

Name Type Description Default
*fixture_name str | PathLike[str]

Components of the CSV fixture file path. Can be strings or path-like objects.

()
encoding str

Text encoding to use when reading the file (default: "utf-8").

'utf-8'

Returns:

Type Description
None

A generator of lists, one for each row in the CSV file.

Raises:

Type Description
FileNotFoundError

If the fixture file doesn't exist.

Error

If the file contains malformed CSV data.

Example

Using the ReadCsvFixture protocol in a test:

def test_user_data(read_csv_fixture: ReadCsvFixture):
    rows = read_csv_fixture("data", "users.csv")
    header = next(rows)  # First row is typically headers
    assert header == ["name", "age", "email"]
Source code in src/pytest_fixtures_fixtures/protocols.py
def __call__(
    self,
    *fixture_name: str | os.PathLike[str],
    encoding: str = "utf-8",
) -> Generator[list[str], None, None]:
    """
    Read and parse a CSV fixture file.

    This method reads CSV fixture files using Python's built-in csv.reader.
    The result is a generator of lists, one for each row in the file.
    Each row is returned as a list of strings.

    Args:
        *fixture_name: Components of the CSV fixture file path. Can be strings or path-like objects.
        encoding: Text encoding to use when reading the file (default: "utf-8").

    Returns:
        A generator of lists, one for each row in the CSV file.

    Raises:
        FileNotFoundError: If the fixture file doesn't exist.
        csv.Error: If the file contains malformed CSV data.

    Example:
        Using the ReadCsvFixture protocol in a test:

        ```python
        def test_user_data(read_csv_fixture: ReadCsvFixture):
            rows = read_csv_fixture("data", "users.csv")
            header = next(rows)  # First row is typically headers
            assert header == ["name", "age", "email"]
        ```

    """
    ...

ReadFixture

Bases: Protocol

A callable that reads and optionally deserializes fixture files.

Source code in src/pytest_fixtures_fixtures/protocols.py
class ReadFixture(Protocol):
    """A callable that reads and optionally deserializes fixture files."""

    def __call__(
        self,
        *fixture_name: str | os.PathLike[str],
        encoding: str = "utf-8",
        mode: str = "r",
        deserialize: Callable[[str | bytes], Any] = lambda x: x,
    ) -> Any:
        r"""
        Read and optionally deserialize a fixture file.

        This method reads fixture files with customizable encoding, file mode,
        and deserialization. It's used by various read fixture functions to
        provide a consistent interface for accessing fixture file contents.

        Args:
            *fixture_name: Components of the fixture file path. Can be strings or path-like objects.
            encoding: Text encoding to use when reading the file (default: "utf-8").
            mode: File open mode (default: "r" for text mode).
            deserialize: Function to process the file contents. Takes str or bytes and returns Any (default: identity).

        Returns:
            The result of applying the deserialize function to the file contents.

        Raises:
            FileNotFoundError: If the fixture file doesn't exist.
            UnicodeDecodeError: If the file cannot be decoded with the specified encoding.
            OSError: If there's an error reading the file.

        Example:
            Using the ReadFixture protocol in a test:

            ```python
            def test_read_fixture(read_fixture: ReadFixture):
                # Read a text file
                content = read_fixture("data", "sample.txt")
                assert "hello" in content

                # Read a binary file
                data = read_fixture("images", "logo.png", mode="rb", deserialize=lambda x: x)
                assert data.startswith(b'\x89PNG')
            ```

        """
        ...
Functions
__call__(*fixture_name: str | os.PathLike[str], encoding: str = 'utf-8', mode: str = 'r', deserialize: Callable[[str | bytes], Any] = lambda x: x) -> Any

Read and optionally deserialize a fixture file.

This method reads fixture files with customizable encoding, file mode, and deserialization. It's used by various read fixture functions to provide a consistent interface for accessing fixture file contents.

Parameters:

Name Type Description Default
*fixture_name str | PathLike[str]

Components of the fixture file path. Can be strings or path-like objects.

()
encoding str

Text encoding to use when reading the file (default: "utf-8").

'utf-8'
mode str

File open mode (default: "r" for text mode).

'r'
deserialize Callable[[str | bytes], Any]

Function to process the file contents. Takes str or bytes and returns Any (default: identity).

lambda x: x

Returns:

Type Description
Any

The result of applying the deserialize function to the file contents.

Raises:

Type Description
FileNotFoundError

If the fixture file doesn't exist.

UnicodeDecodeError

If the file cannot be decoded with the specified encoding.

OSError

If there's an error reading the file.

Example

Using the ReadFixture protocol in a test:

def test_read_fixture(read_fixture: ReadFixture):
    # Read a text file
    content = read_fixture("data", "sample.txt")
    assert "hello" in content

    # Read a binary file
    data = read_fixture("images", "logo.png", mode="rb", deserialize=lambda x: x)
    assert data.startswith(b'\x89PNG')
Source code in src/pytest_fixtures_fixtures/protocols.py
def __call__(
    self,
    *fixture_name: str | os.PathLike[str],
    encoding: str = "utf-8",
    mode: str = "r",
    deserialize: Callable[[str | bytes], Any] = lambda x: x,
) -> Any:
    r"""
    Read and optionally deserialize a fixture file.

    This method reads fixture files with customizable encoding, file mode,
    and deserialization. It's used by various read fixture functions to
    provide a consistent interface for accessing fixture file contents.

    Args:
        *fixture_name: Components of the fixture file path. Can be strings or path-like objects.
        encoding: Text encoding to use when reading the file (default: "utf-8").
        mode: File open mode (default: "r" for text mode).
        deserialize: Function to process the file contents. Takes str or bytes and returns Any (default: identity).

    Returns:
        The result of applying the deserialize function to the file contents.

    Raises:
        FileNotFoundError: If the fixture file doesn't exist.
        UnicodeDecodeError: If the file cannot be decoded with the specified encoding.
        OSError: If there's an error reading the file.

    Example:
        Using the ReadFixture protocol in a test:

        ```python
        def test_read_fixture(read_fixture: ReadFixture):
            # Read a text file
            content = read_fixture("data", "sample.txt")
            assert "hello" in content

            # Read a binary file
            data = read_fixture("images", "logo.png", mode="rb", deserialize=lambda x: x)
            assert data.startswith(b'\x89PNG')
        ```

    """
    ...

ReadJsonFixture

Bases: Protocol

A callable that reads and parses JSON fixture files.

Source code in src/pytest_fixtures_fixtures/protocols.py
class ReadJsonFixture(Protocol):
    """A callable that reads and parses JSON fixture files."""

    def __call__(
        self,
        *fixture_name: str | os.PathLike[str],
        encoding: str = "utf-8",
    ) -> dict:
        """
        Read and parse a JSON fixture file.

        This method reads JSON fixture files and automatically parses them
        into Python dictionaries.

        Args:
            *fixture_name: Components of the JSON fixture file path. Can be strings or path-like objects.
            encoding: Text encoding to use when reading the file (default: "utf-8").

        Returns:
            The parsed JSON data as a Python dictionary.

        Raises:
            FileNotFoundError: If the fixture file doesn't exist.
            json.JSONDecodeError: If the file contains invalid JSON.

        Example:
            Using the ReadJsonFixture protocol in a test:

            ```python
            def test_config_data(read_json_fixture: ReadJsonFixture):
                config = read_json_fixture("config", "settings.json")
                assert config["database"]["host"] == "localhost"
            ```

        """
        ...
Functions
__call__(*fixture_name: str | os.PathLike[str], encoding: str = 'utf-8') -> dict

Read and parse a JSON fixture file.

This method reads JSON fixture files and automatically parses them into Python dictionaries.

Parameters:

Name Type Description Default
*fixture_name str | PathLike[str]

Components of the JSON fixture file path. Can be strings or path-like objects.

()
encoding str

Text encoding to use when reading the file (default: "utf-8").

'utf-8'

Returns:

Type Description
dict

The parsed JSON data as a Python dictionary.

Raises:

Type Description
FileNotFoundError

If the fixture file doesn't exist.

JSONDecodeError

If the file contains invalid JSON.

Example

Using the ReadJsonFixture protocol in a test:

def test_config_data(read_json_fixture: ReadJsonFixture):
    config = read_json_fixture("config", "settings.json")
    assert config["database"]["host"] == "localhost"
Source code in src/pytest_fixtures_fixtures/protocols.py
def __call__(
    self,
    *fixture_name: str | os.PathLike[str],
    encoding: str = "utf-8",
) -> dict:
    """
    Read and parse a JSON fixture file.

    This method reads JSON fixture files and automatically parses them
    into Python dictionaries.

    Args:
        *fixture_name: Components of the JSON fixture file path. Can be strings or path-like objects.
        encoding: Text encoding to use when reading the file (default: "utf-8").

    Returns:
        The parsed JSON data as a Python dictionary.

    Raises:
        FileNotFoundError: If the fixture file doesn't exist.
        json.JSONDecodeError: If the file contains invalid JSON.

    Example:
        Using the ReadJsonFixture protocol in a test:

        ```python
        def test_config_data(read_json_fixture: ReadJsonFixture):
            config = read_json_fixture("config", "settings.json")
            assert config["database"]["host"] == "localhost"
        ```

    """
    ...

ReadJsonlFixture

Bases: Protocol

A callable that reads and parses JSONL (JSON Lines) fixture files.

Source code in src/pytest_fixtures_fixtures/protocols.py
class ReadJsonlFixture(Protocol):
    """A callable that reads and parses JSONL (JSON Lines) fixture files."""

    def __call__(
        self,
        *fixture_name: str | os.PathLike[str],
        encoding: str = "utf-8",
    ) -> Generator[dict, None, None]:
        """
        Read and parse a JSONL (JSON Lines) fixture file.

        This method reads JSONL fixture files, where each line contains a separate
        JSON object. The result is a generator of dictionaries, one for each line
        in the file.

        Args:
            *fixture_name: Components of the JSONL fixture file path. Can be strings or path-like objects.
            encoding: Text encoding to use when reading the file (default: "utf-8").

        Returns:
            A generator of dictionaries, one for each JSON object in the file.

        Raises:
            FileNotFoundError: If the fixture file doesn't exist.
            json.JSONDecodeError: If any line contains invalid JSON.

        Example:
            Using the ReadJsonlFixture protocol in a test:

            ```python
            def test_log_entries(read_jsonl_fixture: ReadJsonlFixture):
                logs = read_jsonl_fixture("logs", "access.jsonl")
                first_log = next(logs)
                assert "timestamp" in first_log
            ```

        """
        ...
Functions
__call__(*fixture_name: str | os.PathLike[str], encoding: str = 'utf-8') -> Generator[dict, None, None]

Read and parse a JSONL (JSON Lines) fixture file.

This method reads JSONL fixture files, where each line contains a separate JSON object. The result is a generator of dictionaries, one for each line in the file.

Parameters:

Name Type Description Default
*fixture_name str | PathLike[str]

Components of the JSONL fixture file path. Can be strings or path-like objects.

()
encoding str

Text encoding to use when reading the file (default: "utf-8").

'utf-8'

Returns:

Type Description
None

A generator of dictionaries, one for each JSON object in the file.

Raises:

Type Description
FileNotFoundError

If the fixture file doesn't exist.

JSONDecodeError

If any line contains invalid JSON.

Example

Using the ReadJsonlFixture protocol in a test:

def test_log_entries(read_jsonl_fixture: ReadJsonlFixture):
    logs = read_jsonl_fixture("logs", "access.jsonl")
    first_log = next(logs)
    assert "timestamp" in first_log
Source code in src/pytest_fixtures_fixtures/protocols.py
def __call__(
    self,
    *fixture_name: str | os.PathLike[str],
    encoding: str = "utf-8",
) -> Generator[dict, None, None]:
    """
    Read and parse a JSONL (JSON Lines) fixture file.

    This method reads JSONL fixture files, where each line contains a separate
    JSON object. The result is a generator of dictionaries, one for each line
    in the file.

    Args:
        *fixture_name: Components of the JSONL fixture file path. Can be strings or path-like objects.
        encoding: Text encoding to use when reading the file (default: "utf-8").

    Returns:
        A generator of dictionaries, one for each JSON object in the file.

    Raises:
        FileNotFoundError: If the fixture file doesn't exist.
        json.JSONDecodeError: If any line contains invalid JSON.

    Example:
        Using the ReadJsonlFixture protocol in a test:

        ```python
        def test_log_entries(read_jsonl_fixture: ReadJsonlFixture):
            logs = read_jsonl_fixture("logs", "access.jsonl")
            first_log = next(logs)
            assert "timestamp" in first_log
        ```

    """
    ...

ReadYamlFixture

Bases: Protocol

A callable that reads and parses YAML fixture files.

Source code in src/pytest_fixtures_fixtures/protocols.py
class ReadYamlFixture(Protocol):
    """A callable that reads and parses YAML fixture files."""

    def __call__(
        self,
        *fixture_name: str | os.PathLike[str],
        encoding: str = "utf-8",
        unsafe_load: bool = False,
    ) -> Any:
        """
        Read and parse a YAML fixture file.

        This method reads YAML fixture files and automatically parses them into
        Python objects (typically dictionaries). Requires the PyYAML library
        to be installed.

        Args:
            *fixture_name: Components of the YAML fixture file path. Can be strings or path-like objects.
            encoding: Text encoding to use when reading the file (default: "utf-8").
            unsafe_load: If True, uses yaml.FullLoader instead of yaml.SafeLoader (default: False).
                        WARNING: Only use unsafe_load=True with trusted YAML content.

        Returns:
            The parsed YAML data (typically a dictionary or list).

        Raises:
            ImportError: If PyYAML is not installed.
            FileNotFoundError: If the fixture file doesn't exist.
            yaml.YAMLError: If the file contains invalid YAML syntax.

        Example:
            Using the ReadYamlFixture protocol in a test:

            ```python
            def test_config_data(read_yaml_fixture: ReadYamlFixture):
                config = read_yaml_fixture("config", "settings.yaml")
                assert config["database"]["host"] == "localhost"
            ```

        """
        ...
Functions
__call__(*fixture_name: str | os.PathLike[str], encoding: str = 'utf-8', unsafe_load: bool = False) -> Any

Read and parse a YAML fixture file.

This method reads YAML fixture files and automatically parses them into Python objects (typically dictionaries). Requires the PyYAML library to be installed.

Parameters:

Name Type Description Default
*fixture_name str | PathLike[str]

Components of the YAML fixture file path. Can be strings or path-like objects.

()
encoding str

Text encoding to use when reading the file (default: "utf-8").

'utf-8'
unsafe_load bool

If True, uses yaml.FullLoader instead of yaml.SafeLoader (default: False). WARNING: Only use unsafe_load=True with trusted YAML content.

False

Returns:

Type Description
Any

The parsed YAML data (typically a dictionary or list).

Raises:

Type Description
ImportError

If PyYAML is not installed.

FileNotFoundError

If the fixture file doesn't exist.

YAMLError

If the file contains invalid YAML syntax.

Example

Using the ReadYamlFixture protocol in a test:

def test_config_data(read_yaml_fixture: ReadYamlFixture):
    config = read_yaml_fixture("config", "settings.yaml")
    assert config["database"]["host"] == "localhost"
Source code in src/pytest_fixtures_fixtures/protocols.py
def __call__(
    self,
    *fixture_name: str | os.PathLike[str],
    encoding: str = "utf-8",
    unsafe_load: bool = False,
) -> Any:
    """
    Read and parse a YAML fixture file.

    This method reads YAML fixture files and automatically parses them into
    Python objects (typically dictionaries). Requires the PyYAML library
    to be installed.

    Args:
        *fixture_name: Components of the YAML fixture file path. Can be strings or path-like objects.
        encoding: Text encoding to use when reading the file (default: "utf-8").
        unsafe_load: If True, uses yaml.FullLoader instead of yaml.SafeLoader (default: False).
                    WARNING: Only use unsafe_load=True with trusted YAML content.

    Returns:
        The parsed YAML data (typically a dictionary or list).

    Raises:
        ImportError: If PyYAML is not installed.
        FileNotFoundError: If the fixture file doesn't exist.
        yaml.YAMLError: If the file contains invalid YAML syntax.

    Example:
        Using the ReadYamlFixture protocol in a test:

        ```python
        def test_config_data(read_yaml_fixture: ReadYamlFixture):
            config = read_yaml_fixture("config", "settings.yaml")
            assert config["database"]["host"] == "localhost"
        ```

    """
    ...

Functions

parametrize_from_fixture(fixture_name: str, *, file_format: str = 'auto', encoding: str = 'utf-8', fixtures_dir: str | Path | None = None, id_field: str | None = 'id', **kwargs: Any) -> Callable[[F], F]

Parametrize a test function using data from a fixture file.

This decorator reads data from a fixture file and automatically applies pytest.mark.parametrize to the test function. It supports CSV, JSON, JSONL, and YAML file formats.

Parameters:

Name Type Description Default
fixture_name str

Path to the fixture file relative to the fixtures directory.

required
file_format str

File format ("csv", "json", "jsonl", "yaml", or "auto" to detect from extension).

'auto'
encoding str

Text encoding to use when reading the file (default: "utf-8").

'utf-8'
fixtures_dir str | Path | None

Override the fixtures directory path. If None, defaults to "tests/fixtures/".

None
id_field str | None

The field name to use for test IDs. If None, no test IDs will be used. Defaults to "id".

'id'
**kwargs Any

Additional arguments passed to pytest.mark.parametrize.

{}

Returns:

Type Description
Callable[[F], F]

A decorator that parametrizes the test function.

Raises:

Type Description
ValueError

If the file format is unsupported or data format is invalid.

FileNotFoundError

If the fixture file doesn't exist.

ImportError

If a required library is not installed.

Note

Test IDs can be specified using a special column (CSV) or key (JSON/JSONL/YAML). When present, these IDs are automatically used for test identification. User-provided 'ids' parameter takes precedence over file-based IDs.

Example

CSV file with custom IDs:

id,value,expected
test_case_1,a,b
test_case_2,x,y

JSON file with custom IDs:

[
    {"id": "test_case_1", "value": "a", "expected": "b"},
    {"id": "test_case_2", "value": "x", "expected": "y"}
]

Usage:

@parametrize_from_fixture("data.csv")
def test_something(value, expected):
    # Runs with test IDs: test_case_1, test_case_2
    assert value != expected

Source code in src/pytest_fixtures_fixtures/parametrize.py
def parametrize_from_fixture(  # noqa: C901
    fixture_name: str,
    *,
    file_format: str = "auto",
    encoding: str = "utf-8",
    fixtures_dir: str | Path | None = None,
    id_field: str | None = "id",
    **kwargs: Any,
) -> Callable[[F], F]:
    """
    Parametrize a test function using data from a fixture file.

    This decorator reads data from a fixture file and automatically applies
    pytest.mark.parametrize to the test function. It supports CSV, JSON, JSONL,
    and YAML file formats.

    Args:
        fixture_name: Path to the fixture file relative to the fixtures directory.
        file_format: File format ("csv", "json", "jsonl", "yaml", or "auto" to detect from extension).
        encoding: Text encoding to use when reading the file (default: "utf-8").
        fixtures_dir: Override the fixtures directory path. If None, defaults to "tests/fixtures/".
        id_field: The field name to use for test IDs. If None, no test IDs will be used. Defaults to "id".
        **kwargs: Additional arguments passed to pytest.mark.parametrize.

    Returns:
        A decorator that parametrizes the test function.

    Raises:
        ValueError: If the file format is unsupported or data format is invalid.
        FileNotFoundError: If the fixture file doesn't exist.
        ImportError: If a required library is not installed.

    Note:
        Test IDs can be specified using a special column (CSV) or key (JSON/JSONL/YAML).
        When present, these IDs are automatically used for test identification. User-provided
        'ids' parameter takes precedence over file-based IDs.

    Example:
        CSV file with custom IDs:
        ```csv
        id,value,expected
        test_case_1,a,b
        test_case_2,x,y
        ```

        JSON file with custom IDs:
        ```json
        [
            {"id": "test_case_1", "value": "a", "expected": "b"},
            {"id": "test_case_2", "value": "x", "expected": "y"}
        ]
        ```

        Usage:
        ```python
        @parametrize_from_fixture("data.csv")
        def test_something(value, expected):
            # Runs with test IDs: test_case_1, test_case_2
            assert value != expected
        ```

    """

    def decorator(og_test_func: F) -> F:  # noqa: C901, PLR0912
        fixtures_path = _get_fixtures_path(fixtures_dir)

        # Detect file format if auto
        detected_format = file_format
        if detected_format == "auto":
            suffix = Path(fixture_name).suffix.lower()
            if suffix == ".csv":
                detected_format = "csv"
            elif suffix == ".json":
                detected_format = "json"
            elif suffix == ".jsonl":
                detected_format = "jsonl"
            elif suffix in [".yaml", ".yml"]:
                detected_format = "yaml"
            else:
                raise ValueError(f"Cannot auto-detect format for file: {fixture_name}")

        # Read the fixture file
        fixture_path = fixtures_path / fixture_name
        if not fixture_path.exists():
            raise FileNotFoundError(f"Fixture {fixture_name} does not exist at {fixture_path}")

        # Parse based on format
        if detected_format == "csv":
            param_names, param_values, test_ids = _read_csv_for_parametrize(fixture_path, encoding, id_field)
        elif detected_format == "json":
            param_names, param_values, test_ids = _read_json_for_parametrize(fixture_path, encoding, id_field)
        elif detected_format == "jsonl":
            param_names, param_values, test_ids = _read_jsonl_for_parametrize(fixture_path, encoding, id_field)
        elif detected_format == "yaml":
            param_names, param_values, test_ids = _read_yaml_for_parametrize(fixture_path, encoding, id_field)
        else:
            raise ValueError(f"Unsupported file format: {detected_format}")

        # Apply parametrize with the data
        parametrize_kwargs = {"argnames": param_names, "argvalues": param_values, **kwargs}

        # Use extracted test IDs if available and not overridden by user
        if test_ids is not None and "ids" not in kwargs:
            parametrize_kwargs["ids"] = test_ids

        return pytest.mark.parametrize(**parametrize_kwargs)(og_test_func)

    return decorator