-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsession.py
227 lines (180 loc) · 7.01 KB
/
session.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
__all__ = ["SnapshotSession", "SnapshotContext"]
import os
import shutil
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, Iterable, List, Set, Tuple
from _pytest.terminal import TerminalReporter
from pytest import Session
from .format import Fmt
from .review import ReviewTool
from .utils import is_ci, pluralize, remove_path, rename_path
@dataclass
class SnapshotContext:
path: Path
counter: int
available: Set[Path]
matching: Set[Path]
differing: Dict[Path, Tuple[Fmt[Any], Any]]
def __post_init__(self):
self.path.parent.mkdir(parents=True, exist_ok=True)
@property
def created(self) -> Dict[Path, Tuple[Fmt[Any], Any]]:
return {
path: pair
for path, pair in self.differing.items()
if path not in self.available
}
@property
def updated(self) -> Dict[Path, Tuple[Fmt[Any], Any]]:
return {
path: pair
for path, pair in self.differing.items()
if path in self.available
}
@property
def deleted(self) -> Set[Path]:
return self.available - self.matching - self.differing.keys()
def flush(self, session: "SnapshotSession"):
if session.should_create:
for path, (fmt, value) in self.created.items():
fmt.dump(path, value)
session.created.add(path)
if session.should_record:
directory = self.path.parent.parent.resolve()
record_dir = session.record_dir / directory.relative_to(
session.config.rootpath
)
record_dir.mkdir(parents=True, exist_ok=True)
for path, (fmt, value) in self.updated.items():
path = record_dir / path.name
fmt.dump(path, value)
session.recorded.add(path)
elif session.should_update:
for path, (fmt, value) in self.updated.items():
fmt.dump(path, value)
session.updated.add(path)
if session.should_delete:
for path in self.deleted:
remove_path(path)
session.deleted.add(path)
self.reset()
def reset(self):
self.counter = 0
self.matching = set()
self.differing = {}
@dataclass
class SnapshotSession(Dict[Path, SnapshotContext]):
session: Session
config: Any = field(init=False)
tr: TerminalReporter = field(init=False)
record_dir: Path = field(init=False)
strategy: str = "auto"
recorded: Set[Path] = field(default_factory=set)
rejected: Set[Path] = field(default_factory=set)
created: Set[Path] = field(default_factory=set)
updated: Set[Path] = field(default_factory=set)
deleted: Set[Path] = field(default_factory=set)
notices: List[str] = field(default_factory=list)
def __post_init__(self):
self.config = self.session.config
cache = self.config.cache
if not cache:
raise TypeError("No cache")
record_dir = cache.mkdir("insta")
self.record_dir = Path(os.path.relpath(Path(record_dir), Path(".").resolve()))
tr = self.config.pluginmanager.getplugin("terminalreporter")
if not isinstance(tr, TerminalReporter):
raise TypeError("No TerminalReporter")
self.tr = tr
self.strategy = self.config.option.insta
if self.strategy == "auto":
self.strategy = "update-none" if is_ci() else "update-new"
def __missing__(self, path: Path) -> SnapshotContext:
available = set(path.parent.glob(f"{path.name}__*"))
ctx = SnapshotContext(path, 0, available, set(), {})
self[path] = ctx
return ctx
@property
def should_record(self) -> bool:
return self.strategy in ["record", "review"]
@property
def should_create(self) -> bool:
return self.strategy in ["record", "review", "update", "update-new"]
@property
def should_update(self) -> bool:
return self.strategy in ["record", "review", "update"]
@property
def should_delete(self) -> bool:
return self.strategy in ["record", "review", "update"]
@property
def should_review(self) -> bool:
return self.strategy in ["review-only", "review"]
@property
def should_skip_testloop(self) -> bool:
return self.strategy in ["review-only", "clear"]
@property
def should_clear_recorded(self) -> bool:
return self.strategy in ["update", "clear"]
def on_finish(self, status: int = 0):
if not status:
self.on_success()
if snapshots_to_review := self.count_snapshots_to_review():
self.notices.append(
pluralize("snapshot", snapshots_to_review) + " to review"
)
def on_success(self):
if self.should_review:
capture = self.config.pluginmanager.getplugin("capturemanager")
capture.suspend_global_capture(True)
review_tool = ReviewTool(
self.tr, self.config, self.record_dir, self.session.items
)
for snapshot, destination in review_tool.collect():
if destination:
rename_path(snapshot, destination)
self.updated.add(destination)
else:
remove_path(snapshot)
self.rejected.add(snapshot)
self.recorded.discard(snapshot)
if self.should_clear_recorded and (
snapshots_to_clear := self.count_snapshots_to_review()
):
shutil.rmtree(self.record_dir)
self.notices.append(
pluralize("recorded snapshot", snapshots_to_clear) + " cleared"
)
def write_summary(self):
report = {
"RECORD": self.recorded,
"REJECT": self.rejected,
"CREATE": self.created,
"UPDATE": self.updated,
"DELETE": self.deleted,
}
if not any(report.values()) and not self.notices:
return
self.tr.ensure_newline()
self.tr.section("SNAPSHOTS", blue=True)
for operation, snapshots in report.items():
for snapshot in sorted(snapshots):
self.tr.write_line(f"{operation} {snapshot}")
if self.notices:
if any(report.values()):
self.tr.write_line("")
for notice in self.notices:
self.tr.write("NOTICE ", bold=True, yellow=True)
self.tr.write_line(notice)
def count_snapshots_to_review(self) -> int:
return len(list(self.collect_snapshots_to_review()))
def collect_snapshots_to_review(self) -> Iterable[str]:
for _, dirs, files in os.walk(self.record_dir):
directory_snapshots = {
directory
for directory in dirs
if any(directory.endswith(extension) for extension in Fmt.registry)
}
dirs[:] = set(dirs) - directory_snapshots
yield from directory_snapshots
yield from files