Repository navigation
Expand file tree
/
Copy pathinteraction_check.py
More file actions
375 lines (343 loc) · 17.6 KB
/
Copy pathinteraction_check.py
File metadata and controls
375 lines (343 loc) · 17.6 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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
"""Replay semantic JSONL scenarios against an explicitly selected local adapter.
No shell, sleeps, network client, GUI automation, or application dependency is required.
Each scenario gets a fresh adapter process. Expected results are never sent to it.
"""
from __future__ import annotations
import argparse
import json
import math
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import time
import xml.etree.ElementTree as ET
VERSION = "1.0.0"
LIMIT = 1024 * 1024
MAX_DEPTH = 64
class CheckError(Exception):
"""A failed check, optionally carrying the adapter's bounded diagnostic output."""
def __init__(self, message, *, stderr=""):
super().__init__(message)
self.stderr = stderr
self.trace = None
self.failure_step = None
def validate_json(value):
"""Bound nesting before recursive comparison/encoding, including Python API input."""
pending = [(value, 1)]
while pending:
item, depth = pending.pop()
if type(item) in (dict, list):
if depth > MAX_DEPTH:
raise CheckError(f"JSON nesting exceeds {MAX_DEPTH} containers")
if isinstance(item, dict):
if any(type(key) is not str for key in item):
raise CheckError("JSON object keys must be strings")
pending.extend((key, depth + 1) for key in item)
pending.extend((child, depth + 1) for child in item.values())
else:
pending.extend((child, depth + 1) for child in item)
elif type(item) is str:
try:
item.encode("utf-8")
except UnicodeError as error:
raise CheckError("JSON strings must contain valid Unicode scalar values") from error
elif type(item) is float:
if not math.isfinite(item):
raise CheckError("JSON numbers must be finite")
elif item is not None and type(item) not in (bool, int):
raise CheckError(f"Unsupported JSON value type: {type(item).__name__}")
def strict_json(text):
def reject(value):
raise CheckError(f"Non-JSON numeric constant: {value}")
def finite_float(value):
result = float(value)
if not math.isfinite(result):
raise CheckError(f"Number is outside the finite JSON range: {value}")
return result
def unique_object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise CheckError(f"Duplicate JSON key: {key!r}")
result[key] = value
return result
try:
value = json.loads(text, parse_constant=reject, parse_float=finite_float,
object_pairs_hook=unique_object)
except (ValueError, UnicodeError, RecursionError) as error:
raise CheckError(f"Invalid JSON: {error}") from error
validate_json(value)
return value
def validate(scenario):
validate_json(scenario)
if not isinstance(scenario, dict) or type(scenario.get("schema")) is not int or scenario["schema"] != 1:
raise CheckError("Scenario must declare schema: 1")
if not isinstance(scenario.get("name"), str) or not scenario["name"].strip():
raise CheckError("Scenario needs a nonempty name")
steps = scenario.get("steps")
if not isinstance(steps, list) or not steps:
raise CheckError("Scenario needs at least one step")
for index, step in enumerate(steps, 1):
if not isinstance(step, dict) or set(step) != {"event", "expect"}:
raise CheckError(f"Step {index}: use exactly event and expect")
if not isinstance(step["event"], dict) or not isinstance(step["expect"], dict) or not step["expect"]:
raise CheckError(f"Step {index}: event and nonempty expect must be objects")
def differences(expected, actual, path="state"):
"""Objects are subsets even inside arrays; array length/order and scalar types match."""
if isinstance(expected, dict):
if not isinstance(actual, dict):
return [f"{path}: expected an object, got {actual!r}"]
errors = []
for key, value in expected.items():
if key not in actual:
errors.append(f"{path}.{key}: missing")
else:
errors.extend(differences(value, actual[key], f"{path}.{key}"))
return errors
if isinstance(expected, list):
if not isinstance(actual, list) or len(expected) != len(actual):
return [f"{path}: expected {expected!r}, got {actual!r}"]
return [error for i, (a, b) in enumerate(zip(expected, actual))
for error in differences(a, b, f"{path}[{i}]")]
both_numbers = type(expected) in (int, float) and type(actual) in (int, float)
if (not both_numbers and type(expected) is not type(actual)) or expected != actual:
return [f"{path}: expected {expected!r}, got {actual!r}"]
return []
def run_adapter(command, payload, timeout):
"""Capture a trusted adapter, checking output growth while the process runs.
Sizes are checked periodically, not enforced as a disk quota: a fast writer may
overshoot between polls. Only the direct process is stopped, not its descendants.
"""
with tempfile.TemporaryFile() as source, tempfile.TemporaryFile() as output, \
tempfile.TemporaryFile() as diagnostic:
source.write(payload)
source.seek(0)
try:
# A file-backed stdin cannot block the parent when an adapter stops reading.
with subprocess.Popen(command, stdin=source, stdout=output, stderr=diagnostic) as process:
deadline = time.monotonic() + timeout
try:
while True:
if (os.fstat(output.fileno()).st_size > LIMIT
or os.fstat(diagnostic.fileno()).st_size > LIMIT):
raise CheckError("Adapter output exceeds 1 MiB")
remaining = deadline - time.monotonic()
if remaining <= 0:
raise CheckError(f"Adapter timed out after {timeout:g}s")
try:
process.wait(timeout=min(remaining, 0.05))
break
except subprocess.TimeoutExpired:
continue
except BaseException:
# Reap even on cancellation; Popen's context manager otherwise waits
# for a still-running adapter on exit.
process.kill()
process.wait()
raise
output.seek(0)
stdout = output.read(LIMIT + 1)
if len(stdout) > LIMIT or os.fstat(diagnostic.fileno()).st_size > LIMIT:
raise CheckError("Adapter output exceeds 1 MiB")
except CheckError as error:
diagnostic.seek(0)
error.stderr = diagnostic.read(LIMIT).decode("utf-8", errors="replace")
raise
except OSError as error:
raise CheckError(f"Cannot run adapter: {error}") from error
diagnostic.seek(0)
stderr = diagnostic.read(LIMIT).decode("utf-8", errors="replace")
if process.returncode:
raise CheckError(f"Adapter exited with {process.returncode}: {stderr[-2000:]}",
stderr=stderr)
return stdout, stderr
def replay(scenario, command, timeout=5.0, *, trace=False):
"""Replay a scenario; optionally retain each checked event/expectation/actual state."""
validate(scenario)
if not command or not math.isfinite(timeout) or timeout <= 0:
raise CheckError("A command and a positive finite timeout are required")
try:
payload = "".join(json.dumps({"protocol": 1, "id": i, "event": step["event"]},
ensure_ascii=False, allow_nan=False) + "\n"
for i, step in enumerate(scenario["steps"], 1)).encode("utf-8")
except (ValueError, UnicodeError, RecursionError) as error:
raise CheckError(f"Cannot encode scenario: {error}") from error
if len(payload) > LIMIT:
raise CheckError("Scenario exceeds 1 MiB")
stdout, stderr = run_adapter(command, payload, timeout)
entries = []
try:
try:
# JSONL is delimited by LF, not Unicode line separators inside strings.
lines = stdout.decode("utf-8").split("\n")
if lines[-1] == "":
lines.pop() # A single final LF is optional; extra blank lines are errors.
except UnicodeError as error:
raise CheckError("Adapter output is not UTF-8") from error
if len(lines) != len(scenario["steps"]):
raise CheckError(f"Expected {len(scenario['steps'])} replies, got {len(lines)}")
for index, (line, step) in enumerate(zip(lines, scenario["steps"]), 1):
try:
response = strict_json(line)
except CheckError as error:
raise CheckError(f"Step {index}: {error}") from error
if (not isinstance(response, dict) or type(response.get("protocol")) is not int
or response["protocol"] != 1 or type(response.get("id")) is not int
or response["id"] != index or not isinstance(response.get("state"), dict)):
raise CheckError(f"Step {index}: invalid envelope or mismatched reply id")
errors = differences(step["expect"], response["state"])
if trace:
entry = {"step": index, "event": step["event"], "expect": step["expect"],
"actual": response["state"], "passed": not errors}
if errors:
entry["differences"] = errors
entries.append(entry)
if errors:
error = CheckError(f"Step {index} ({step['event']}): " + "; ".join(errors))
error.failure_step = index
raise error
except CheckError as error:
error.stderr = stderr
if trace:
error.trace = entries
raise
result = {"name": scenario["name"], "passed": True, "steps": len(lines), "stderr": stderr}
if trace:
result["trace"] = entries
return result
def check_report_paths(destinations, scenarios):
"""Catch accidental input replacement and overlapping outputs before running adapters."""
previous = list(scenarios)
for destination in destinations:
for other in previous:
if (destination.resolve() == other.resolve()
or (destination.exists() and other.exists() and destination.samefile(other))):
raise CheckError(f"Report path overlaps an input or another report: {destination}")
previous.append(destination)
def write_report(path, content):
"""Replace only a complete report; a failed write leaves the previous file intact."""
temporary = None
try:
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", newline="\n",
dir=path.parent, prefix=f".{path.name}.",
suffix=".tmp", delete=False) as output:
temporary = Path(output.name)
output.write(content)
os.replace(temporary, path)
finally:
if temporary is not None:
temporary.unlink(missing_ok=True)
def junit_report(results):
def xml_text(value):
# JSON and stderr may include control characters that XML 1.0 cannot represent.
return "".join(char if (char in "\t\n\r" or " " <= char <= "\ud7ff"
or "\ue000" <= char <= "\ufffd" or "\U00010000" <= char <= "\U0010ffff")
else "\ufffd" for char in value)
suite = ET.Element("testsuite", name="interaction-check", tests=str(len(results)),
failures=str(sum(not result["passed"] for result in results)), errors="0")
for result in results:
case = ET.SubElement(suite, "testcase", name=xml_text(result["name"]),
classname="interaction-check", file=xml_text(result["source"]))
if not result["passed"]:
failure = ET.SubElement(case, "failure", message=xml_text(result["error"]),
type="CheckError")
failure.text = xml_text(result["error"])
if result.get("stderr"):
ET.SubElement(case, "system-err").text = xml_text(result["stderr"])
return '<?xml version="1.0" encoding="utf-8"?>\n' + ET.tostring(suite, encoding="unicode") + "\n"
def console(message, *, file=None):
"""Escape only characters the console cannot encode; reports retain Unicode."""
stream = sys.stdout if file is None else file
encoding = getattr(stream, "encoding", None)
if encoding is not None:
message = message.encode(encoding, errors="backslashreplace").decode(encoding)
print(message, file=stream)
def main(argv=None):
argv = list(sys.argv[1:] if argv is None else argv)
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--version", action="version", version=f"interaction-check {VERSION}")
parser.add_argument("--timeout", type=float, default=5.0)
parser.add_argument("--report", type=Path, help="write a JSON report atomically")
parser.add_argument("--trace", action="store_true",
help="include checked events, expectations and actual states in --report")
parser.add_argument("--junit", type=Path, help="write a JUnit XML report atomically")
parser.add_argument("--failure-dir", type=Path,
help="create a new directory for scenarios ending at their first state mismatch")
parser.add_argument("scenarios", nargs="+", type=Path)
if argv in (["--help"], ["-h"], ["--version"]):
parser.parse_args(argv)
if "--" not in argv:
parser.error("Separate the adapter command with --")
boundary = argv.index("--")
args = parser.parse_args(argv[:boundary])
command = argv[boundary + 1:]
if not command or not math.isfinite(args.timeout) or args.timeout <= 0:
parser.error("Specify an adapter command and a positive finite timeout")
if args.trace and args.report is None:
parser.error("--trace requires --report")
try:
destinations = [path for path in (args.report, args.junit) if path]
if args.failure_dir is not None:
destinations += [args.failure_dir]
destinations += [args.failure_dir / f"{index:04d}.json"
for index in range(1, len(args.scenarios) + 1)]
check_report_paths(destinations, args.scenarios)
if args.failure_dir is not None:
# A fresh directory prevents stale exports from looking like this run's results.
# The parent must already exist, like the JSON/JUnit report destinations.
args.failure_dir.mkdir()
except (CheckError, OSError, RuntimeError) as error:
parser.error(str(error))
results = []
for index, path in enumerate(args.scenarios, 1):
name = path.name
try:
if path.stat().st_size > LIMIT:
raise CheckError("Scenario exceeds 1 MiB")
scenario = strict_json(path.read_text(encoding="utf-8"))
if isinstance(scenario, dict) and isinstance(scenario.get("name"), str) and scenario["name"].strip():
name = scenario["name"]
result = replay(scenario, command, args.timeout, trace=args.trace)
except (CheckError, OSError, UnicodeError) as error:
result = {"name": name, "passed": False, "error": str(error)}
if isinstance(error, CheckError) and error.stderr:
result["stderr"] = error.stderr
if isinstance(error, CheckError) and error.trace is not None:
result["trace"] = error.trace
if isinstance(error, CheckError) and error.failure_step is not None:
result["failure_step"] = error.failure_step
if (args.failure_dir is not None and isinstance(error, CheckError)
and error.failure_step is not None):
destination = args.failure_dir / f"{index:04d}.json"
prefix = dict(scenario, steps=scenario["steps"][:error.failure_step])
try:
write_report(destination, json.dumps(prefix, ensure_ascii=False, indent=2) + "\n")
result["failure_scenario"] = str(destination)
except (OSError, UnicodeError) as export_error:
result["export_error"] = str(export_error)
console(f"ERROR writing failure scenario {destination}: {export_error}",
file=sys.stderr)
result["source"] = str(path)
results.append(result)
console(("PASS " if result["passed"] else "FAIL ") + result["name"])
if not result["passed"]:
console(" " + result["error"])
if result.get("failure_scenario"):
console(" Scenario: " + result["failure_scenario"])
report_failed = False
for destination, render in [
(args.report, lambda: json.dumps({"schema": 1, "version": VERSION, "results": results},
ensure_ascii=False, indent=2) + "\n"),
(args.junit, lambda: junit_report(results)),
]:
if destination:
try:
write_report(destination, render())
except (OSError, UnicodeError) as error:
console(f"ERROR writing report {destination}: {error}", file=sys.stderr)
report_failed = True
return 0 if not report_failed and all(result["passed"] for result in results) else 1
if __name__ == "__main__":
raise SystemExit(main())