Debian Codegraph @

src/syrupy/location.py

raw
1 from collections.abc import Iterator
2 from dataclasses import (
3 dataclass,
4 field,
5 )
6 from pathlib import Path
7
8 import pytest
9
10 from syrupy.constants import PYTEST_NODE_SEP
11 from syrupy.extensions.base import SnapshotCollectionStorage
12
13
14 @dataclass(frozen=True)
15 class PyTestLocation:
16 item: "pytest.Item"
17 nodename: str | None = field(init=False)
18 testname: str = field(init=False)
19 methodname: str = field(init=False)
20 modulename: str = field(init=False)
21 filepath: str = field(init=False)
22
23 def __post_init__(self) -> None:
24 # NB. we're in a frozen dataclass, but need to transform the values that the caller
25 # supplied... we do so by (ab)using object.__setattr__ to forcibly set the attributes. (See
26 # rejected PEP-0712 for an example of a better way to handle this.)
27 #
28 # This is safe because this all happens during initialization: `self` hasn't been hashed
29 # (or, e.g., stored in a dict), so the mutation won't be noticed.
30 if self.is_doctest:
31 return self.__attrs_post_init_doc__()
32 self.__attrs_post_init_def__()
33
34 def __attrs_post_init_def__(self) -> None:
35 node_path: Path = getattr(self.item, "path") # noqa: B009
36 # See __post_init__ for discussion of object.__setattr__
37 object.__setattr__(self, "filepath", str(node_path.absolute()))
38 obj = getattr(self.item, "obj") # noqa: B009
39 object.__setattr__(self, "modulename", obj.__module__)
40 object.__setattr__(self, "methodname", obj.__name__)
41 object.__setattr__(self, "nodename", getattr(self.item, "name", None))
42 object.__setattr__(self, "testname", self.nodename or self.methodname)
43
44 def __attrs_post_init_doc__(self) -> None:
45 doctest = getattr(self.item, "dtest") # noqa: B009
46 # See __post_init__ for discussion of object.__setattr__
47 object.__setattr__(self, "filepath", doctest.filename)
48 test_relfile, test_node = self.nodeid.split(PYTEST_NODE_SEP)
49 test_relpath = Path(test_relfile)
50 object.__setattr__(
51 self,
52 "modulename",
53 ".".join([*test_relpath.parent.parts, test_relpath.stem]),
54 )
55 object.__setattr__(self, "methodname", None)
56 object.__setattr__(
57 self, "nodename", test_node.replace(f"{self.modulename}.", "")
58 )
59 object.__setattr__(self, "testname", self.nodename or self.methodname)
60
61 @property
62 def is_item_parametrized(self) -> bool:
63 return self.nodeid.endswith("]")
64
65 @property
66 def classname(self) -> str | None:
67 if self.is_doctest:
68 return None
69 return ".".join(self.nodeid.split(PYTEST_NODE_SEP)[1:-1]) or None
70
71 @property
72 def nodeid(self) -> str:
73 """
74 Pytest node names contain file path and module members delimited by `::`
75
76 Examples:
77 - tests/grouping/test_file.py::TestClass::TestSubClass::test_method
78 - tests/grouping/test_file.py::DocTestClass.doc_test_method
79 - tests/grouping/test_file.py::doctestfile.txt
80
81 :raises: `AttributeError` if node has no node id
82 :return: test node id
83 """
84 return str(getattr(self.item, "nodeid")) # noqa: B009
85
86 @property
87 def basename(self) -> str:
88 return Path(self.filepath).stem
89
90 @property
91 def snapshot_name(self) -> str:
92 if self.classname is not None:
93 return f"{self.classname}.{self.testname}"
94 return str(self.testname)
95
96 @property
97 def snapshot_name_parametrized(self) -> str:
98 if self.classname is not None:
99 return f"{self.classname}.{self.nodename}"
100 return str(self.nodename)
101
102 @property
103 def is_doctest(self) -> bool:
104 return self.__is_doctest(self.item)
105
106 def __is_doctest(self, node: "pytest.Item") -> bool:
107 return hasattr(node, "dtest")
108
109 def __valid_id(self, name: str) -> str:
110 """
111 Take characters from the name while the result would be a valid python
112 identified. Example: "test_2[A]" returns "test_2" while "1_a" would return ""
113 """
114 valid_id = ""
115 for char in name:
116 new_valid_id = f"{valid_id}{char}"
117 if not new_valid_id.isidentifier():
118 break
119 valid_id = new_valid_id
120 return valid_id
121
122 def __valid_ids(self, name: str) -> Iterator[str]:
123 """
124 Break a name path into valid name parts stopping at the first non valid name.
125 Example "TestClass.test_method_[1]" would yield ("TestClass", "test_method_")
126 """
127 for n in name.split("."):
128 valid_id = self.__valid_id(n)
129 if valid_id:
130 yield valid_id
131 if valid_id != n:
132 break
133
134 def __parse(self, name: str) -> str:
135 return ".".join(self.__valid_ids(name))
136
137 def matches_snapshot_name(self, snapshot_name: str) -> bool:
138 return self.__parse(self.snapshot_name) == self.__parse(snapshot_name)
139
140 def matches_snapshot_location(self, snapshot_location: str) -> bool:
141 loc = Path(snapshot_location)
142 if not self._matches_snapshot_basename(loc):
143 return False
144 return self._matches_test_site(loc)
145
146 def _matches_snapshot_basename(self, loc: Path) -> bool:
147 # "test_file" should match "test_file.ext" or "test_file/whatever.ext", but not
148 # "test_file_suffix.ext" (see PR #607).
149 if self.basename == loc.stem:
150 return True
151 if self.basename != loc.parent.name:
152 return False
153 if not self.is_item_parametrized:
154 return True
155 # Parametrized single-file snapshots (see PR #965).
156 return (
157 loc.stem == self.snapshot_name_parametrized
158 or loc.stem.startswith(f"{self.snapshot_name_parametrized}.")
159 or loc.stem.startswith(f"{self.snapshot_name_parametrized}[")
160 )
161
162 def _matches_test_site(self, loc: Path) -> bool:
163 """
164 Ensure a snapshot path belongs to this test file's site.
165
166 Basename-only matching is not enough: ``test_views`` in one module must
167 not match ``__snapshots__/test_views`` from another module's directory.
168 """
169 test_dir = Path(self.filepath).parent.resolve()
170 resolved = loc.resolve()
171
172 try:
173 resolved.relative_to(test_dir)
174 return True
175 except ValueError:
176 pass
177
178 snapshot_test_dir = self._snapshot_collection_test_dir(resolved)
179 if snapshot_test_dir is not None:
180 # Snapshot is in a collection directory (e.g. ``__snapshots__/``); only
181 # the test files alongside that directory may claim it.
182 return snapshot_test_dir == test_dir
183
184 # Snapshots stored outside the test file directory (custom dirname locations).
185 return True
186
187 @staticmethod
188 def _snapshot_collection_test_dir(loc: Path) -> Path | None:
189 """
190 Return the test directory that owns a snapshot collection path.
191
192 Walks upward from ``loc`` looking for a snapshot collection directory
193 (``__snapshots__`` by default, or ``--snapshot-dirname``). There is no
194 fixed depth limit: any ancestor may be the collection dir, and snapshots
195 may be nested arbitrarily deep beneath it (e.g. single-file extension
196 layouts). When found, snapshots belong to the collection dir's parent.
197 """
198 for parent in loc.parents:
199 if PyTestLocation._is_snapshot_dir(parent):
200 return parent.parent.resolve()
201 return None
202
203 @staticmethod
204 def _is_snapshot_dir(path: Path) -> bool:
205 return path.name == str(SnapshotCollectionStorage.snapshot_dirname)