Debian Codegraph @

src/pytest_regressions/data_regression.py

raw symbols SCIP
1 import os
2 from functools import partial
3 from pathlib import Path
4 from typing import Any
5 from typing import Callable
6 from typing import Dict
7 from typing import Optional
8
9 import pytest
10 import yaml
11
12 from .common import check_text_files
13 from .common import perform_regression_check
14
15
16 class DataRegressionFixture:
17 """
18 Implementation of `data_regression` fixture.
19 """
20
21 def __init__(
22 self, datadir: Path, original_datadir: Path, request: pytest.FixtureRequest
23 ) -> None:
24 self.request = request
25 self.datadir = datadir
26 self.original_datadir = original_datadir
27 self.force_regen = False
28 self.with_test_class_names = False
29
30 def check(
31 self,
32 data_dict: Dict[str, Any],
33 basename: Optional[str] = None,
34 fullpath: Optional["os.PathLike[str]"] = None,
35 ) -> None:
36 """
37 Checks the given dict against a previously recorded version, or generate a new file.
38
39 :param data_dict: any yaml serializable dict.
40
41 :param basename: basename of the file to test/record. If not given the name
42 of the test is used.
43 Use either `basename` or `fullpath`.
44
45 :param fullpath: complete path to use as a reference file. This option
46 will ignore ``datadir`` fixture when reading *expected* files but will still use it to
47 write *obtained* files. Useful if a reference file is located in the session data dir for example.
48
49 ``basename`` and ``fullpath`` are exclusive.
50 """
51 __tracebackhide__ = True
52
53 def dump(filename: Path) -> None:
54 """Dump dict contents to the given filename"""
55 import yaml
56
57 dumped_str = yaml.dump_all(
58 [data_dict],
59 Dumper=RegressionYamlDumper,
60 default_flow_style=False,
61 allow_unicode=True,
62 indent=2,
63 encoding="utf-8",
64 )
65 with filename.open("wb") as f:
66 f.write(dumped_str)
67
68 perform_regression_check(
69 datadir=self.datadir,
70 original_datadir=self.original_datadir,
71 request=self.request,
72 check_fn=partial(check_text_files, encoding="UTF-8"),
73 dump_fn=dump,
74 extension=".yml",
75 basename=basename,
76 fullpath=fullpath,
77 force_regen=self.force_regen,
78 with_test_class_names=self.with_test_class_names,
79 )
80
81 # non-PEP 8 alias used internally at ESSS
82 Check = check
83
84
85 class RegressionYamlDumper(yaml.SafeDumper):
86 """
87 Custom YAML dumper aimed for regression testing. Differences to usual YAML dumper:
88
89 * Doesn't support aliases, as they produce confusing results on regression tests. The most
90 definitive way to get rid of YAML aliases in the dump is to create an specialization that
91 never allows aliases, as there isn't an argument that offers same guarantee
92 (see http://pyyaml.org/ticket/91).
93 """
94
95 def ignore_aliases(self, data: object) -> bool:
96 return True
97
98 @classmethod
99 def add_custom_yaml_representer(
100 cls, data_type: type, representer_fn: Callable[[object, Any], None]
101 ) -> None:
102 """
103 Add custom representer to regression YAML dumper. It is polymorphic, so it works also for
104 subclasses of `data_type`.
105
106 :param data_type: Type of objects.
107 :param representer_fn: Function that receives ``(dumper, data)`` type as
108 argument and must must return a YAML-convertible representation.
109 """
110 # Use multi-representer instead of simple-representer because it supports polymorphism.
111 yaml.add_multi_representer(
112 data_type, multi_representer=representer_fn, Dumper=cls
113 )