Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add a prescision parameter to data_regression #177

Merged
merged 15 commits into from
Dec 17, 2024
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions src/pytest_regressions/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@
from pathlib import Path
from typing import Callable
from typing import List
from typing import MutableMapping
from typing import MutableSequence
from typing import Optional
from typing import TypeVar
from typing import Union

import pytest

Expand Down Expand Up @@ -188,3 +192,27 @@ def make_location_message(banner: str, filename: Path, aux_files: List[str]) ->
else:
dump_aux_fn(Path(obtained_filename))
raise


T = TypeVar("T", bound=Union[MutableSequence, MutableMapping])


def round_digits(data: T, precision: int) -> T:
"""
Recursively Round the values of any float value in a collection to the given precision.

:param data: The collection to round.
:param precision: The number of decimal places to round to.
:return: The collection with all float values rounded to the given precision.

"""
# change the generator depending on the collection type
generator = enumerate(data) if isinstance(data, MutableSequence) else data.items()
for k, v in generator:
if isinstance(v, (MutableSequence, MutableMapping)):
data[k] = round_digits(v, precision)
elif isinstance(v, float):
data[k] = round(v, precision)
else:
data[k] = v
return data
nicoddemus marked this conversation as resolved.
Show resolved Hide resolved
8 changes: 7 additions & 1 deletion src/pytest_regressions/data_regression.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

from .common import check_text_files
from .common import perform_regression_check
from .common import round_digits


class DataRegressionFixture:
Expand All @@ -32,6 +33,7 @@ def check(
data_dict: Dict[str, Any],
basename: Optional[str] = None,
fullpath: Optional["os.PathLike[str]"] = None,
precision: Optional[int] = None,
nicoddemus marked this conversation as resolved.
Show resolved Hide resolved
) -> None:
"""
Checks the given dict against a previously recorded version, or generate a new file.
Expand All @@ -46,13 +48,17 @@ def check(
will ignore ``datadir`` fixture when reading *expected* files but will still use it to
write *obtained* files. Useful if a reference file is located in the session data dir for example.

:param precision: if given, round all floats in the dict to the given number of digits.
nicoddemus marked this conversation as resolved.
Show resolved Hide resolved

``basename`` and ``fullpath`` are exclusive.
"""
__tracebackhide__ = True

if precision is not None:
round_digits(data_dict, precision)
nicoddemus marked this conversation as resolved.
Show resolved Hide resolved

def dump(filename: Path) -> None:
"""Dump dict contents to the given filename"""
import yaml

dumped_str = yaml.dump_all(
[data_dict],
Expand Down
19 changes: 19 additions & 0 deletions tests/test_data_regression.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import sys
from textwrap import dedent

import pytest
import yaml

from pytest_regressions.testing import check_regression_fixture_workflow
Expand Down Expand Up @@ -38,6 +39,24 @@ def dump_scalar(dumper, scalar):
data_regression.check(contents)


def test_round_digits(data_regression):
"""Example including float numbers and check rounding capabilities."""
contents = {
"content": {"value1": "toto", "value": 1.123456789},
"values": [1.12345, 2.34567],
"value": 1.23456789,
}
data_regression.check(contents, precision=2)

with pytest.raises(AssertionError):
contents = {
"content": {"value1": "toto", "value": 1.2345678},
"values": [1.13456, 2.45678],
"value": 1.23456789,
}
data_regression.check(contents, precision=2)
nicoddemus marked this conversation as resolved.
Show resolved Hide resolved


def test_usage_workflow(pytester, monkeypatch):
monkeypatch.setattr(
sys, "testing_get_data", lambda: {"contents": "Foo", "value": 10}, raising=False
Expand Down
7 changes: 7 additions & 0 deletions tests/test_data_regression/test_round_digits.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
content:
value: 1.12
value1: toto
value: 1.23
values:
- 1.12
- 2.35
Loading