### Install pytest-results with pip Source: https://github.com/100nm/pytest-results/blob/prod/README.md Install the plugin via pip. Requires Python 3.12 or higher. ```bash pip install pytest-results ``` -------------------------------- ### Usage example — reading resolved config in a custom hook Source: https://github.com/100nm/pytest-results Shows how to instantiate PytestResultsConfig from a pytest hook's config and inspect accept_diff and diff_command. The printed diff_command example is "code -d -r -w {current} {previous}". ```python from pytest_results.contrib.pytest.plugin import PytestResultsConfig def pytest_sessionfinish(session): config = PytestResultsConfig(session.config) if config.accept_diff: print("Snapshots will be updated") print(config.diff_command) # e.g. "code -d -r -w {current} {previous}" ``` -------------------------------- ### pyproject.toml configuration for pytest-results Source: https://github.com/100nm/pytest-results/blob/prod/docs/configuration.md Configuration file example for pyproject.toml. Sets the IDE to vscode under the [tool.pytest] section. ```toml # pyproject.toml [tool.pytest] ide = "vscode" ``` -------------------------------- ### pytest.ini configuration for pytest-results Source: https://github.com/100nm/pytest-results/blob/prod/docs/configuration.md Configuration file example for pytest.ini. Sets the IDE to vscode under the [pytest] section. ```ini # pytest.ini [pytest] ide = vscode ``` -------------------------------- ### Error handling for absolute paths in LocalStorage Source: https://github.com/100nm/pytest-results Demonstrates that passing an absolute path to get_absolute_path raises an AssertionError. The example catches the exception and prints a message. ```python from pathlib import Path from pytest_results._core.storages.local import LocalStorage storage = LocalStorage(Path("results"), Path("tmp")) try: storage.get_absolute_path(Path("/etc/passwd")) except AssertionError: print("Absolute snapshot paths are rejected") ``` -------------------------------- ### Usage example — first run fails, second run passes Source: https://github.com/100nm/pytest-results Shows how to instantiate `_RegressionImpl` directly with a `LocalStorage` and a `command_runner` that runs diff commands via `subprocess.run`. The first `check` call raises `ResultsMismatchError` and writes current bytes to a temp file; after accepting the snapshot, the same call returns normally. ```python from pytest_results import _RegressionImpl # internal, shown for completeness from pytest_results._core.storages.local import LocalStorage from functools import partial import subprocess storage = LocalStorage(Path("__pytest_results__"), Path("/tmp/__pytest_results__")) impl = _RegressionImpl( testinfo=("tests", "test_module", "test_function"), storage=storage, command_runner=partial(subprocess.run, shell=True), ) # First run: raises ResultsMismatchError, writes current bytes to a temp file. impl.check({"hello": "world"}) # After accepting the snapshot, the same call returns normally. impl.check({"hello": "world"}) ``` -------------------------------- ### Basic usage example Source: https://github.com/100nm/pytest-results Serializes a dict with a datetime value. The output is JSON indented by 2 spaces, with the datetime converted to ISO 8601 string. ```python from datetime import datetime from pytest_results._core.dump_functions.json import json_dump payload = {"title": "Hello, World!", "created": datetime(2024, 1, 1, 12, 0, 0)} snapshot_bytes = json_dump(payload) print(snapshot_bytes.decode()) # { # "title": "Hello, World!", # "created": "2024-01-01T12:00:00" # } ``` -------------------------------- ### Usage example — custom suffix and format Source: https://github.com/100nm/pytest-results Shows using the `regression` fixture to call `check` with a custom `suffix` and `file_format`. The suffix is appended to the file name base and the format determines the snapshot file extension. ```python def test_total(regression: Regression) -> None: regression.check(120, suffix="[1]", file_format="json") ``` -------------------------------- ### Usage example — regression fixture in a test Source: https://github.com/100nm/pytest-results Shows how to use the regression fixture in a test: regression.check stores results as JSON files, with optional suffix for additional checks. ```python from pytest_results import Regression def test_order_total(regression: Regression) -> None: total = compute_total() regression.check(total) # .json regression.check({"tax": total * 0.2}, suffix="-tax") # -tax.json ``` -------------------------------- ### Usage example: several checks in one test Source: https://github.com/100nm/pytest-results Shows how to use RegressionStack via the regression fixture to run multiple checks in a single test. Each check creates a snapshot file; mismatches are collected and raised together as an ExceptionGroup at the end. ```python from pytest_results import Regression def test_orders(regression: Regression) -> None: for i in range(3): regression.check({"index": i}) # 3 snapshots: .json, _1.json, _2.json ``` -------------------------------- ### Catch ResultsMismatchError Source: https://github.com/100nm/pytest-results Example of catching ResultsMismatchError when a regression check fails, including using the mismatch object's properties and actions. ```APIDOC ### Description Example of catching ResultsMismatchError when a regression check fails, including using the mismatch object's properties and actions. ### Code ```python from pathlib import Path from pytest_results import Regression from pytest_results.exceptions import PytestResultsError, ResultsMismatchError try: regression.check({"version": 2}) except ResultsMismatchError as mismatch: print(mismatch.current, mismatch.previous) mismatch.accept_diff() # promote new result to snapshot except PytestResultsError: # broader base class ... ``` ``` -------------------------------- ### pytest_collection_modifyitems hook Source: https://github.com/100nm/pytest-results Wraps each collected pytest.Function with __autodetect_result to check results after execution. Async functions get an async wrapper. Returning None skips result checking. ```python @pytest.hookimpl def pytest_collection_modifyitems(items: Iterable[pytest.Item]) -> None: for item in items: if isinstance(item, pytest.Function): __autodetect_result(item) ``` -------------------------------- ### get_testinfo returns derived tuple type Source: https://github.com/100nm/pytest-results get_testinfo (pytest_results/_testinfo.py:8) returns a tuple of strings derived from the request fixture. __iter_testinfo yields module name split by dots, class name if inside a class, then function name. The tuple becomes the testinfo sequence of RegressionImpl; last element is snapshot file-name base, preceding ones are directory components. Example for tests/test_orders.py::TestOrder::test_total: ("tests", "test_orders", "TestOrder", "test_total"). Import: from pytest_results._testinfo import get_testinfo. ```python def get_testinfo(request: pytest.FixtureRequest) -> tuple[str, ...]: return tuple(__iter_testinfo(request)) ``` -------------------------------- ### Standalone usage of LocalStorage Source: https://github.com/100nm/pytest-results Shows how to instantiate LocalStorage with a snapshot directory and a temporary directory, then write, read, and check existence of a snapshot file. Reading a missing snapshot returns empty bytes instead of raising an error. ```python from pathlib import Path from pytest_results._core.storages.local import LocalStorage storage = LocalStorage(Path("__pytest_results__"), Path("/tmp/__pytest_results__")) storage.write(Path("tests/test_module/test_function.json"), b'{"hello": "world"}') assert storage.read(Path("tests/test_module/test_function.json")) == b'{"hello": "world"}' assert storage.exists(Path("tests/test_module/test_function.json")) is True # read of a missing snapshot yields empty bytes, not an error: assert storage.read(Path("missing.json")) == b"" ``` -------------------------------- ### Use regression.check for more control Source: https://github.com/100nm/pytest-results/blob/prod/docs/regression-fixture.md For more control, use the regression fixture and call regression.check. A test returning None checks nothing. ```python from pytest_results import Regression def test_function(regression: Regression) -> None: result = ... regression.check(result) ``` -------------------------------- ### pytest --ide vscode command Source: https://github.com/100nm/pytest-results/blob/prod/docs/configuration.md Opens each mismatch in an interactive comparison of the IDE. The test still fails. ```bash pytest --ide vscode ``` -------------------------------- ### LocalStorage.write Source: https://github.com/100nm/pytest-results Writes binary data to a file, creating parent directories if necessary. This method is part of the LocalStorage class and is used to write snapshot files. ```APIDOC ## LocalStorage.write ### Description Writes binary data to a file, creating parent directories if necessary. This method is part of the LocalStorage class and is used to write snapshot files. ### Method write(self, filepath: Path, result: bytes = b"") -> None ### Parameters - **filepath** (Path) - Required - Path to the file to write - **result** (bytes) - Optional - Binary data to write (default: `b""`) ### Returns None ### Behavior Creates parent directories with `os.makedirs(..., exist_ok=True)` and writes `result` in binary mode. ``` -------------------------------- ### Import Storage and LocalStorage Source: https://github.com/100nm/pytest-results Imports the Storage protocol and LocalStorage implementation, plus internal top-level re-exports. ```python from pytest_results._core.storages.abc import Storage from pytest_results._core.storages.local import LocalStorage from pytest_results import _Storage, _LocalStorage # internal top-level re-exports ``` -------------------------------- ### show_diff(command) Source: https://github.com/100nm/pytest-results Runs a diff command for this mismatch. The previous snapshot is created empty if missing, then the command template is formatted with current and previous placeholders and passed to the command runner. Returns None. ```APIDOC ## show_diff(command) ### Description Runs a diff command for this mismatch. The `previous` snapshot is created empty if missing (`__ensure_file_exists`), then `command.format(current=self.current, previous=self.previous)` substitutes the placeholders and the formatted string is passed to `command_runner`. ### Method show_diff ### Signature `def show_diff(self, command: str) -> None` ### Parameters #### Parameters - **command** (str) - Required - Template with `{current}` and `{previous}` placeholders, e.g. `"code -d -r -w {current} {previous}"` ### Returns `None` ### Raises Whatever the `command_runner` raises (in the plugin, `subprocess.run` errors propagate); `KeyError`/`IndexError`/`ValueError` from `str.format` if the template does not contain exactly the expected placeholders or contains malformed braces. ``` -------------------------------- ### Pytest 11 plugin entry point configuration Source: https://github.com/100nm/pytest-results Declares the pytest plugin entry point in pyproject.toml for auto-loading. The module path points to the plugin implementation. ```toml pytest-results = "pytest_results.contrib.pytest.plugin" ``` -------------------------------- ### Parameters of regression.check Source: https://github.com/100nm/pytest-results/blob/prod/docs/regression-fixture.md Shows the signature of regression.check with its parameters: suffix, dump_func, and file_format. file_format defaults to "json". ```python regression.check( result, suffix=None, # appended to the file name dump_func=None, # converts the result to bytes file_format=None, # file extension, "json" by default ) ``` -------------------------------- ### LocalStorage.copy Source: https://github.com/100nm/pytest-results Copies a file from one path to another using shutil.copyfile. This method is part of the LocalStorage class and is used to copy snapshot files. ```APIDOC ## LocalStorage.copy ### Description Copies a file from one path to another using shutil.copyfile. This method is part of the LocalStorage class and is used to copy snapshot files. ### Method copy(self, filepath: Path, destination: Path) -> None ### Parameters - **filepath** (Path) - Required - Source file path - **destination** (Path) - Required - Destination file path ### Returns None ### Behavior Calls `shutil.copyfile(filepath, destination)`. ``` -------------------------------- ### Custom regression fixture with BoundRegression Source: https://github.com/100nm/pytest-results/blob/prod/docs/regression-fixture.md To reuse a format, bind it to a fixture with BoundRegression. Its check uses the bound dump_func and file_format, unless they are passed explicitly. The conftest.py defines the fixture, and the test uses it. ```python # conftest.py from typing import Any import pytest import yaml from pytest_results import BoundRegression, Regression def _yaml_dump(value: Any) -> bytes: return yaml.safe_dump(value).encode() @pytest.fixture def regression_yaml(regression: Regression) -> Regression: return BoundRegression(regression, dump_func=_yaml_dump, file_format="yml") ``` ```python from pytest_results import Regression def test_function(regression_yaml: Regression) -> None: result = ... regression_yaml.check(result) ``` -------------------------------- ### Async test returning result Source: https://github.com/100nm/pytest-results/blob/prod/docs/regression-fixture.md Async tests work the same way, but require an async plugin such as pytest-asyncio. ```python async def test_function() -> dict[str, str]: return {"hello": "world"} ``` -------------------------------- ### pytest --diff command Source: https://github.com/100nm/pytest-results/blob/prod/docs/configuration.md Runs a command line on each mismatch. Placeholders {current} and {previous} are replaced with paths. The test still fails. ```bash pytest --diff "meld {current} {previous}" ``` -------------------------------- ### Custom format with dump_func and file_format Source: https://github.com/100nm/pytest-results/blob/prod/docs/regression-fixture.md dump_func converts the result to the bytes of the snapshot, and file_format sets the extension of the snapshot file. ```python import yaml from pytest_results import Regression def test_function(regression: Regression) -> None: result = ... regression.check( result, dump_func=lambda value: yaml.safe_dump(value).encode(), file_format="yml", ) ``` -------------------------------- ### pytest --accept-diff command Source: https://github.com/100nm/pytest-results/blob/prod/docs/configuration.md Updates snapshots instead of failing. Tests are marked as skipped; run Pytest again to verify. ```bash pytest --accept-diff ``` -------------------------------- ### Module graph of pytest_results package Source: https://github.com/100nm/pytest-results Shows the package structure with core modules, contrib plugin, exceptions, and internal utilities. All subpackage __init__.py files are empty; symbols are imported from defining modules. ```text pytest_results/ (top-level package, `__init__.py`) ├── _core/ │ ├── regression.py Regression (Protocol), BoundRegression, │ │ RegressionImpl, RegressionStack, │ │ type DumpFunction, type CommandRunner │ ├── dump_functions/ │ │ └── json.py json_dump (singledispatch) │ └── storages/ │ ├── abc.py Storage (Protocol) │ └── local.py LocalStorage ├── contrib/ │ └── pytest/ │ └── plugin.py PytestResultsConfig, pytest hooks, │ `regression` fixture (entry point module) ├── exceptions.py PytestResultsError, ResultsMismatchError ├── _testinfo.py get_testinfo (internal) └── _exc_group.py iter_nested_exceptions (internal) ``` -------------------------------- ### LocalStorage.read Source: https://github.com/100nm/pytest-results Reads the binary content of a file. If the file does not exist, returns an empty bytes object. This method is part of the LocalStorage class and is used to read snapshot files. ```APIDOC ## LocalStorage.read ### Description Reads the binary content of a file. If the file does not exist, returns an empty bytes object. This method is part of the LocalStorage class and is used to read snapshot files. ### Method read(self, filepath: Path) -> bytes ### Parameters - **filepath** (Path) - Required - Path to the file to read ### Returns bytes - The binary content of the file, or `b""` if the file does not exist. ### Behavior Attempts to open the file in binary mode and read its content. If `FileNotFoundError` is raised, returns `b""`. ``` -------------------------------- ### Snapshot file structure Source: https://github.com/100nm/pytest-results/blob/prod/docs/regression-fixture.md Snapshots are stored in the __pytest_results__ folder in the root directory. The path follows the test's module, class, and function, with numbering for successive checks. ```text __pytest_results__/ └── tests/ └── test_orders/ └── TestOrder/ ├── test_total.json # first check ├── test_total_1.json # second check └── test_total_2.json # third check ``` -------------------------------- ### Return result from test function Source: https://github.com/100nm/pytest-results/blob/prod/docs/regression-fixture.md The simplest way to check a result is to return it from the test. The fixture compares the returned value with the snapshot. ```python def test_function() -> dict[str, str]: return {"hello": "world"} ``` -------------------------------- ### pyproject.toml: set IDE to vscode Source: https://github.com/100nm/pytest-results Configure the pytest-results plugin via pyproject.toml. The `ide` key accepts `cursor`, `pycharm`, or `vscode` (case-insensitive). ```toml # pyproject.toml [tool.pytest] ide = "vscode" ``` -------------------------------- ### Catch UserWarning for unsupported IDE Source: https://github.com/100nm/pytest-results Use warnings.catch_warnings to capture the UserWarning emitted when diff_command resolves an unsupported ide value. The warning message is 'pytest-results doesn't yet support the {ide} IDE.' and diff_command returns None. ```python import warnings with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") command = config.diff_command # caught[0].message is the UserWarning about the unsupported IDE ``` -------------------------------- ### Use suffix for parametrized tests Source: https://github.com/100nm/pytest-results/blob/prod/docs/regression-fixture.md The snapshot file name is based on the test function only, so parametrized cases would overwrite each other. Use suffix to give each case its own snapshot. A suffix also replaces the _1, _2 numbering of successive checks. ```python import pytest from pytest_results import Regression @pytest.mark.parametrize("quantity", [1, 2, 3]) def test_total(quantity: int, regression: Regression) -> None: result = ... regression.check(result, suffix=f"[{quantity}]") ``` -------------------------------- ### LocalStorage.exists Source: https://github.com/100nm/pytest-results Checks whether a file exists at the given path. This method is part of the LocalStorage class and is used to verify the presence of snapshot files. ```APIDOC ## LocalStorage.exists ### Description Checks whether a file exists at the given path. This method is part of the LocalStorage class and is used to verify the presence of snapshot files. ### Method exists(self, path: Path) -> bool ### Parameters - **path** (Path) - Required - Path to check ### Returns bool - True if the file exists, False otherwise. ### Behavior Returns `path.exists()`. ``` -------------------------------- ### pytest.ini: set IDE and diff command Source: https://github.com/100nm/pytest-results Configure the plugin via pytest.ini. The `diff` command uses `{current}` and `{previous}` placeholders for the current result and snapshot file paths. ```ini # pytest.ini [pytest] ide = vscode diff = meld {current} {previous} ``` -------------------------------- ### accept_diff() Source: https://github.com/100nm/pytest-results Promotes the current result to the new snapshot. If the previous snapshot file does not exist, it is created empty, then the current file is copied over it. Returns None. ```APIDOC ## accept_diff() ### Description Promotes the current result to the new snapshot: if the `previous` snapshot file does not exist, it is created empty (`__ensure_file_exists` → `storage.write`), then `storage.copy(self.current, self.previous)` overwrites it. ### Method accept_diff ### Signature `def accept_diff(self) -> None` ### Returns `None` ### Notes Corresponds to the plugin's `--accept-diff` mode. ``` -------------------------------- ### Import json_dump Source: https://github.com/100nm/pytest-results Import the default DumpFunction implementation from the json module. ```python from pytest_results._core.dump_functions.json import json_dump ``` -------------------------------- ### Top-level exports __all__ in pytest_results/__init__.py Source: https://github.com/100nm/pytest-results Defines the public and internal symbols re-exported from the package. The underscore-prefixed names are internal but exported for typing/testing and for use by exceptions.py and the plugin. ```python __all__ = ( "BoundRegression", "Regression", "_CommandRunner", "_LocalStorage", "_RegressionImpl", "_RegressionStack", "_Storage", ) ``` -------------------------------- ### __str__ Source: https://github.com/100nm/pytest-results Renders a human-readable string representation of the mismatch, showing the current and previous file paths. Pytest displays this string for failed checks. ```APIDOC ## __str__ ### Description Render: `"Results mismatch\n・Current: `{current}`\n・Previous: `{previous}`"` (line 67–69). Pytest displays this string for failed checks; the message references the temporary `current` file and the `previous` snapshot path rather than the raw bytes. ### Method __str__ ### Returns A string representation of the mismatch. ``` -------------------------------- ### Return value from test function Source: https://github.com/100nm/pytest-results/blob/prod/README.md Return the value to check from your test. The first run fails because no snapshot exists yet. ```python def test_function(): return {"hello": "world"} ``` -------------------------------- ### Explicit overrides on top of bindings Source: https://github.com/100nm/pytest-results Shows how explicit file_format arguments override the bound default, producing .json and .log files respectively. ```python from pytest_results import BoundRegression, Regression def test_with_override(regression: Regression) -> None: bound = BoundRegression(regression, file_format="json") bound.check({"a": 1}) # .json bound.check({"a": 1}, file_format="log") # .log this time ``` -------------------------------- ### LocalStorage class definition Source: https://github.com/100nm/pytest-results Default filesystem storage used by the regression fixture. It is a frozen dataclass with a root directory for snapshots and a temporary directory for scratch files. Methods copy, exists, read, and write operate on files, while get_absolute_path and get_temporary_path resolve relative paths under the respective directories, asserting the path is not absolute. ```python @dataclass(repr=False, eq=False, frozen=True, slots=True) class LocalStorage(Storage): dir: Path temporary_dir: Path def copy(self, filepath: Path, destination: Path) -> None: shutil.copyfile(filepath, destination) def exists(self, path: Path) -> bool: return path.exists() def get_absolute_path(self, relative_path: Path) -> Path: return self.__get_absolute_path(relative_path, self.dir) def get_temporary_path(self, relative_path: Path) -> Path: return self.__get_absolute_path(relative_path, self.temporary_dir) def read(self, filepath: Path) -> bytes: with suppress(FileNotFoundError), open(filepath, "rb") as reader: return reader.read() return b"" def write(self, filepath: Path, result: bytes = b"") -> None: os.makedirs(filepath.parent, exist_ok=True) with open(filepath, "wb") as writer: writer.write(result) @staticmethod def __get_absolute_path(filepath: Path, directory: Path) -> Path: assert not filepath.is_absolute() return directory / filepath ``` -------------------------------- ### Supplying a custom dumper to check Source: https://github.com/100nm/pytest-results Shows how to replace the default json_dump with a custom DumpFunction when calling Regression.check, here using yaml.safe_dump and file_format='yml'. ```python import yaml from pytest_results import Regression def test_yaml(regression: Regression) -> None: result = {"a": 1} regression.check( result, dump_func=lambda value: yaml.safe_dump(value).encode(), file_format="yml", ) ``` -------------------------------- ### Top-level re-exports of Storage and CommandRunner Source: https://github.com/100nm/pytest-results Underscore-prefixed aliases for Storage and CommandRunner re-exported at the package top level. Used under TYPE_CHECKING by pytest_results/exceptions.py to annotate ResultsMismatchError fields. Import with: from pytest_results import _Storage, _CommandRunner. ```python from ._core.regression import CommandRunner as _CommandRunner from ._core.storages.abc import Storage as _Storage ``` -------------------------------- ### Module constants _DEFAULT_DUMP_FUNCTION and _DEFAULT_FILE_FORMAT Source: https://github.com/100nm/pytest-results Defaults used by RegressionImpl.check when dump_func or file_format are None. ```python _DEFAULT_DUMP_FUNCTION: Final[DumpFunction[Any]] = json_dump # regression.py:14 _DEFAULT_FILE_FORMAT: Final[str] = "json" # regression.py:15 ``` -------------------------------- ### Storage Protocol Definition Source: https://github.com/100nm/pytest-results Runtime-checkable protocol defining the storage interface for snapshot files. All methods are abstract and required. Import via `from pytest_results._core.storages.abc import Storage`. Satisfied by `LocalStorage` and used by `RegressionImpl` and `ResultsMismatchError`. ```python @runtime_checkable class Storage(Protocol): __slots__ = () @abstractmethod def copy(self, filepath: Path, destination: Path) -> None: raise NotImplementedError @abstractmethod def exists(self, path: Path) -> bool: raise NotImplementedError @abstractmethod def get_absolute_path(self, relative_path: Path) -> Path: raise NotImplementedError @abstractmethod def get_temporary_path(self, relative_path: Path) -> Path: raise NotImplementedError @abstractmethod def read(self, filepath: Path) -> bytes: raise NotImplementedError @abstractmethod def write(self, filepath: Path, result: bytes = ...) -> None: raise NotImplementedError ``` -------------------------------- ### Diffing programmatically with a custom runner using show_diff Source: https://github.com/100nm/pytest-results Constructs a ResultsMismatchError with a custom command_runner (subprocess.run with shell=True) and calls show_diff() with a template containing {current} and {previous} placeholders. The command_runner is invoked with the formatted string; exceptions from it propagate. ```python from pathlib import Path from pytest_results.exceptions import ResultsMismatchError from pytest_results._core.storages.local import LocalStorage from functools import partial import subprocess storage = LocalStorage(Path("__pytest_results__"), Path("/tmp/__pytest_results__")) mismatch = ResultsMismatchError( current=Path("/tmp/__pytest_results__/test_function.json"), previous=Path("__pytest_results__/test_function.json"), storage=storage, command_runner=partial(subprocess.run, shell=True), ) try: mismatch.show_diff("meld {current} {previous}") except Exception as exc: print(f"Diff command failed: {exc}") ``` -------------------------------- ### Catching and accepting a mismatch with ResultsMismatchError Source: https://github.com/100nm/pytest-results Shows how to catch a ResultsMismatchError from a regression check and promote the new result to the snapshot using accept_diff(). The mismatch object exposes current and previous paths for reporting. ```python from pytest_results import Regression from pytest_results.exceptions import ResultsMismatchError def test_manual_accept(regression: Regression) -> None: try: regression.check({"version": 2}) except ResultsMismatchError as mismatch: print(f"Changed: {mismatch.current} vs {mismatch.previous}") mismatch.accept_diff() # promote the new result to the snapshot ``` -------------------------------- ### PytestResultsConfig class definition Source: https://github.com/100nm/pytest-results Defines the configuration wrapper that reads resolved options from a pytest.Config. It exposes accept_diff and diff_command properties, with diff_command resolving --diff/ini first, then --ide/ini via a known IDE mapping, warning on unsupported IDE names. ```python class PytestResultsConfig: __slots__ = ("__config",) __diff_commands: ClassVar[Mapping[str, str]] = { "cursor": "cursor -d -r -w {current} {previous}", "pycharm": "pycharm diff {current} {previous}", "vscode": "code -d -r -w {current} {previous}", } def __init__(self, pytest_config: pytest.Config) -> None: self.__config = pytest_config @property def accept_diff(self) -> bool: return self.__config.getoption("accept_diff") @property def diff_command(self) -> str | None: if diff := self.__get_option_or_ini("diff"): return diff if ide := self.__get_option_or_ini("ide"): lowercase_ide = ide.lower() try: return self.__diff_commands[lowercase_ide] except KeyError: warnings.warn(f"pytest-results doesn't yet support the `{ide}` IDE.") return None def __get_option_or_ini[T](self, key: str) -> T | None: config = self.__config return config.getoption(key) or config.getini(key) ``` -------------------------------- ### json_dump singledispatch implementation Source: https://github.com/100nm/pytest-results The full implementation of json_dump, a singledispatch function that serializes values to bytes. It returns bytes as-is, registers msgspec.Struct and pydantic.BaseModel handlers if those libraries are importable (ImportError suppressed), and falls back to orjson.dumps with default=str and OPT_INDENT_2. ```python @singledispatch def json_dump(value: Any) -> bytes: return orjson.dumps(value, default=str, option=orjson.OPT_INDENT_2) @json_dump.register def _(value: bytes) -> bytes: return value with suppress(ImportError): import msgspec @json_dump.register def _(value: msgspec.Struct) -> bytes: b = msgspec.json.encode(value) return msgspec.json.format(b, indent=2) with suppress(ImportError): import pydantic @json_dump.register def _(value: pydantic.BaseModel) -> bytes: return value.model_dump_json(indent=2).encode() ``` -------------------------------- ### LocalStorage.get_temporary_path Source: https://github.com/100nm/pytest-results Returns the absolute path for a given relative path within the temporary directory. This method is part of the LocalStorage class and is used to resolve temporary snapshot paths. ```APIDOC ## LocalStorage.get_temporary_path ### Description Returns the absolute path for a given relative path within the temporary directory. This method is part of the LocalStorage class and is used to resolve temporary snapshot paths. ### Method get_temporary_path(self, relative_path: Path) -> Path ### Parameters - **relative_path** (Path) - Required - Relative path to resolve ### Returns Path - The absolute path. ### Behavior Returns `temporary_dir / relative_path`. Raises `AssertionError` if the given path is absolute. ### Errors - **AssertionError** - If `relative_path` is absolute. ``` -------------------------------- ### LocalStorage.get_absolute_path Source: https://github.com/100nm/pytest-results Returns the absolute path for a given relative path within the storage root directory. This method is part of the LocalStorage class and is used to resolve snapshot paths. ```APIDOC ## LocalStorage.get_absolute_path ### Description Returns the absolute path for a given relative path within the storage root directory. This method is part of the LocalStorage class and is used to resolve snapshot paths. ### Method get_absolute_path(self, relative_path: Path) -> Path ### Parameters - **relative_path** (Path) - Required - Relative path to resolve ### Returns Path - The absolute path. ### Behavior Returns `dir / relative_path`. Raises `AssertionError` if the given path is absolute. ### Errors - **AssertionError** - If `relative_path` is absolute. ``` -------------------------------- ### pytest_pyfunc_call wrapper hook (trylast) Source: https://github.com/100nm/pytest-results Wrapper hook that lets the wrapped implementation run and intercepts ResultsMismatchError or ExceptionGroup containing it, calling __on_mismatches and re-raising. Other exceptions pass through. ```python @pytest.hookimpl(trylast=True, wrapper=True) def pytest_pyfunc_call( pyfuncitem: pytest.Function, ) -> Generator[None, object | None, object | None]: ``` -------------------------------- ### Fixture reusing custom YAML format with BoundRegression Source: https://github.com/100nm/pytest-results conftest.py fixture that binds a YAML dumper and 'yml' file format to the regression fixture, enabling tests to write/compare .yml files. ```python from typing import Any import pytest import yaml from pytest_results import BoundRegression, Regression def _yaml_dump(value: Any) -> bytes: return yaml.safe_dump(value).encode() @pytest.fixture def regression_yaml(regression: Regression) -> Regression: return BoundRegression(regression, dump_func=_yaml_dump, file_format="yml") ``` -------------------------------- ### regression fixture (function-scoped) Source: https://github.com/100nm/pytest-results Function-scoped fixture that sets up a regression stack with local storage, shell command runner, and test info. Results dir is {rootpath}/__pytest_results__, temporary dir is {tmp_path}/__pytest_results__. ```python @pytest.fixture(scope="function") def regression(request: pytest.FixtureRequest, tmp_path: Path) -> _RegressionStack: dirname = "__pytest_results__" command_runner = partial(subprocess.run, shell=True) storage = _LocalStorage(request.config.rootpath / dirname, tmp_path / dirname) testinfo = get_testinfo(request) delegate = _RegressionImpl(testinfo, storage, command_runner) return _RegressionStack(delegate) ``` -------------------------------- ### Bytes passthrough and custom objects Source: https://github.com/100nm/pytest-results Shows that bytes values are returned unchanged (identity) and unknown objects fall back to str() serialization, e.g., Path becomes its string representation. ```python from pathlib import Path from pytest_results._core.dump_functions.json import json_dump # bytes pass through unchanged (identity): raw = b"\x00\x01\x02" assert json_dump(raw) is raw # unknown objects fall back to str(): snapshot = json_dump({"path": Path("hello/world")}) print(snapshot) # b'{\n "path": "hello/world"\n}' ``` -------------------------------- ### pytest_addoption hook Source: https://github.com/100nm/pytest-results Registers the pytest-results options group and options like --accept-diff, --diff, --ide. The hook signature is declared but the body is not shown. ```python @pytest.hookimpl def pytest_addoption(parser: pytest.Parser) -> None: ``` -------------------------------- ### Import Regression API types Source: https://github.com/100nm/pytest-results Imports the public Regression and BoundRegression classes, internal implementations, and the DumpFunction and CommandRunner type aliases. ```python from pytest_results import Regression, BoundRegression from pytest_results import _RegressionImpl, _RegressionStack # internal from pytest_results._core.regression import DumpFunction, CommandRunner ``` -------------------------------- ### RegressionImpl dataclass definition with check method Source: https://github.com/100nm/pytest-results The concrete checking engine: dumps the result, reads the snapshot, and raises on difference. This is the class the `regression` fixture instantiates as its delegate. The `check` method is generic over type `T`, uses `__tracebackhide__` to hide internals, and raises `ResultsMismatchError` on any difference, including the first run when no snapshot exists. ```python @dataclass(repr=False, eq=False, frozen=True, slots=True) class RegressionImpl(Regression): testinfo: Sequence[str] storage: Storage command_runner: CommandRunner def check[T]( self, current_result: T, /, suffix: str | None = None, dump_func: DumpFunction[T] | None = None, file_format: str | None = None, ) -> None: __tracebackhide__ = True dump_func = dump_func or _DEFAULT_DUMP_FUNCTION file_format = file_format or _DEFAULT_FILE_FORMAT suffix = suffix or "" current_bytes = dump_func(current_result) relative_filepath = self.__get_relative_result_filepath(file_format, suffix) filepath = self.storage.get_absolute_path(relative_filepath) previous_bytes = self.storage.read(filepath) try: assert current_bytes == previous_bytes except AssertionError as exc: temporary_filepath = self.storage.get_temporary_path(relative_filepath) self.storage.write(temporary_filepath, current_bytes) raise ResultsMismatchError( current=temporary_filepath, previous=filepath, storage=self.storage, command_runner=self.command_runner, ) from exc ``` -------------------------------- ### Regression protocol definition Source: https://github.com/100nm/pytest-results Runtime-checkable protocol defining the check method for comparing results against snapshots. Satisfied by BoundRegression, RegressionImpl, and RegressionStack; used as the annotation for the regression fixture parameter. ```python @runtime_checkable class Regression(Protocol): __slots__ = () @abstractmethod def check[T]( self, current_result: T, /, suffix: str | None = ..., dump_func: DumpFunction[T] | None = ..., file_format: str | None = ..., ) -> None: raise NotImplementedError ``` -------------------------------- ### Import public exceptions Source: https://github.com/100nm/pytest-results Import the two public exceptions from the package. ```python from pytest_results.exceptions import PytestResultsError, ResultsMismatchError ``` -------------------------------- ### BoundRegression.check Source: https://github.com/100nm/pytest-results Checks the current result against the stored baseline, using bound defaults for dump_func and file_format unless overridden. Returns the delegate's result (always None in practice) and raises ResultsMismatchError on mismatch. ```APIDOC ## BoundRegression.check ### Description Checks the current result against the stored baseline, using bound defaults for dump_func and file_format unless overridden. Returns the delegate's result (always None in practice) and raises ResultsMismatchError on mismatch. ### Method check ### Signature ```python def check[T]( self, current_result: T, /, suffix: str | None = None, dump_func: DumpFunction[T] | None = None, file_format: str | None = None, ) -> None: ``` ### Parameters #### Positional-Only Parameters - **current_result** (T) - Required - The current result to compare against the stored baseline. #### Keyword Parameters - **suffix** (str | None) - Optional - Suffix to append to the baseline file name. - **dump_func** (DumpFunction[T] | None) - Optional - Custom dump function; if None, uses the bound default. - **file_format** (str | None) - Optional - Custom file format; if None, uses the bound default. ### Response #### Success Response - Returns None. #### Error Response - **ResultsMismatchError** - Raised when the current result does not match the stored baseline. ### Usage Example ```python from pytest_results import BoundRegression, Regression def test_with_override(regression: Regression) -> None: bound = BoundRegression(regression, file_format="json") bound.check({"a": 1}) # .json bound.check({"a": 1}, file_format="log") # .log this time ``` ``` -------------------------------- ### check method signature Source: https://github.com/100nm/pytest-results Exact signature of the check method. current_result is positional-only; all other parameters are keyword-optional. Returns None and raises ResultsMismatchError on mismatch. ```python def check[T]( self, current_result: T, /, suffix: str | None = ..., dump_func: DumpFunction[T] | None = ..., file_format: str | None = ..., ) -> None ``` -------------------------------- ### Call regression.check multiple times Source: https://github.com/100nm/pytest-results/blob/prod/docs/regression-fixture.md regression.check can be called several times in the same test. Every check runs, and all mismatches are reported together at the end of the test. ```python from pytest_results import Regression def test_function(regression: Regression) -> None: for i in range(3): regression.check({"index": i}) ``` -------------------------------- ### json_dump(value) Source: https://github.com/100nm/pytest-results The default DumpFunction implementation that converts a result value into snapshot bytes. It uses singledispatch to handle bytes, msgspec.Struct, pydantic.BaseModel, and falls back to orjson.dumps with default=str and OPT_INDENT_2. ```APIDOC ## json_dump(value) ### Description Converts a result value into snapshot bytes. The default DumpFunction implementation. ### Function Signature ```python @singledispatch def json_dump(value: Any) -> bytes: return orjson.dumps(value, default=str, option=orjson.OPT_INDENT_2) ``` ### Parameters - **value** (Any) - Required - The result value to serialize ### Returns - **bytes** - The snapshot content ### Dispatch Table | Runtime type of `value` | Serialization | Condition | |--------------------------|---------------|-----------| | `bytes` | Returned as-is (same object: `return value`) | always | | `msgspec.Struct` | `msgspec.json.format(msgspec.json.encode(value), indent=2)` | only if `msgspec` is importable at first import of the module (ImportError suppressed) | | `pydantic.BaseModel` | `value.model_dump_json(indent=2).encode()` | only if `pydantic` is importable at first import of the module (ImportError suppressed) | | anything else | `orjson.dumps(value, default=str, option=orjson.OPT_INDENT_2)` | fallback | ### Usage Example — basic ```python from datetime import datetime from pytest_results._core.dump_functions.json import json_dump payload = {"title": "Hello, World!", "created": datetime(2024, 1, 1, 12, 0, 0)} snapshot_bytes = json_dump(payload) print(snapshot_bytes.decode()) # { # "title": "Hello, World!", # "created": "2024-01-01T12:00:00" # } ``` ### Usage Example — bytes passthrough and custom objects ```python from pathlib import Path from pytest_results._core.dump_functions.json import json_dump # bytes pass through unchanged (identity): raw = b"\x00\x01\x02" assert json_dump(raw) is raw # unknown objects fall back to str(): snapshot = json_dump({"path": Path("hello/world")}) print(snapshot) # b'{\n "path": "hello/world"\n}' ``` ### Usage Example — supplying a custom dumper to `check` `json_dump` is the implicit default of `Regression.check`; pass any `DumpFunction` to replace it: ```python import yaml from pytest_results import Regression def test_yaml(regression: Regression) -> None: result = {"a": 1} regression.check( result, dump_func=lambda value: yaml.safe_dump(value).encode(), file_format="yml", ) ``` ``` -------------------------------- ### BoundRegression class definition Source: https://github.com/100nm/pytest-results Dataclass wrapper that fixes default dump_func and file_format for a delegate Regression. check() overrides bound defaults when explicit arguments are passed. ```python @dataclass(repr=False, eq=False, frozen=True, slots=True) class BoundRegression(Regression): regression: Regression dump_func: DumpFunction[Any] file_format: str def check[T]( self, current_result: T, /, suffix: str | None = None, dump_func: DumpFunction[T] | None = None, file_format: str | None = None, ) -> None: __tracebackhide__ = True return self.regression.check( current_result, suffix, dump_func or self.dump_func, file_format or self.file_format, ) ``` -------------------------------- ### CommandRunner type alias Source: https://github.com/100nm/pytest-results Type alias for a callable that executes a shell command string. The plugin wires partial(subprocess.run, shell=True) as the default implementation. ```python type CommandRunner = Callable[[str], Any] ``` -------------------------------- ### Regression.check Source: https://github.com/100nm/pytest-results Checks a current result against a stored snapshot. Raises ResultsMismatchError on mismatch or when no snapshot exists. ```APIDOC ## Regression.check ### Description Checks a current result against a stored snapshot. Raises ResultsMismatchError on mismatch or when no snapshot exists. ### Method check ### Signature ```python def check[T]( self, current_result: T, /, suffix: str | None = ..., dump_func: DumpFunction[T] | None = ..., file_format: str | None = ..., ) -> None ``` ### Parameters - **current_result** (T) - Required (positional-only) - The value to compare against the stored snapshot - **suffix** (str | None) - Optional - String appended to the snapshot file name (before the extension) - **dump_func** (DumpFunction[T] | None) - Optional - Converts current_result to the snapshot bytes; defaults to json_dump in RegressionImpl - **file_format** (str | None) - Optional - File extension of the snapshot; defaults to "json" in RegressionImpl ### Returns - None. A mismatch is signalled by raising ResultsMismatchError, never by the return value. ### Raises - ResultsMismatchError when the dumped current result differs from the stored snapshot (or when no snapshot exists yet) ``` -------------------------------- ### RegressionStack.check Source: https://github.com/100nm/pytest-results Delegates a check to the underlying regression implementation, collecting mismatches instead of raising immediately. Returns None always; mismatches are deferred to close(). ```APIDOC ## [METHOD] RegressionStack.check ### Description Delegates a check to the underlying regression implementation, collecting mismatches instead of raising immediately. Returns None always; mismatches are deferred to close(). ### Method check ### Endpoint RegressionStack.check(current_result, /, suffix=None, dump_func=None, file_format=None) ### Parameters #### Path Parameters - **current_result** (T) - Required - Value to check #### Query Parameters - **suffix** (str | None) - Optional - Explicit suffix; when omitted, repeated checks automatically get `_1`, `_2`, … (only from the second check onward) - **dump_func** (DumpFunction[T] | None) - Optional - Forwarded to the delegate - **file_format** (str | None) - Optional - Forwarded to the delegate ### Response #### Success Response (200) - **None** - Always returns None; mismatches are deferred. ### Request Example ```python from pytest_results import Regression def test_orders(regression: Regression) -> None: for i in range(3): regression.check({"index": i}) # 3 snapshots: .json, _1.json, _2.json ``` ``` -------------------------------- ### PytestResultsError class definition Source: https://github.com/100nm/pytest-results Base class of all pytest-results errors. Derives from Exception and adds no behavior. ```python class PytestResultsError(Exception): ... ```