interaction-check 0.1.0a6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,68 @@
1
+ Metadata-Version: 2.4
2
+ Name: interaction-check
3
+ Version: 0.1.0a6
4
+ Summary: Replay semantic event sequences against explicit local adapters
5
+ Author: PerchAnton
6
+ License-Expression: MIT OR Apache-2.0
7
+ Project-URL: Repository, https://github.com/PerchAnton/interaction-check
8
+ Project-URL: Documentation, https://github.com/PerchAnton/interaction-check#readme
9
+ Project-URL: Issues, https://github.com/PerchAnton/interaction-check/issues
10
+ Project-URL: Changelog, https://github.com/PerchAnton/interaction-check/blob/main/CHANGELOG.md
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Environment :: Console
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Software Development :: Testing
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE-MIT
19
+ License-File: LICENSE-APACHE
20
+ Dynamic: license-file
21
+
22
+ # interaction-check
23
+
24
+ A small Python command-line tool that replays semantic JSON event sequences against
25
+ an explicitly selected local adapter. Python 3.10+; **zero runtime dependencies**.
26
+ Licensed under MIT OR Apache-2.0. Experimental alpha: formats and CLI may still change.
27
+
28
+ ## Installation
29
+
30
+ Install a published copy of this prerelease from PyPI:
31
+
32
+ ```sh
33
+ python -m pip install 'interaction-check==0.1.0a6'
34
+ ```
35
+
36
+ An exact version selects this prerelease without opting into all future prereleases.
37
+ Use a virtual environment. On Windows, the same command works with `py -m pip`.
38
+ For other distribution options and current publication status, see the
39
+ [project README](https://github.com/PerchAnton/interaction-check#install-the-released-command).
40
+
41
+ ## Usage
42
+
43
+ ```sh
44
+ interaction-check --version
45
+ interaction-check --failure-dir failures --trace --report report.json scenario.json -- path/to/adapter
46
+ ```
47
+
48
+ The adapter is a trusted program you select; it receives events as JSONL and returns
49
+ states. Expected states are never sent to it. Each scenario starts a fresh process.
50
+ The runner is not a sandbox and does not download or discover adapters automatically.
51
+
52
+ `--failure-dir` creates a **new** directory containing numbered JSON scenarios through
53
+ the first state mismatch. Expectations stay unchanged. These are checked prefixes, not
54
+ automatically minimized or independently verified reproductions. Re-run an export with
55
+ the same adapter revision. Crashes, timeouts and malformed protocol replies do not
56
+ produce a guessed state-mismatch scenario.
57
+
58
+ The installed wheel contains the runner and its licenses. Examples and application
59
+ adapters remain in the repository and may have their own dependencies. The separate
60
+ Rust library edit-session is not required.
61
+
62
+ - [Scenario and adapter protocol](https://github.com/PerchAnton/interaction-check#scenario-format)
63
+ - [Worked XState example](https://github.com/PerchAnton/interaction-check/tree/main/examples/xstate)
64
+ - [Moving a useful scenario into a native test](https://github.com/PerchAnton/interaction-check/blob/main/docs/NATIVE_TESTS.md)
65
+ - [Measured benefits and costs](https://github.com/PerchAnton/interaction-check/blob/main/docs/VALUE.md)
66
+
67
+ If a normal project test is simpler, keep that test. Replay is useful when sharing an
68
+ event sequence and a consistent report earns the adapter and runner maintenance cost.
@@ -0,0 +1,8 @@
1
+ interaction_check.py,sha256=FxorEVn1Gp2x0vPoWVnDS3x4JjqPTwc-pIKPFfduMmo,17470
2
+ interaction_check-0.1.0a6.dist-info/licenses/LICENSE-APACHE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
3
+ interaction_check-0.1.0a6.dist-info/licenses/LICENSE-MIT,sha256=ZlqUL5MXo1iTC0cK1SKiKlj_bDRtsDlUY-yE3T4Z13U,1067
4
+ interaction_check-0.1.0a6.dist-info/METADATA,sha256=MD52dcVR8N-BH_2ctzYAUqQnmOca81h-vWjgFWohB0s,3247
5
+ interaction_check-0.1.0a6.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ interaction_check-0.1.0a6.dist-info/entry_points.txt,sha256=-N-zlzGcyMJBGZWExvoTRrMlRtCq8veFbRTWcMA9iNo,61
7
+ interaction_check-0.1.0a6.dist-info/top_level.txt,sha256=FALQVtc_dXNieBc8DOfjNeTpYZAFaz_5yeB7qZYnO9g,18
8
+ interaction_check-0.1.0a6.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ interaction-check = interaction_check:main
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 PerchAnton
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ interaction_check
interaction_check.py ADDED
@@ -0,0 +1,364 @@
1
+ """Replay semantic JSONL scenarios against an explicitly selected local adapter.
2
+
3
+ No shell, sleeps, network client, GUI automation, or application dependency is required.
4
+ Each scenario gets a fresh adapter process. Expected results are never sent to it.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ import json
10
+ import math
11
+ import os
12
+ from pathlib import Path
13
+ import subprocess
14
+ import sys
15
+ import tempfile
16
+ import time
17
+ import xml.etree.ElementTree as ET
18
+
19
+ VERSION = "0.1.0a6"
20
+ LIMIT = 1024 * 1024
21
+ MAX_DEPTH = 64
22
+
23
+
24
+ class CheckError(Exception):
25
+ """A failed check, optionally carrying the adapter's bounded diagnostic output."""
26
+
27
+ def __init__(self, message, *, stderr=""):
28
+ super().__init__(message)
29
+ self.stderr = stderr
30
+ self.trace = None
31
+ self.failure_step = None
32
+
33
+
34
+ def validate_json(value):
35
+ """Bound nesting before recursive comparison/encoding, including Python API input."""
36
+ pending = [(value, 1)]
37
+ while pending:
38
+ item, depth = pending.pop()
39
+ if type(item) in (dict, list):
40
+ if depth > MAX_DEPTH:
41
+ raise CheckError(f"JSON nesting exceeds {MAX_DEPTH} containers")
42
+ if isinstance(item, dict):
43
+ if any(type(key) is not str for key in item):
44
+ raise CheckError("JSON object keys must be strings")
45
+ pending.extend((key, depth + 1) for key in item)
46
+ pending.extend((child, depth + 1) for child in item.values())
47
+ else:
48
+ pending.extend((child, depth + 1) for child in item)
49
+ elif type(item) is str:
50
+ try:
51
+ item.encode("utf-8")
52
+ except UnicodeError as error:
53
+ raise CheckError("JSON strings must contain valid Unicode scalar values") from error
54
+ elif type(item) is float:
55
+ if not math.isfinite(item):
56
+ raise CheckError("JSON numbers must be finite")
57
+ elif item is not None and type(item) not in (bool, int):
58
+ raise CheckError(f"Unsupported JSON value type: {type(item).__name__}")
59
+
60
+
61
+ def strict_json(text):
62
+ def reject(value):
63
+ raise CheckError(f"Non-JSON numeric constant: {value}")
64
+ def finite_float(value):
65
+ result = float(value)
66
+ if not math.isfinite(result):
67
+ raise CheckError(f"Number is outside the finite JSON range: {value}")
68
+ return result
69
+ def unique_object(pairs):
70
+ result = {}
71
+ for key, value in pairs:
72
+ if key in result:
73
+ raise CheckError(f"Duplicate JSON key: {key!r}")
74
+ result[key] = value
75
+ return result
76
+ try:
77
+ value = json.loads(text, parse_constant=reject, parse_float=finite_float,
78
+ object_pairs_hook=unique_object)
79
+ except (ValueError, UnicodeError, RecursionError) as error:
80
+ raise CheckError(f"Invalid JSON: {error}") from error
81
+ validate_json(value)
82
+ return value
83
+
84
+
85
+ def validate(scenario):
86
+ validate_json(scenario)
87
+ if not isinstance(scenario, dict) or type(scenario.get("schema")) is not int or scenario["schema"] != 1:
88
+ raise CheckError("Scenario must declare schema: 1")
89
+ if not isinstance(scenario.get("name"), str) or not scenario["name"].strip():
90
+ raise CheckError("Scenario needs a nonempty name")
91
+ steps = scenario.get("steps")
92
+ if not isinstance(steps, list) or not steps:
93
+ raise CheckError("Scenario needs at least one step")
94
+ for index, step in enumerate(steps, 1):
95
+ if not isinstance(step, dict) or set(step) != {"event", "expect"}:
96
+ raise CheckError(f"Step {index}: use exactly event and expect")
97
+ if not isinstance(step["event"], dict) or not isinstance(step["expect"], dict) or not step["expect"]:
98
+ raise CheckError(f"Step {index}: event and nonempty expect must be objects")
99
+
100
+
101
+ def differences(expected, actual, path="state"):
102
+ """Objects are subsets even inside arrays; array length/order and scalar types match."""
103
+ if isinstance(expected, dict):
104
+ if not isinstance(actual, dict):
105
+ return [f"{path}: expected an object, got {actual!r}"]
106
+ errors = []
107
+ for key, value in expected.items():
108
+ if key not in actual:
109
+ errors.append(f"{path}.{key}: missing")
110
+ else:
111
+ errors.extend(differences(value, actual[key], f"{path}.{key}"))
112
+ return errors
113
+ if isinstance(expected, list):
114
+ if not isinstance(actual, list) or len(expected) != len(actual):
115
+ return [f"{path}: expected {expected!r}, got {actual!r}"]
116
+ return [error for i, (a, b) in enumerate(zip(expected, actual))
117
+ for error in differences(a, b, f"{path}[{i}]")]
118
+ both_numbers = type(expected) in (int, float) and type(actual) in (int, float)
119
+ if (not both_numbers and type(expected) is not type(actual)) or expected != actual:
120
+ return [f"{path}: expected {expected!r}, got {actual!r}"]
121
+ return []
122
+
123
+
124
+ def run_adapter(command, payload, timeout):
125
+ """Capture a trusted adapter, checking output growth while the process runs.
126
+
127
+ Sizes are checked periodically, not enforced as a disk quota: a fast writer may
128
+ overshoot between polls. Only the direct process is stopped, not its descendants.
129
+ """
130
+ with tempfile.TemporaryFile() as source, tempfile.TemporaryFile() as output, \
131
+ tempfile.TemporaryFile() as diagnostic:
132
+ source.write(payload)
133
+ source.seek(0)
134
+ try:
135
+ # A file-backed stdin cannot block the parent when an adapter stops reading.
136
+ with subprocess.Popen(command, stdin=source, stdout=output, stderr=diagnostic) as process:
137
+ deadline = time.monotonic() + timeout
138
+ try:
139
+ while True:
140
+ if (os.fstat(output.fileno()).st_size > LIMIT
141
+ or os.fstat(diagnostic.fileno()).st_size > LIMIT):
142
+ raise CheckError("Adapter output exceeds 1 MiB")
143
+ remaining = deadline - time.monotonic()
144
+ if remaining <= 0:
145
+ raise CheckError(f"Adapter timed out after {timeout:g}s")
146
+ try:
147
+ process.wait(timeout=min(remaining, 0.05))
148
+ break
149
+ except subprocess.TimeoutExpired:
150
+ continue
151
+ except BaseException:
152
+ # Reap even on cancellation; Popen's context manager otherwise waits
153
+ # for a still-running adapter on exit.
154
+ process.kill()
155
+ process.wait()
156
+ raise
157
+ output.seek(0)
158
+ stdout = output.read(LIMIT + 1)
159
+ if len(stdout) > LIMIT or os.fstat(diagnostic.fileno()).st_size > LIMIT:
160
+ raise CheckError("Adapter output exceeds 1 MiB")
161
+ except CheckError as error:
162
+ diagnostic.seek(0)
163
+ error.stderr = diagnostic.read(LIMIT).decode("utf-8", errors="replace")
164
+ raise
165
+ except OSError as error:
166
+ raise CheckError(f"Cannot run adapter: {error}") from error
167
+ diagnostic.seek(0)
168
+ stderr = diagnostic.read(LIMIT).decode("utf-8", errors="replace")
169
+ if process.returncode:
170
+ raise CheckError(f"Adapter exited with {process.returncode}: {stderr[-2000:]}",
171
+ stderr=stderr)
172
+ return stdout, stderr
173
+
174
+
175
+ def replay(scenario, command, timeout=5.0, *, trace=False):
176
+ """Replay a scenario; optionally retain each checked event/expectation/actual state."""
177
+ validate(scenario)
178
+ if not command or not math.isfinite(timeout) or timeout <= 0:
179
+ raise CheckError("A command and a positive finite timeout are required")
180
+ try:
181
+ payload = "".join(json.dumps({"protocol": 1, "id": i, "event": step["event"]},
182
+ ensure_ascii=False, allow_nan=False) + "\n"
183
+ for i, step in enumerate(scenario["steps"], 1)).encode("utf-8")
184
+ except (ValueError, UnicodeError, RecursionError) as error:
185
+ raise CheckError(f"Cannot encode scenario: {error}") from error
186
+ if len(payload) > LIMIT:
187
+ raise CheckError("Scenario exceeds 1 MiB")
188
+ stdout, stderr = run_adapter(command, payload, timeout)
189
+ entries = []
190
+ try:
191
+ try:
192
+ # JSONL is delimited by LF, not Unicode line separators inside strings.
193
+ lines = stdout.decode("utf-8").split("\n")
194
+ if lines[-1] == "":
195
+ lines.pop() # A single final LF is optional; extra blank lines are errors.
196
+ except UnicodeError as error:
197
+ raise CheckError("Adapter output is not UTF-8") from error
198
+ if len(lines) != len(scenario["steps"]):
199
+ raise CheckError(f"Expected {len(scenario['steps'])} replies, got {len(lines)}")
200
+ for index, (line, step) in enumerate(zip(lines, scenario["steps"]), 1):
201
+ try:
202
+ response = strict_json(line)
203
+ except CheckError as error:
204
+ raise CheckError(f"Step {index}: {error}") from error
205
+ if (not isinstance(response, dict) or type(response.get("protocol")) is not int
206
+ or response["protocol"] != 1 or type(response.get("id")) is not int
207
+ or response["id"] != index or not isinstance(response.get("state"), dict)):
208
+ raise CheckError(f"Step {index}: invalid envelope or mismatched reply id")
209
+ errors = differences(step["expect"], response["state"])
210
+ if trace:
211
+ entry = {"step": index, "event": step["event"], "expect": step["expect"],
212
+ "actual": response["state"], "passed": not errors}
213
+ if errors:
214
+ entry["differences"] = errors
215
+ entries.append(entry)
216
+ if errors:
217
+ error = CheckError(f"Step {index} ({step['event']}): " + "; ".join(errors))
218
+ error.failure_step = index
219
+ raise error
220
+ except CheckError as error:
221
+ error.stderr = stderr
222
+ if trace:
223
+ error.trace = entries
224
+ raise
225
+ result = {"name": scenario["name"], "passed": True, "steps": len(lines), "stderr": stderr}
226
+ if trace:
227
+ result["trace"] = entries
228
+ return result
229
+
230
+
231
+ def check_report_paths(destinations, scenarios):
232
+ """Catch accidental input replacement and overlapping outputs before running adapters."""
233
+ previous = list(scenarios)
234
+ for destination in destinations:
235
+ for other in previous:
236
+ if (destination.resolve() == other.resolve()
237
+ or (destination.exists() and other.exists() and destination.samefile(other))):
238
+ raise CheckError(f"Report path overlaps an input or another report: {destination}")
239
+ previous.append(destination)
240
+
241
+
242
+ def write_report(path, content):
243
+ """Replace only a complete report; a failed write leaves the previous file intact."""
244
+ temporary = None
245
+ try:
246
+ with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", newline="\n",
247
+ dir=path.parent, prefix=f".{path.name}.",
248
+ suffix=".tmp", delete=False) as output:
249
+ temporary = Path(output.name)
250
+ output.write(content)
251
+ os.replace(temporary, path)
252
+ finally:
253
+ if temporary is not None:
254
+ temporary.unlink(missing_ok=True)
255
+
256
+
257
+ def junit_report(results):
258
+ def xml_text(value):
259
+ # JSON and stderr may include control characters that XML 1.0 cannot represent.
260
+ return "".join(char if (char in "\t\n\r" or " " <= char <= "\ud7ff"
261
+ or "\ue000" <= char <= "\ufffd" or "\U00010000" <= char <= "\U0010ffff")
262
+ else "\ufffd" for char in value)
263
+
264
+ suite = ET.Element("testsuite", name="interaction-check", tests=str(len(results)),
265
+ failures=str(sum(not result["passed"] for result in results)), errors="0")
266
+ for result in results:
267
+ case = ET.SubElement(suite, "testcase", name=xml_text(result["name"]),
268
+ classname="interaction-check", file=xml_text(result["source"]))
269
+ if not result["passed"]:
270
+ failure = ET.SubElement(case, "failure", message=xml_text(result["error"]),
271
+ type="CheckError")
272
+ failure.text = xml_text(result["error"])
273
+ if result.get("stderr"):
274
+ ET.SubElement(case, "system-err").text = xml_text(result["stderr"])
275
+ return '<?xml version="1.0" encoding="utf-8"?>\n' + ET.tostring(suite, encoding="unicode") + "\n"
276
+
277
+
278
+ def main(argv=None):
279
+ argv = list(sys.argv[1:] if argv is None else argv)
280
+ parser = argparse.ArgumentParser(description=__doc__)
281
+ parser.add_argument("--version", action="version", version=f"interaction-check {VERSION}")
282
+ parser.add_argument("--timeout", type=float, default=5.0)
283
+ parser.add_argument("--report", type=Path, help="write a JSON report atomically")
284
+ parser.add_argument("--trace", action="store_true",
285
+ help="include checked events, expectations and actual states in --report")
286
+ parser.add_argument("--junit", type=Path, help="write a JUnit XML report atomically")
287
+ parser.add_argument("--failure-dir", type=Path,
288
+ help="create a new directory for scenarios ending at their first state mismatch")
289
+ parser.add_argument("scenarios", nargs="+", type=Path)
290
+ if argv in (["--help"], ["-h"], ["--version"]):
291
+ parser.parse_args(argv)
292
+ if "--" not in argv:
293
+ parser.error("Separate the adapter command with --")
294
+ boundary = argv.index("--")
295
+ args = parser.parse_args(argv[:boundary])
296
+ command = argv[boundary + 1:]
297
+ if not command or not math.isfinite(args.timeout) or args.timeout <= 0:
298
+ parser.error("Specify an adapter command and a positive finite timeout")
299
+ if args.trace and args.report is None:
300
+ parser.error("--trace requires --report")
301
+ try:
302
+ destinations = [path for path in (args.report, args.junit) if path]
303
+ if args.failure_dir is not None:
304
+ destinations += [args.failure_dir]
305
+ destinations += [args.failure_dir / f"{index:04d}.json"
306
+ for index in range(1, len(args.scenarios) + 1)]
307
+ check_report_paths(destinations, args.scenarios)
308
+ if args.failure_dir is not None:
309
+ # A fresh directory prevents stale exports from looking like this run's results.
310
+ # The parent must already exist, like the JSON/JUnit report destinations.
311
+ args.failure_dir.mkdir()
312
+ except (CheckError, OSError, RuntimeError) as error:
313
+ parser.error(str(error))
314
+ results = []
315
+ for index, path in enumerate(args.scenarios, 1):
316
+ name = path.name
317
+ try:
318
+ if path.stat().st_size > LIMIT:
319
+ raise CheckError("Scenario exceeds 1 MiB")
320
+ scenario = strict_json(path.read_text(encoding="utf-8"))
321
+ if isinstance(scenario, dict) and isinstance(scenario.get("name"), str) and scenario["name"].strip():
322
+ name = scenario["name"]
323
+ result = replay(scenario, command, args.timeout, trace=args.trace)
324
+ except (CheckError, OSError, UnicodeError) as error:
325
+ result = {"name": name, "passed": False, "error": str(error)}
326
+ if isinstance(error, CheckError) and error.stderr:
327
+ result["stderr"] = error.stderr
328
+ if isinstance(error, CheckError) and error.trace is not None:
329
+ result["trace"] = error.trace
330
+ if (args.failure_dir is not None and isinstance(error, CheckError)
331
+ and error.failure_step is not None):
332
+ destination = args.failure_dir / f"{index:04d}.json"
333
+ prefix = dict(scenario, steps=scenario["steps"][:error.failure_step])
334
+ try:
335
+ write_report(destination, json.dumps(prefix, ensure_ascii=False, indent=2) + "\n")
336
+ result["failure_scenario"] = str(destination)
337
+ except (OSError, UnicodeError) as export_error:
338
+ result["export_error"] = str(export_error)
339
+ print(f"ERROR writing failure scenario {destination}: {export_error}",
340
+ file=sys.stderr)
341
+ result["source"] = str(path)
342
+ results.append(result)
343
+ print(("PASS " if result["passed"] else "FAIL ") + result["name"])
344
+ if not result["passed"]:
345
+ print(" " + result["error"])
346
+ if result.get("failure_scenario"):
347
+ print(" Scenario: " + result["failure_scenario"])
348
+ report_failed = False
349
+ for destination, render in [
350
+ (args.report, lambda: json.dumps({"version": VERSION, "results": results},
351
+ ensure_ascii=False, indent=2) + "\n"),
352
+ (args.junit, lambda: junit_report(results)),
353
+ ]:
354
+ if destination:
355
+ try:
356
+ write_report(destination, render())
357
+ except (OSError, UnicodeError) as error:
358
+ print(f"ERROR writing report {destination}: {error}", file=sys.stderr)
359
+ report_failed = True
360
+ return 0 if not report_failed and all(result["passed"] for result in results) else 1
361
+
362
+
363
+ if __name__ == "__main__":
364
+ raise SystemExit(main())