init.py


Overview

This module provides a generic mechanism for marking and selecting Python test functions within the pytest framework. Its primary focus is on handling test parameterization and filtering tests based on keywords or markers. It exposes core utilities such as the `param` function for defining parameter sets, and classes for matching keywords and markers in test selection. The module integrates tightly with pytest's command line interface (CLI) and collection hooks to enable expressive and flexible test selection using `-k` (keyword expressions) and `-m` (marker expressions) options.


Public API

The following names are exported for external use:


Detailed Explanations

Function: param

param(
    *values: object,
    marks: MarkDecorator | Collection[MarkDecorator | Mark] = (),
    id: str | _HiddenParam | None = None,
) -> ParameterSet

Creates a parameter set for use in `pytest.mark.parametrize` calls or parametrized fixtures.

import pytest

@pytest.mark.parametrize(
    "input, expected",
    [
        ("3+5", 8),
        pytest.param("6*9", 42, marks=pytest.mark.xfail),
    ],
)
def test_eval(input, expected):
    assert eval(input) == expected

Function: pytest_addoption

pytest_addoption(parser: Parser) -> None

Pytest hook to add CLI options related to test selection by keyword and marker expressions, as well as options to display registered markers.


Function: pytest_cmdline_main

def pytest_cmdline_main(config: Config) -> int | ExitCode | None

Pytest hook executed early during command line main execution.


Class: KeywordMatcher

@dataclasses.dataclass
class KeywordMatcher:
    _names: AbstractSet[str]

    @classmethod
    def from_item(cls, item: Item) -> KeywordMatcher:
        ...

    def __call__(self, subname: str, /) -> bool:
        ...

Matches tests based on keyword expressions (used with `-k`).

matcher = KeywordMatcher.from_item(test_item)
if matcher("somekeyword"):
    # matched

Function: deselect_by_keyword

def deselect_by_keyword(items: list[Item], config: Config) -> None

Filters out test items that do not match the keyword expression provided via the `-k` option.


Class: MarkMatcher

@dataclasses.dataclass
class MarkMatcher:
    own_mark_name_mapping: dict[str, list[Mark]]

    @classmethod
    def from_markers(cls, markers: Iterable[Mark]) -> MarkMatcher:
        ...

    def __call__(self, name: str, /, **kwargs: str | int | bool | None) -> bool:
        ...

Matches test items based on marker expressions (used with `-m`).

matcher = MarkMatcher.from_markers(item.iter_markers())
if matcher("xfail", reason="some reason"):
    # matched

Function: deselect_by_mark

def deselect_by_mark(items: list[Item], config: Config) -> None

Filters out test items that do not match the marker expression provided via the `-m` option.


Function: _parse_expression

def _parse_expression(expr: str, exc_message: str) -> Expression

Parses a string expression into an `Expression` object, handling parse errors by raising `UsageError` with a custom message.


Hook: pytest_collection_modifyitems

def pytest_collection_modifyitems(items: list[Item], config: Config) -> None

Modifies the list of collected test items by deselecting tests based on keyword and marker expressions.


Hook: pytest_configure

def pytest_configure(config: Config) -> None

Called during pytest configuration phase.


Hook: pytest_unconfigure

def pytest_unconfigure(config: Config) -> None

Called during pytest unconfiguration phase.


Important Implementation Details


Interactions with Other System Components


Visual Diagram

classDiagram
    class KeywordMatcher {
        -_names: AbstractSet[str]
        +from_item(item: Item) KeywordMatcher
        +__call__(subname: str) bool
    }

    class MarkMatcher {
        -own_mark_name_mapping: dict[str, list[Mark]]
        +from_markers(markers: Iterable[Mark]) MarkMatcher
        +__call__(name: str, **kwargs) bool
    }

    class ParameterSet {
        +param(*values, marks=(), id=None) ParameterSet
    }

    class __init__py {
        +param(*values, marks=(), id=None) ParameterSet
        +pytest_addoption(parser: Parser)
        +pytest_cmdline_main(config: Config) int | ExitCode | None
        +deselect_by_keyword(items: list[Item], config: Config)
        +deselect_by_mark(items: list[Item], config: Config)
        +pytest_collection_modifyitems(items: list[Item], config: Config)
        +pytest_configure(config: Config)
        +pytest_unconfigure(config: Config)
    }

    __init__py --> ParameterSet : uses
    __init__py --> KeywordMatcher : uses
    __init__py --> MarkMatcher : uses
    ParameterSet ..> MarkDecorator : composition
    MarkMatcher ..> Mark : composition
    KeywordMatcher ..> Item : depends on
    MarkMatcher ..> Item : depends on

Summary

This [__init__.py](/projects/286/67254) file is a core component in pytest's marking and test selection system. It provides the machinery to define parameter sets with optional marks, parse CLI options for selecting tests based on keyword and marker expressions, and integrate these selections into the test collection and execution lifecycle. By leveraging expression parsing and matchers for keywords and markers, it enables powerful and flexible test filtering capabilities accessible directly via command line options.


End of Documentation for init.py