sim-cli-core 0.2.4__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.
- sim/__init__.py +11 -0
- sim/__main__.py +24 -0
- sim/_plugin_install.py +451 -0
- sim/_timeout.py +115 -0
- sim/cli.py +1353 -0
- sim/compat.py +411 -0
- sim/config.py +380 -0
- sim/describe.py +346 -0
- sim/driver.py +190 -0
- sim/drivers/__init__.py +161 -0
- sim/drivers/coolprop/__init__.py +3 -0
- sim/drivers/coolprop/driver.py +183 -0
- sim/drivers/openfoam/__init__.py +4 -0
- sim/drivers/openfoam/compatibility.yaml +37 -0
- sim/drivers/openfoam/driver.py +432 -0
- sim/gui/LICENSES/ATTRIBUTION.md +24 -0
- sim/gui/__init__.py +230 -0
- sim/gui/_pywinauto_tools.py +452 -0
- sim/gui/_win32_dialog.py +148 -0
- sim/history.py +170 -0
- sim/inspect.py +1088 -0
- sim/plugins.py +468 -0
- sim/runner.py +195 -0
- sim/server.py +547 -0
- sim/session.py +224 -0
- sim/testing/__init__.py +30 -0
- sim/testing/protocol_conformance.py +264 -0
- sim_cli_core-0.2.4.dist-info/METADATA +309 -0
- sim_cli_core-0.2.4.dist-info/RECORD +33 -0
- sim_cli_core-0.2.4.dist-info/WHEEL +4 -0
- sim_cli_core-0.2.4.dist-info/entry_points.txt +2 -0
- sim_cli_core-0.2.4.dist-info/licenses/LICENSE +190 -0
- sim_cli_core-0.2.4.dist-info/licenses/NOTICE +72 -0
sim/session.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""Session client — HTTP client that talks to sim-server.
|
|
2
|
+
|
|
3
|
+
Always HTTP, whether local or remote:
|
|
4
|
+
sim connect --solver pyfluent # auto-starts sim-server locally
|
|
5
|
+
sim connect --solver pyfluent --host 100.90.x.x # talks to remote sim-server
|
|
6
|
+
|
|
7
|
+
If no server is running locally, `connect` auto-starts one as a background process.
|
|
8
|
+
|
|
9
|
+
Multi-session (issue #26): the client carries an optional `session_id`. When
|
|
10
|
+
set, every per-session call (`run`, `query`, `disconnect`, `screenshot`)
|
|
11
|
+
sends `X-Sim-Session: <id>`. When unset, the server picks the sole live
|
|
12
|
+
session as default — so single-session callers work unchanged.
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import subprocess
|
|
17
|
+
import sys
|
|
18
|
+
import time
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
import httpx
|
|
22
|
+
|
|
23
|
+
DEFAULT_HOST = "localhost"
|
|
24
|
+
DEFAULT_PORT = 7600
|
|
25
|
+
CONNECT_TIMEOUT_S = 180
|
|
26
|
+
CMD_TIMEOUT_S = 600
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _local_hosts() -> set[str]:
|
|
30
|
+
return {"localhost", "127.0.0.1", "::1", ""}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _httpx_client(host: str, timeout: float) -> httpx.Client:
|
|
34
|
+
"""Build an httpx Client that bypasses system proxies for localhost.
|
|
35
|
+
|
|
36
|
+
Windows workstations often run a system-wide proxy (Privoxy, Clash, etc.)
|
|
37
|
+
which happily intercepts 127.0.0.1:* calls and returns garbage. Setting
|
|
38
|
+
trust_env=False for localhost targets sidesteps all of that.
|
|
39
|
+
"""
|
|
40
|
+
if host in _local_hosts():
|
|
41
|
+
return httpx.Client(timeout=timeout, trust_env=False)
|
|
42
|
+
return httpx.Client(timeout=timeout)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class SessionClient:
|
|
46
|
+
"""HTTP client for sim-server. Works with local or remote servers.
|
|
47
|
+
|
|
48
|
+
`session_id` is used as the `X-Sim-Session` header on per-session
|
|
49
|
+
endpoints. Leave it None to use the server's default-picking rules
|
|
50
|
+
(works whenever exactly one session is live).
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(
|
|
54
|
+
self,
|
|
55
|
+
host: str = DEFAULT_HOST,
|
|
56
|
+
port: int = DEFAULT_PORT,
|
|
57
|
+
session_id: str | None = None,
|
|
58
|
+
):
|
|
59
|
+
self._base = f"http://{host}:{port}"
|
|
60
|
+
self._host = host
|
|
61
|
+
self._port = port
|
|
62
|
+
self.session_id = session_id
|
|
63
|
+
|
|
64
|
+
def _is_local(self) -> bool:
|
|
65
|
+
return self._host in ("localhost", "127.0.0.1")
|
|
66
|
+
|
|
67
|
+
def _server_reachable(self) -> bool:
|
|
68
|
+
try:
|
|
69
|
+
with _httpx_client(self._host, timeout=3) as c:
|
|
70
|
+
r = c.get(f"{self._base}/ps")
|
|
71
|
+
return r.status_code == 200
|
|
72
|
+
except (httpx.ConnectError, httpx.TimeoutException, httpx.ReadTimeout):
|
|
73
|
+
return False
|
|
74
|
+
|
|
75
|
+
def _auto_start_server(self) -> bool:
|
|
76
|
+
"""Start sim-server locally as a background process.
|
|
77
|
+
|
|
78
|
+
On Windows DETACHED_PROCESS hides the console — so any write to
|
|
79
|
+
stdout/stderr from uvicorn (or any import-time print) crashes the
|
|
80
|
+
subprocess. Redirecting stdio to DEVNULL avoids that.
|
|
81
|
+
"""
|
|
82
|
+
import os
|
|
83
|
+
sim_dir = Path(os.environ.get("SIM_DIR") or (Path.cwd() / ".sim"))
|
|
84
|
+
sim_dir.mkdir(parents=True, exist_ok=True)
|
|
85
|
+
log_path = sim_dir / "sim-serve.log"
|
|
86
|
+
|
|
87
|
+
cmd = [sys.executable, "-c",
|
|
88
|
+
"import uvicorn; from sim.server import app; "
|
|
89
|
+
f"uvicorn.run(app, host='127.0.0.1', port={self._port}, log_level='warning')"]
|
|
90
|
+
|
|
91
|
+
try:
|
|
92
|
+
log_fh = open(log_path, "ab")
|
|
93
|
+
if sys.platform == "win32":
|
|
94
|
+
CREATE_NEW_PROCESS_GROUP = 0x00000200
|
|
95
|
+
DETACHED_PROCESS = 0x00000008
|
|
96
|
+
subprocess.Popen(
|
|
97
|
+
cmd,
|
|
98
|
+
stdin=subprocess.DEVNULL,
|
|
99
|
+
stdout=log_fh,
|
|
100
|
+
stderr=log_fh,
|
|
101
|
+
creationflags=CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS,
|
|
102
|
+
close_fds=True,
|
|
103
|
+
)
|
|
104
|
+
else:
|
|
105
|
+
subprocess.Popen(
|
|
106
|
+
cmd,
|
|
107
|
+
stdin=subprocess.DEVNULL,
|
|
108
|
+
stdout=log_fh,
|
|
109
|
+
stderr=log_fh,
|
|
110
|
+
start_new_session=True,
|
|
111
|
+
close_fds=True,
|
|
112
|
+
)
|
|
113
|
+
except Exception:
|
|
114
|
+
return False
|
|
115
|
+
|
|
116
|
+
# Wait for server to become reachable
|
|
117
|
+
deadline = time.time() + 15
|
|
118
|
+
while time.time() < deadline:
|
|
119
|
+
if self._server_reachable():
|
|
120
|
+
return True
|
|
121
|
+
time.sleep(0.3)
|
|
122
|
+
return False
|
|
123
|
+
|
|
124
|
+
def _session_headers(self) -> dict[str, str]:
|
|
125
|
+
return {"X-Sim-Session": self.session_id} if self.session_id else {}
|
|
126
|
+
|
|
127
|
+
def _request(
|
|
128
|
+
self,
|
|
129
|
+
method: str,
|
|
130
|
+
path: str,
|
|
131
|
+
*,
|
|
132
|
+
timeout: float = CMD_TIMEOUT_S,
|
|
133
|
+
session_scoped: bool = False,
|
|
134
|
+
**kwargs,
|
|
135
|
+
) -> dict:
|
|
136
|
+
headers = kwargs.pop("headers", {}) or {}
|
|
137
|
+
if session_scoped:
|
|
138
|
+
headers = {**self._session_headers(), **headers}
|
|
139
|
+
try:
|
|
140
|
+
with _httpx_client(self._host, timeout=timeout) as c:
|
|
141
|
+
r = getattr(c, method)(f"{self._base}{path}", headers=headers, **kwargs)
|
|
142
|
+
data = r.json()
|
|
143
|
+
if r.status_code >= 400:
|
|
144
|
+
return {"ok": False, "error": data.get("detail", str(data))}
|
|
145
|
+
return data
|
|
146
|
+
except httpx.ConnectError:
|
|
147
|
+
return {"ok": False, "error": f"cannot reach sim-server at {self._base}"}
|
|
148
|
+
except httpx.TimeoutException:
|
|
149
|
+
return {"ok": False, "error": f"request timed out after {timeout}s"}
|
|
150
|
+
except Exception as e:
|
|
151
|
+
return {"ok": False, "error": str(e)}
|
|
152
|
+
|
|
153
|
+
def connect(self, solver: str, mode: str = "meshing",
|
|
154
|
+
ui_mode: str = "no_gui", processors: int = 1,
|
|
155
|
+
workspace: str | None = None) -> dict:
|
|
156
|
+
# Auto-start local server if needed
|
|
157
|
+
if self._is_local() and not self._server_reachable():
|
|
158
|
+
if not self._auto_start_server():
|
|
159
|
+
return {"ok": False, "error": "failed to auto-start sim-server locally"}
|
|
160
|
+
|
|
161
|
+
body: dict = {
|
|
162
|
+
"solver": solver, "mode": mode,
|
|
163
|
+
"ui_mode": ui_mode, "processors": processors,
|
|
164
|
+
}
|
|
165
|
+
if workspace is not None:
|
|
166
|
+
body["workspace"] = workspace
|
|
167
|
+
resp = self._request("post", "/connect", timeout=CONNECT_TIMEOUT_S, json=body)
|
|
168
|
+
# Remember the new session_id so subsequent calls on this client
|
|
169
|
+
# route to it even if another session shows up later.
|
|
170
|
+
if resp.get("ok"):
|
|
171
|
+
new_sid = (resp.get("data") or {}).get("session_id")
|
|
172
|
+
if new_sid:
|
|
173
|
+
self.session_id = new_sid
|
|
174
|
+
return resp
|
|
175
|
+
|
|
176
|
+
def run(self, code: str, label: str = "cli-snippet") -> dict:
|
|
177
|
+
return self._request(
|
|
178
|
+
"post", "/exec",
|
|
179
|
+
json={"code": code, "label": label},
|
|
180
|
+
session_scoped=True,
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
def query(self, name: str) -> dict:
|
|
184
|
+
return self._request(
|
|
185
|
+
"get", f"/inspect/{name}",
|
|
186
|
+
timeout=30,
|
|
187
|
+
session_scoped=True,
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
def disconnect(self) -> dict:
|
|
191
|
+
return self._request(
|
|
192
|
+
"post", "/disconnect",
|
|
193
|
+
timeout=30,
|
|
194
|
+
session_scoped=True,
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
def stop(self) -> dict:
|
|
198
|
+
"""Stop the sim-server process itself (tears down all sessions).
|
|
199
|
+
|
|
200
|
+
POSTs /shutdown. The server tears down active sessions, flushes
|
|
201
|
+
the response, then exits cleanly via os._exit(0). Because the
|
|
202
|
+
process dies mid-stream, the connection often closes before we
|
|
203
|
+
read the body — that's expected, treat it as success.
|
|
204
|
+
"""
|
|
205
|
+
try:
|
|
206
|
+
with _httpx_client(self._host, timeout=10) as c:
|
|
207
|
+
r = c.post(f"{self._base}/shutdown")
|
|
208
|
+
try:
|
|
209
|
+
return r.json()
|
|
210
|
+
except Exception:
|
|
211
|
+
return {"ok": True, "data": {"shutting_down": True}}
|
|
212
|
+
except (httpx.ConnectError, httpx.RemoteProtocolError, httpx.ReadError):
|
|
213
|
+
return {"ok": True, "data": {"shutting_down": True}}
|
|
214
|
+
except httpx.TimeoutException:
|
|
215
|
+
return {"ok": False, "error": "timed out waiting for /shutdown"}
|
|
216
|
+
except Exception as e:
|
|
217
|
+
return {"ok": False, "error": str(e)}
|
|
218
|
+
|
|
219
|
+
def status(self) -> dict:
|
|
220
|
+
"""GET /ps — returns the multi-session shape {sessions: [...], default_session}."""
|
|
221
|
+
return self._request("get", "/ps", timeout=10)
|
|
222
|
+
|
|
223
|
+
def screenshot(self) -> dict:
|
|
224
|
+
return self._request("get", "/screenshot", timeout=30)
|
sim/testing/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Test helpers for plugin authors.
|
|
2
|
+
|
|
3
|
+
The single most important export here is :func:`assert_protocol_conformance`,
|
|
4
|
+
which every external plugin should call from its own test suite to confirm
|
|
5
|
+
its driver class meets the contract sim-cli depends on.
|
|
6
|
+
|
|
7
|
+
Plugins typically pull this in via::
|
|
8
|
+
|
|
9
|
+
# sim-plugin-<solver>/tests/test_protocol.py
|
|
10
|
+
from sim.testing import assert_protocol_conformance
|
|
11
|
+
from sim_plugin_<solver> import <Solver>Driver
|
|
12
|
+
|
|
13
|
+
def test_protocol_conformance():
|
|
14
|
+
assert_protocol_conformance(<Solver>Driver)
|
|
15
|
+
|
|
16
|
+
This module intentionally has zero plugin-author boilerplate beyond that.
|
|
17
|
+
"""
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
from .protocol_conformance import (
|
|
21
|
+
assert_protocol_conformance,
|
|
22
|
+
check_driver,
|
|
23
|
+
ConformanceFailure,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"assert_protocol_conformance",
|
|
28
|
+
"check_driver",
|
|
29
|
+
"ConformanceFailure",
|
|
30
|
+
]
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
"""Conformance checks every sim plugin's CI should run.
|
|
2
|
+
|
|
3
|
+
This file is the single source of truth for "does this driver class
|
|
4
|
+
implement DriverProtocol correctly enough for sim-cli to use it?". It
|
|
5
|
+
catches mistakes that the structural ``isinstance(d, DriverProtocol)``
|
|
6
|
+
runtime check misses — things like methods that exist but have the wrong
|
|
7
|
+
return type, missing attributes, or a ``detect_installed`` that imports
|
|
8
|
+
the SDK at attribute-access time.
|
|
9
|
+
|
|
10
|
+
Plugin authors call :func:`assert_protocol_conformance` from a single test
|
|
11
|
+
function and get the whole battery for free. The check returns structured
|
|
12
|
+
failures via :class:`ConformanceFailure` so the test runner shows useful
|
|
13
|
+
diagnostics rather than ``AssertionError``.
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import inspect
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from sim.driver import (
|
|
23
|
+
ConnectionInfo,
|
|
24
|
+
DriverProtocol,
|
|
25
|
+
LintResult,
|
|
26
|
+
RunResult,
|
|
27
|
+
SolverInstall,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class ConformanceFailure(AssertionError):
|
|
33
|
+
"""Raised when a driver class fails conformance.
|
|
34
|
+
|
|
35
|
+
Subclassing AssertionError so pytest renders it nicely without the
|
|
36
|
+
test author needing to wrap calls in ``pytest.raises``. NOT frozen:
|
|
37
|
+
Python's exception machinery mutates ``__traceback__`` on the way up.
|
|
38
|
+
"""
|
|
39
|
+
label: str
|
|
40
|
+
message: str
|
|
41
|
+
|
|
42
|
+
def __str__(self) -> str: # pragma: no cover — formatting only
|
|
43
|
+
return f"[{self.label}] {self.message}"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# Required methods on the structural protocol. We check these by name AND
|
|
47
|
+
# by inspecting the signature (parameter count, names) so authors who alias
|
|
48
|
+
# parameters get a helpful error.
|
|
49
|
+
REQUIRED_METHODS: tuple[tuple[str, tuple[str, ...]], ...] = (
|
|
50
|
+
("detect", ("script",)),
|
|
51
|
+
("lint", ("script",)),
|
|
52
|
+
("connect", ()),
|
|
53
|
+
("parse_output", ("stdout",)),
|
|
54
|
+
("run_file", ("script",)),
|
|
55
|
+
("detect_installed", ()),
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
# Optional methods — only checked when the driver advertises supports_session.
|
|
59
|
+
OPTIONAL_SESSION_METHODS: tuple[str, ...] = ("launch", "run", "disconnect")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _instantiate(driver_class: type) -> Any:
|
|
63
|
+
"""Instantiate the driver class, surfacing the real failure cleanly."""
|
|
64
|
+
try:
|
|
65
|
+
return driver_class()
|
|
66
|
+
except TypeError as e:
|
|
67
|
+
raise ConformanceFailure(
|
|
68
|
+
"instantiation",
|
|
69
|
+
f"{driver_class.__name__}() requires arguments — drivers must "
|
|
70
|
+
f"be no-arg constructible. Original: {e}",
|
|
71
|
+
) from e
|
|
72
|
+
except Exception as e: # noqa: BLE001 — surface the original failure verbatim
|
|
73
|
+
raise ConformanceFailure(
|
|
74
|
+
"instantiation",
|
|
75
|
+
f"{driver_class.__name__}() raised at construction: {type(e).__name__}: {e}",
|
|
76
|
+
) from e
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def check_driver(driver_class: type) -> list[ConformanceFailure]:
|
|
80
|
+
"""Run every conformance check and return all failures (does not raise).
|
|
81
|
+
|
|
82
|
+
Use this when you want to produce a report; use
|
|
83
|
+
:func:`assert_protocol_conformance` when you want a single
|
|
84
|
+
pass/fail in a test.
|
|
85
|
+
"""
|
|
86
|
+
failures: list[ConformanceFailure] = []
|
|
87
|
+
|
|
88
|
+
# 1. The class can be instantiated without arguments.
|
|
89
|
+
try:
|
|
90
|
+
instance = _instantiate(driver_class)
|
|
91
|
+
except ConformanceFailure as f:
|
|
92
|
+
return [f]
|
|
93
|
+
|
|
94
|
+
# 2. ``name`` property exists and is a non-empty string.
|
|
95
|
+
name = getattr(instance, "name", None)
|
|
96
|
+
if not isinstance(name, str) or not name:
|
|
97
|
+
failures.append(ConformanceFailure(
|
|
98
|
+
"name",
|
|
99
|
+
f"driver.name must be a non-empty string, got {name!r}",
|
|
100
|
+
))
|
|
101
|
+
|
|
102
|
+
# 3. Required methods exist with sensible signatures.
|
|
103
|
+
for method_name, expected_params in REQUIRED_METHODS:
|
|
104
|
+
method = getattr(instance, method_name, None)
|
|
105
|
+
if method is None or not callable(method):
|
|
106
|
+
failures.append(ConformanceFailure(
|
|
107
|
+
f"method:{method_name}",
|
|
108
|
+
f"{method_name!r} is missing or not callable",
|
|
109
|
+
))
|
|
110
|
+
continue
|
|
111
|
+
try:
|
|
112
|
+
sig = inspect.signature(method)
|
|
113
|
+
except (TypeError, ValueError):
|
|
114
|
+
continue # builtin / C extension methods can't be introspected
|
|
115
|
+
param_names = [p.name for p in sig.parameters.values()
|
|
116
|
+
if p.kind not in (inspect.Parameter.VAR_KEYWORD,
|
|
117
|
+
inspect.Parameter.VAR_POSITIONAL)]
|
|
118
|
+
for expected in expected_params:
|
|
119
|
+
if expected not in param_names:
|
|
120
|
+
failures.append(ConformanceFailure(
|
|
121
|
+
f"method:{method_name}",
|
|
122
|
+
f"{method_name}() expected parameter {expected!r}, "
|
|
123
|
+
f"got params: {param_names}",
|
|
124
|
+
))
|
|
125
|
+
|
|
126
|
+
# 4. ``detect_installed`` returns an iterable of SolverInstall.
|
|
127
|
+
try:
|
|
128
|
+
installs = list(instance.detect_installed())
|
|
129
|
+
except Exception as e: # noqa: BLE001 — must be safe to call
|
|
130
|
+
failures.append(ConformanceFailure(
|
|
131
|
+
"detect_installed",
|
|
132
|
+
f"raised {type(e).__name__}: {e}. Must be safe to call when "
|
|
133
|
+
f"nothing is installed.",
|
|
134
|
+
))
|
|
135
|
+
else:
|
|
136
|
+
for inst in installs:
|
|
137
|
+
if not isinstance(inst, SolverInstall):
|
|
138
|
+
failures.append(ConformanceFailure(
|
|
139
|
+
"detect_installed",
|
|
140
|
+
f"returned {type(inst).__name__}; must be SolverInstall",
|
|
141
|
+
))
|
|
142
|
+
break
|
|
143
|
+
|
|
144
|
+
# 5. ``connect`` returns a ConnectionInfo (or close-enough duck).
|
|
145
|
+
try:
|
|
146
|
+
ci = instance.connect()
|
|
147
|
+
except Exception as e: # noqa: BLE001 — driver may legitimately error here
|
|
148
|
+
# We don't fail conformance — connect() is allowed to fail when the
|
|
149
|
+
# solver isn't installed. But the type when it does succeed must be
|
|
150
|
+
# ConnectionInfo. We can only skip in this case.
|
|
151
|
+
ci = None
|
|
152
|
+
if not isinstance(e, (FileNotFoundError, RuntimeError, OSError, ImportError)):
|
|
153
|
+
failures.append(ConformanceFailure(
|
|
154
|
+
"connect",
|
|
155
|
+
f"raised {type(e).__name__}: {e!s}. Failures should produce "
|
|
156
|
+
f"ConnectionInfo(status='not_installed'/'error') instead.",
|
|
157
|
+
))
|
|
158
|
+
if ci is not None and not isinstance(ci, ConnectionInfo):
|
|
159
|
+
failures.append(ConformanceFailure(
|
|
160
|
+
"connect",
|
|
161
|
+
f"returned {type(ci).__name__}; must be ConnectionInfo",
|
|
162
|
+
))
|
|
163
|
+
|
|
164
|
+
# 6. ``parse_output`` returns a dict.
|
|
165
|
+
try:
|
|
166
|
+
parsed = instance.parse_output("")
|
|
167
|
+
except Exception as e: # noqa: BLE001
|
|
168
|
+
failures.append(ConformanceFailure(
|
|
169
|
+
"parse_output",
|
|
170
|
+
f"raised on empty input: {type(e).__name__}: {e}. "
|
|
171
|
+
f"Must accept any string and return a dict.",
|
|
172
|
+
))
|
|
173
|
+
else:
|
|
174
|
+
if not isinstance(parsed, dict):
|
|
175
|
+
failures.append(ConformanceFailure(
|
|
176
|
+
"parse_output",
|
|
177
|
+
f"returned {type(parsed).__name__}; must be dict",
|
|
178
|
+
))
|
|
179
|
+
|
|
180
|
+
# 7. ``lint`` returns a LintResult on a missing path (the driver may
|
|
181
|
+
# decline to lint missing files, but it must not crash).
|
|
182
|
+
try:
|
|
183
|
+
lr = instance.lint(Path("/nonexistent/script.tmp"))
|
|
184
|
+
except Exception as e: # noqa: BLE001
|
|
185
|
+
failures.append(ConformanceFailure(
|
|
186
|
+
"lint",
|
|
187
|
+
f"raised on missing-file path: {type(e).__name__}: {e}. "
|
|
188
|
+
f"Should return LintResult(ok=True, diagnostics=[]) or similar.",
|
|
189
|
+
))
|
|
190
|
+
else:
|
|
191
|
+
if not isinstance(lr, LintResult):
|
|
192
|
+
failures.append(ConformanceFailure(
|
|
193
|
+
"lint",
|
|
194
|
+
f"returned {type(lr).__name__}; must be LintResult",
|
|
195
|
+
))
|
|
196
|
+
|
|
197
|
+
# 8. Session lifecycle (only if advertised).
|
|
198
|
+
supports_session = bool(getattr(instance, "supports_session", False))
|
|
199
|
+
if supports_session:
|
|
200
|
+
for method_name in OPTIONAL_SESSION_METHODS:
|
|
201
|
+
method = getattr(instance, method_name, None)
|
|
202
|
+
if method is None or not callable(method):
|
|
203
|
+
failures.append(ConformanceFailure(
|
|
204
|
+
f"session:{method_name}",
|
|
205
|
+
f"supports_session=True but {method_name!r} is missing",
|
|
206
|
+
))
|
|
207
|
+
|
|
208
|
+
# 9. Final structural protocol check.
|
|
209
|
+
if not isinstance(instance, DriverProtocol):
|
|
210
|
+
failures.append(ConformanceFailure(
|
|
211
|
+
"protocol",
|
|
212
|
+
f"{driver_class.__name__} instance does not match DriverProtocol "
|
|
213
|
+
f"structurally. The previous failures usually explain why.",
|
|
214
|
+
))
|
|
215
|
+
|
|
216
|
+
return failures
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def assert_protocol_conformance(driver_class: type) -> None:
|
|
220
|
+
"""Test-suite friendly wrapper around :func:`check_driver`.
|
|
221
|
+
|
|
222
|
+
Plugin authors call this from one pytest function::
|
|
223
|
+
|
|
224
|
+
from sim.testing import assert_protocol_conformance
|
|
225
|
+
from sim_plugin_<x> import <X>Driver
|
|
226
|
+
|
|
227
|
+
def test_protocol():
|
|
228
|
+
assert_protocol_conformance(<X>Driver)
|
|
229
|
+
|
|
230
|
+
Raises ConformanceFailure (an AssertionError subclass) listing every
|
|
231
|
+
failure, which pytest renders as one nicely-grouped failure.
|
|
232
|
+
"""
|
|
233
|
+
failures = check_driver(driver_class)
|
|
234
|
+
if not failures:
|
|
235
|
+
return
|
|
236
|
+
|
|
237
|
+
lines = [f"{len(failures)} conformance failure(s) in {driver_class.__name__}:"]
|
|
238
|
+
for f in failures:
|
|
239
|
+
lines.append(f" [{f.label}] {f.message}")
|
|
240
|
+
# Raise the first failure so the test framework's `__cause__` chain points
|
|
241
|
+
# at one root, but include all in the message.
|
|
242
|
+
raise ConformanceFailure(
|
|
243
|
+
label=failures[0].label,
|
|
244
|
+
message="\n".join(lines),
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _ensure_dataclass_imports_for_consumers() -> None:
|
|
249
|
+
"""No-op: ensures RunResult is reachable for type-checkers reading this module.
|
|
250
|
+
|
|
251
|
+
Plugin authors might also want to assert their driver returns RunResult
|
|
252
|
+
from run_file when given a real script — that test is plugin-specific
|
|
253
|
+
and we don't try to write it here.
|
|
254
|
+
"""
|
|
255
|
+
_ = RunResult
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
__all__ = [
|
|
259
|
+
"ConformanceFailure",
|
|
260
|
+
"assert_protocol_conformance",
|
|
261
|
+
"check_driver",
|
|
262
|
+
"REQUIRED_METHODS",
|
|
263
|
+
"OPTIONAL_SESSION_METHODS",
|
|
264
|
+
]
|