Debian Codegraph @

src/syrupy/filters.py

raw
1 from typing import (
2 TYPE_CHECKING,
3 )
4
5 if TYPE_CHECKING:
6 from syrupy.types import (
7 PropertyFilter,
8 PropertyName,
9 PropertyPath,
10 )
11
12
13 def paths(*path_parts: str) -> "PropertyFilter":
14 """
15 Factory to create a filter using list of path strings.
16
17 This filter does not work well when combined with "include" and
18 nested paths, since "include" oeprates per key as an object is traversed
19 for serialization. For nested paths, we must include all parents. To accomplish
20 this, we provide an alternative "paths_include" filter which does this
21 automatically.
22 """
23
24 if not path_parts:
25 raise TypeError("At least 1 path argument is required.")
26
27 parts: set[str] = set(path_parts)
28
29 def path_filter(*, prop: "PropertyName", path: "PropertyPath") -> bool:
30 path_str = ".".join(str(p) for p, _ in (*path, (prop, None)))
31 return path_str in parts
32
33 return path_filter
34
35
36 def paths_include(*path_parts: tuple[str, ...] | list[str]) -> "PropertyFilter":
37 """
38 Factory to create a filter using list of path tuples.
39 """
40
41 if not path_parts:
42 raise TypeError("At least 1 path argument is required.")
43
44 # "include" operates per key as an object is traversed for serialization.
45 # This means, if matching a nested path, we must also include all parents.
46 parts: set[tuple[str, ...]] = set()
47 for path_part in path_parts:
48 if isinstance(path_part, (list, tuple)):
49 for idx in range(len(path_part)):
50 parts.add(tuple(path_part[: idx + 1]))
51 else:
52 raise TypeError("Unexpected argument. Expected list/tuple.")
53
54 def path_filter(*, prop: "PropertyName", path: "PropertyPath") -> bool:
55 path_tuple = tuple(str(p) for p, _ in (*path, (prop, None)))
56 return path_tuple in parts
57
58 return path_filter
59
60
61 def props(*prop_names: str) -> "PropertyFilter":
62 """
63 Factory to create filter using list of props
64 """
65
66 if not prop_names:
67 raise TypeError("At least 1 prop name is required.")
68
69 def prop_filter(*, prop: "PropertyName", path: "PropertyPath") -> bool:
70 return any(str(prop) == p for p in prop_names)
71
72 return prop_filter