-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
256 lines (230 loc) · 8.98 KB
/
Copy pathcli.py
File metadata and controls
256 lines (230 loc) · 8.98 KB
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
"""Command-line entrypoint for flake-bisect."""
from __future__ import annotations
import argparse
import json
import os
import sys
from typing import Any
from flake_bisect import __version__
from flake_bisect.bisect import ddmin
from flake_bisect.runner import collect_tests, run_ordered, target_failed
def _build_parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(
prog="flake-bisect",
description=(
"Find the minimal set of preceding pytest tests that cause a target "
"test to fail. Use when a test passes in isolation but fails as part "
"of the full suite."
),
)
p.add_argument("--version", action="version", version=f"flake-bisect {__version__}")
p.add_argument(
"--target",
required=True,
help="Nodeid of the flaky test, e.g. tests/test_foo.py::test_bar",
)
p.add_argument(
"--testpaths",
nargs="*",
default=None,
help="Paths to collect candidate predecessor tests from (default: pytest default discovery in --workdir).",
)
p.add_argument(
"--workdir",
default=os.getcwd(),
help="Directory to run pytest from (default: current working directory).",
)
p.add_argument(
"--max-runs",
type=int,
default=200,
help="Hard cap on the number of pytest subprocess invocations during bisect (default: 200).",
)
p.add_argument(
"--pytest-arg",
action="append",
default=[],
metavar="ARG",
help="Extra argument forwarded to pytest. Repeat to pass multiple.",
)
p.add_argument(
"--json",
dest="json_path",
default=None,
metavar="PATH",
help="Write a machine-readable JSON report to PATH (use '-' for stdout).",
)
p.add_argument(
"--no-confirm",
action="store_true",
help="Skip the post-bisect confirmation runs (saves two pytest invocations).",
)
p.add_argument(
"-v",
"--verbose",
action="store_true",
help="Print per-iteration progress.",
)
return p
def _emit_json(path: str, payload: dict[str, Any]) -> None:
"""Write the JSON report to a file, or to stdout when path == '-'."""
text = json.dumps(payload, indent=2, sort_keys=True)
if path == "-":
print(text)
else:
with open(path, "w", encoding="utf-8") as fh:
fh.write(text + "\n")
def main(argv: list[str] | None = None) -> int:
args = _build_parser().parse_args(argv)
workdir = os.path.abspath(args.workdir)
target = args.target
extra = list(args.pytest_arg or [])
json_path = args.json_path
# Total pytest subprocess invocations across every phase (collection excluded).
runs = {"total": 0}
def _run(order: list[str]):
runs["total"] += 1
return run_ordered(workdir, order, extra)
def _report(status: str, exit_code: int, **fields: Any) -> int:
if json_path:
payload: dict[str, Any] = {
"tool": "flake-bisect",
"version": __version__,
"status": status,
"exit_code": exit_code,
"target": target,
"workdir": workdir,
"pytest_invocations": runs["total"],
"max_runs": args.max_runs,
}
payload.update(fields)
_emit_json(json_path, payload)
return exit_code
testpaths = args.testpaths if args.testpaths else []
print(f"flake-bisect {__version__}", file=sys.stderr)
print(f"workdir : {workdir}", file=sys.stderr)
print(f"target : {target}", file=sys.stderr)
print("Collecting tests...", file=sys.stderr)
all_ids = collect_tests(workdir, testpaths)
if not all_ids:
print("ERROR: no tests collected", file=sys.stderr)
return _report("no_tests_collected", 2)
if target not in all_ids:
print(
f"ERROR: target nodeid not found in collection: {target}\n"
f"Got {len(all_ids)} nodeids; first few:\n "
+ "\n ".join(all_ids[:5]),
file=sys.stderr,
)
return _report("target_not_found", 2, collected=len(all_ids))
predecessors = [n for n in all_ids if n != target]
print(f"Collected {len(all_ids)} tests ({len(predecessors)} candidates).", file=sys.stderr)
# Sanity check 1: target passes alone.
print("Sanity check: target alone...", file=sys.stderr)
solo = _run([target])
if target_failed(solo, target):
print(
f"ERROR: target fails alone — this isn't an ordering issue.\n"
f"Outcome: {solo.outcomes.get(target)}\n"
f"pytest exit code: {solo.exit_code}",
file=sys.stderr,
)
return _report("fails_alone", 3, target_outcome=solo.outcomes.get(target))
if solo.outcomes.get(target) != "PASSED":
print(
f"ERROR: target was not run when invoked alone (outcome={solo.outcomes.get(target)!r}).\n"
f"pytest exit code: {solo.exit_code}\n"
f"--- pytest stdout ---\n{solo.stdout}",
file=sys.stderr,
)
return _report("target_not_run_alone", 3, target_outcome=solo.outcomes.get(target))
print(" OK (passes alone)", file=sys.stderr)
# Sanity check 2: target fails when run after everything else.
print("Sanity check: target after full suite...", file=sys.stderr)
full = _run([*predecessors, target])
if not target_failed(full, target):
print(
f"WARNING: target did not fail in the full ordered run "
f"(outcome={full.outcomes.get(target)!r}). Pollution may be "
f"order- or randomness-dependent; flake-bisect cannot help here.",
file=sys.stderr,
)
return _report("no_pollution_reproduced", 4, target_outcome=full.outcomes.get(target))
print(f" OK (target outcome: {full.outcomes[target]})", file=sys.stderr)
# Bisect.
iteration = {"i": 0}
def predicate(preds: list[str]) -> bool:
iteration["i"] += 1
res = _run([*preds, target])
failed = target_failed(res, target)
if args.verbose:
print(
f" [{iteration['i']:>3}] preds={len(preds):>4} -> "
f"{'FAIL' if failed else 'pass'}",
file=sys.stderr,
)
return failed
print(f"Bisecting {len(predecessors)} candidate predecessors...", file=sys.stderr)
try:
culprits = ddmin(predecessors, predicate, max_calls=args.max_runs)
except RuntimeError as e:
print(f"ERROR: {e}", file=sys.stderr)
return _report("max_runs_exhausted", 5, bisect_iterations=iteration["i"])
# Confirmation: (1) the minimal set reproduces the failure *standalone*, and
# (2) removing it from the full suite lets the target pass. If the target
# still fails without the culprits, there is at least one more independent
# polluter that this run did not surface.
reproduces_standalone: bool | None = None
target_clean_without_culprits: bool | None = None
if not args.no_confirm:
print("Confirming...", file=sys.stderr)
standalone = _run([*culprits, target])
reproduces_standalone = target_failed(standalone, target)
remaining = [n for n in predecessors if n not in set(culprits)]
without = _run([*remaining, target])
target_clean_without_culprits = not target_failed(without, target)
print(
f" minimal set reproduces standalone: "
f"{'yes' if reproduces_standalone else 'NO'}",
file=sys.stderr,
)
print(
f" target clean once culprits removed: "
f"{'yes' if target_clean_without_culprits else 'NO (more polluters remain)'}",
file=sys.stderr,
)
print("")
print(f"Minimal poisoning set ({len(culprits)} test{'s' if len(culprits) != 1 else ''}):")
for nid in culprits:
print(f" {nid}")
print("")
print("Reproduce locally:")
reproduce_cmd = "pytest " + " ".join([*culprits, target])
print(" " + reproduce_cmd)
if target_clean_without_culprits is False:
print("")
print(
"NOTE: the target still fails with these tests removed — there is at\n"
" least one more independent polluter. Re-run flake-bisect after\n"
" fixing this set to find the next one."
)
print("")
print(
f"pytest invocations: {runs['total']} "
f"(bisect iterations: {iteration['i']}, cap: {args.max_runs})",
file=sys.stderr,
)
return _report(
"poisoned",
0,
culprits=culprits,
reproduce_command=reproduce_cmd,
bisect_iterations=iteration["i"],
confirmation={
"reproduces_standalone": reproduces_standalone,
"target_clean_without_culprits": target_clean_without_culprits,
"additional_polluters_possible": target_clean_without_culprits is False,
},
)
if __name__ == "__main__":
raise SystemExit(main())