Debian Codegraph @

tests/util.py

raw
1 """
2 This module provides utility functions shared by tests.
3 """
4 from __future__ import annotations
5
6 import itertools
7 import os
8 import os.path
9 import pathlib
10 from collections.abc import (
11 Iterable)
12 from random import (
13 Random)
14 from typing import (
15 Any,
16 Optional, # Replaced by `X | None` in 3.10.
17 cast)
18 from unittest import (
19 SkipTest)
20
21 from pathspec import (
22 PathSpec,
23 RegexPattern)
24 from pathspec.backend import (
25 BackendNamesHint)
26 from pathspec._backends.hyperscan.base import (
27 hyperscan_error)
28 from pathspec._backends.hyperscan._base import (
29 HyperscanExprDebug)
30 from pathspec._backends.hyperscan.pathspec import (
31 HyperscanPsBackend)
32 from pathspec._backends.re2.base import (
33 re2_error)
34 from pathspec._backends.re2._base import (
35 Re2RegexDebug)
36 from pathspec._backends.re2.pathspec import (
37 Re2PsBackend)
38 from pathspec.util import (
39 CheckResult,
40 TStrPath,
41 TreeEntry)
42
43
44 def debug_includes(spec: PathSpec, files: set[str], includes: set[str]) -> str:
45 """
46 Format the match files message.
47
48 *spec* (:class:`~pathspec.PathSpec`) is the path-spec.
49
50 *files* (:class:`set` of :class:`str`) contains the source files.
51
52 *includes* (:class:`set` of :class:`str`) contains the matched files.
53
54 Returns the message (:class:`str`).
55 """
56 results = []
57 for result in spec.check_files(files):
58 assert (result.file in includes) == bool(result.include), {
59 'result': result, 'includes': includes,
60 }
61 results.append(result)
62
63 return debug_results(spec, results)
64
65
66 def debug_results(spec: PathSpec, results: Iterable[CheckResult[str]]) -> str:
67 """
68 Format the check results message.
69
70 *spec* (:class:`~pathspec.PathSpec`) is the path-spec.
71
72 *results* (:class:`~collections.abc.Iterable` or :class:`~pathspec.util.CheckResult`)
73 yields each file check result.
74
75 Returns the message (:class:`str`).
76 """
77 patterns = cast(list[RegexPattern], spec.patterns)
78
79 pattern_table = []
80 if isinstance(spec._backend, HyperscanPsBackend) and spec._backend._debug_exprs:
81 for expr_id, expr_dat in enumerate(spec._backend._expr_data, 1):
82 assert isinstance(expr_dat, HyperscanExprDebug), expr_dat
83 pattern = patterns[expr_dat.index]
84 dir_col = 'd' if expr_dat.is_dir_pattern else '.'
85 pattern_table.append((
86 f"{expr_dat.index+1}({expr_id}):{pattern.pattern}",
87 f"{dir_col} {expr_dat.regex!r}",
88 ))
89
90 elif isinstance(spec._backend, Re2PsBackend) and spec._backend._debug_regex:
91 for regex_id, regex_dat in enumerate(spec._backend._regex_data, 1):
92 assert isinstance(regex_dat, Re2RegexDebug), regex_dat
93 pattern = patterns[regex_dat.index]
94 dir_col = 'd' if regex_dat.is_dir_pattern else '.'
95 pattern_table.append((
96 f"{regex_dat.index+1}({regex_id}):{pattern.pattern}",
97 f"{dir_col} {regex_dat.regex!r}",
98 ))
99
100 else:
101 for index, pattern in enumerate(patterns, 1):
102 pattern_table.append((
103 f"{index}:{pattern.pattern}", repr(pattern.regex.pattern),
104 ))
105
106 result_table = []
107 for result in results:
108 if result.index is not None:
109 pattern = patterns[result.index]
110 result_table.append((f"{result.index + 1}:{pattern.pattern}", result.file))
111 else:
112 result_table.append(("-", result.file))
113
114 result_table.sort(key=lambda r: r[1])
115
116 first_max_len = max((
117 len(__row[0]) for __row in itertools.chain(pattern_table, result_table)
118 ), default=0)
119 first_width = min(first_max_len, 20)
120
121 pattern_lines = []
122 for row in pattern_table:
123 pattern_lines.append(f" {row[0]:<{first_width}} {row[1]}")
124
125 result_lines = []
126 for row in result_table:
127 result_lines.append(f" {row[0]:<{first_width}} {row[1]}")
128
129 return "\n".join([
130 "\n",
131 " DEBUG ".center(32, "-"),
132 *pattern_lines,
133 "-"*32,
134 *result_lines,
135 "-"*32,
136 ])
137
138
139 def get_includes(results: Iterable[CheckResult[TStrPath]]) -> set[TStrPath]:
140 """
141 Get the included files from the check results.
142
143 *results* (:class:`~collections.abc.Iterable` or :class:`~pathspec.util.CheckResult`)
144 yields each file check result.
145
146 Returns the included files (:class:`set` of :class:`str`).
147 """
148 return {__res.file for __res in results if __res.include}
149
150
151 def get_paths_from_entries(entries: Iterable[TreeEntry]) -> set[str]:
152 """
153 Get the entry paths.
154
155 *entries* (:class:`Iterable` of :class:`TreeEntry`) yields the entries.
156
157 Returns the paths (:class:`set` of :class:`str`).
158 """
159 return {__ent.path for __ent in entries}
160
161
162 def make_dirs(temp_dir: pathlib.Path, dirs: Iterable[str]) -> None:
163 """
164 Create the specified directories.
165
166 *temp_dir* (:class:`pathlib.Path`) is the temporary directory to use.
167
168 *dirs* (:class:`Iterable` of :class:`str`) is the POSIX directory
169 paths (relative to *temp_dir*) to create.
170 """
171 for dir in dirs:
172 os.mkdir(temp_dir / ospath(dir))
173
174
175 def make_files(temp_dir: pathlib.Path, files: Iterable[str]) -> None:
176 """
177 Create the specified files.
178
179 *temp_dir* (:class:`pathlib.Path`) is the temporary directory to use.
180
181 *files* (:class:`Iterable` of :class:`str`) is the POSIX file paths
182 (relative to *temp_dir*) to create.
183 """
184 for file in files:
185 mkfile(temp_dir / ospath(file))
186
187
188 def make_links(temp_dir: pathlib.Path, links: Iterable[tuple[str, str]]) -> None:
189 """
190 Create the specified links.
191
192 *temp_dir* (:class:`pathlib.Path`) is the temporary directory to use.
193
194 *links* (:class:`Iterable` of :class:`tuple`) contains the POSIX links
195 to create relative to *temp_dir*. Each link (:class:`tuple`) contains
196 the destination link path (:class:`str`) and source node path
197 (:class:`str`).
198 """
199 for link, node in links:
200 src = temp_dir / ospath(node)
201 dest = temp_dir / ospath(link)
202 os.symlink(src, dest)
203
204
205 def mkfile(file: pathlib.Path) -> None:
206 """
207 Creates an empty file.
208
209 *file* (:class:`pathlib.Path`) is the native file path to create.
210 """
211 with open(file, 'wb'):
212 pass
213
214
215 def ospath(path: str) -> str:
216 """
217 Convert the POSIX path to a native OS path.
218
219 *path* (:class:`str`) is the POSIX path.
220
221 Returns the native path (:class:`str`).
222 """
223 return os.path.join(*path.split('/'))
224
225
226 def require_backend(name: Optional[BackendNamesHint]) -> None:
227 """
228 Skip the test if the backend library is not installed.
229
230 *name* (:class:`str` or :data:`None`) is the backend name.
231
232 Raises :class:`SkipTest` if the backend library is not installed.
233 """
234 if name == 'hyperscan' and hyperscan_error is not None:
235 raise SkipTest(str(hyperscan_error))
236 elif name == 're2' and re2_error is not None:
237 raise SkipTest(str(re2_error))
238
239
240 def reverse_inplace(val: list[Any]) -> None:
241 """
242 Reverse the list inplace.
243
244 *val* (:class:`list`) is the list to sort.
245 """
246 val.reverse()
247
248
249 def shuffle_inplace(val: list[Any]) -> None:
250 """
251 Shuffle the list inplace. The order will consistently be in the same random
252 order between test runs.
253
254 *val* (:class:`list`) is the list to sort.
255 """
256 Random(0).shuffle(val)