Debian Codegraph @

src/syrupy/utils.py

raw
1 import json
2 import os
3 from collections.abc import Iterator, Sequence
4 from contextlib import contextmanager
5 from difflib import ndiff
6 from gettext import gettext
7 from importlib import import_module
8 from pathlib import Path
9 from typing import (
10 Any,
11 )
12
13 from .constants import (
14 DIFF_LINE_COUNT_LIMIT,
15 DIFF_LINE_WIDTH_LIMIT,
16 SYMBOL_ELLIPSIS,
17 )
18 from .exceptions import FailedToLoadModuleMember
19
20
21 def is_xdist_worker() -> bool:
22 worker_name = os.getenv("PYTEST_XDIST_WORKER")
23 return bool(worker_name and worker_name != "master")
24
25
26 def walk_snapshot_dir(
27 root: str | Path, *, ignore_extensions: list[str] | None = None
28 ) -> Iterator[str]:
29 ignore_exts: set[str] = set(ignore_extensions or [])
30
31 for filepath in Path(root).rglob("*"):
32 if not filepath.name.startswith(".") and filepath.is_file():
33 if filepath.suffixes and filepath.suffixes[-1][1:] in ignore_exts:
34 continue
35 yield str(filepath)
36
37
38 def import_module_member(path: str) -> Any:
39 sep = "."
40 [*module_parts, module_member_name] = path.split(sep)
41 module_name = sep.join(module_parts)
42
43 if not module_name:
44 raise FailedToLoadModuleMember(
45 gettext("Cannot load member '{}' without module path").format(
46 module_member_name,
47 )
48 )
49 try:
50 module = import_module(module_name)
51 except ModuleNotFoundError as e:
52 raise FailedToLoadModuleMember(
53 gettext("Module '{}' does not exist.").format(module_name)
54 ) from e
55
56 try:
57 return getattr(module, module_member_name)
58 except AttributeError as e:
59 raise FailedToLoadModuleMember(
60 gettext("Member '{}' not found in module '{}'.").format(
61 module_member_name,
62 module_name,
63 )
64 ) from e
65
66
67 def get_env_value(env_var_name: str) -> object:
68 try:
69 return json.loads(os.environ[env_var_name])
70 except (KeyError, TypeError, json.decoder.JSONDecodeError):
71 return os.environ.get(env_var_name)
72
73
74 def set_attrs(obj: Any, attrs: dict[str, Any]) -> Any:
75 for k in attrs:
76 setattr(obj, k, attrs[k])
77
78
79 @contextmanager
80 def obj_attrs(obj: Any, attrs: dict[str, Any]) -> Iterator[None]:
81 prev_attrs = {k: getattr(obj, k, None) for k in attrs}
82 try:
83 yield set_attrs(obj, attrs)
84 finally:
85 set_attrs(obj, prev_attrs)
86
87
88 def qdiff(
89 lines_a: "Sequence[str]",
90 lines_b: "Sequence[str]",
91 *,
92 line_diff_limit: int = DIFF_LINE_COUNT_LIMIT,
93 line_size_limit: int = DIFF_LINE_WIDTH_LIMIT,
94 ) -> "Iterator[str]":
95 """
96 Wrapper around difflib ndiff to bail early
97 https://github.com/python/cpython/issues/65452
98 """
99 first_diff_line_idx = 0
100 first_diff_char_idx = 0
101
102 for i in range(max(len(lines_a), len(lines_b))):
103 line_a = "".join(lines_a[i : i + 1]) # noqa E203
104 line_b = "".join(lines_b[i : i + 1]) # noqa E203
105 if line_a != line_b:
106 first_diff_line_idx = i
107 for j in range(max(len(line_a), len(line_b))):
108 char_a = line_a[j : j + 1] # noqa E203
109 char_b = line_b[j : j + 1] # noqa E203
110 if char_a != char_b:
111 first_diff_char_idx = j
112 break
113 break
114
115 def adjust_lines(lines: "Sequence[str]") -> "Sequence[str]":
116 line_idx_from = max(first_diff_line_idx - line_diff_limit, 0)
117 line_idx_to = first_diff_line_idx + line_diff_limit
118
119 symbol_hidden_line = SYMBOL_ELLIPSIS + SYMBOL_ELLIPSIS
120 return (
121 # include an indicator in the diff if this was not the first line
122 ([symbol_hidden_line] if line_idx_from > 0 else [])
123 # show included lines with the ends truncated off
124 + [
125 adj_line
126 for n, line in enumerate(lines[line_idx_from:line_idx_to])
127 # adjust the first line shown to be from the first different spotted
128 for line_start, line_end in [
129 (
130 (
131 max(first_diff_char_idx - line_size_limit, 0)
132 if n == line_idx_from
133 else 0
134 ),
135 (
136 first_diff_char_idx + line_size_limit
137 if n == line_idx_from
138 else line_size_limit
139 ),
140 ),
141 ]
142 for adj_line in [
143 (SYMBOL_ELLIPSIS if line_start > 0 else "")
144 + line[line_start:line_end]
145 + (SYMBOL_ELLIPSIS if line_end < len(line) else "")
146 ]
147 ]
148 # include an indicator in the diff if this was not the last line
149 + ([symbol_hidden_line] if line_idx_to < len(lines) else [])
150 )
151
152 return ndiff(adjust_lines(lines_a), adjust_lines(lines_b))