piphi-runtime-testkit-python 0.2.0__py3-none-any.whl → 0.3.1__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,334 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Callable, Mapping
4
+ from dataclasses import dataclass
5
+ import inspect
6
+ from enum import Enum
7
+ from typing import Any, Protocol
8
+
9
+ from .builders import CommandPayload
10
+ from .assertions import assert_command_replay
11
+
12
+
13
+ @dataclass(frozen=True, slots=True)
14
+ class RuntimeResponse:
15
+ status_code: int
16
+ json: Any
17
+ body: bytes
18
+ headers: Mapping[str, str]
19
+
20
+
21
+ class RuntimeTransport(Protocol):
22
+ """Transport seam shared by in-process and black-box runtime adapters."""
23
+
24
+ async def request(self, method: str, path: str, **kwargs: Any) -> RuntimeResponse: ...
25
+ async def restart(self) -> None: ...
26
+ async def close(self) -> None: ...
27
+
28
+
29
+ class HttpxRuntimeTransport:
30
+ """HTTP adapter supporting ASGI in-process and network black-box modes."""
31
+
32
+ def __init__(
33
+ self,
34
+ *,
35
+ base_url: str = "http://testserver",
36
+ app: Any = None,
37
+ app_factory: Callable[[], Any] | None = None,
38
+ restart_callback: Callable[[], Any] | None = None,
39
+ timeout: float = 5.0,
40
+ ) -> None:
41
+ self.base_url = base_url
42
+ self._app = app
43
+ self._app_factory = app_factory
44
+ self._restart_callback = restart_callback
45
+ self.timeout = timeout
46
+ self._client: Any = None
47
+ self._lifespan: Any = None
48
+
49
+ async def _get_client(self) -> Any:
50
+ if self._client is None:
51
+ try:
52
+ import httpx
53
+ except ImportError as exc: # pragma: no cover - install guidance is the behavior.
54
+ raise RuntimeError("RuntimeHarness HTTP adapters require the 'asgi' extra: pip install piphi-runtime-testkit-python[asgi]") from exc
55
+ if self._app_factory is not None:
56
+ self._app = self._app_factory()
57
+ lifespan_context = getattr(getattr(self._app, "router", None), "lifespan_context", None)
58
+ if callable(lifespan_context):
59
+ self._lifespan = lifespan_context(self._app)
60
+ await self._lifespan.__aenter__()
61
+ transport = httpx.ASGITransport(app=self._app) if self._app is not None else None
62
+ self._client = httpx.AsyncClient(
63
+ transport=transport,
64
+ base_url=self.base_url,
65
+ timeout=self.timeout,
66
+ follow_redirects=False,
67
+ )
68
+ return self._client
69
+
70
+ async def request(self, method: str, path: str, **kwargs: Any) -> RuntimeResponse:
71
+ response = await (await self._get_client()).request(method, path, **kwargs)
72
+ try:
73
+ payload = response.json()
74
+ except ValueError:
75
+ payload = None
76
+ return RuntimeResponse(
77
+ status_code=response.status_code,
78
+ json=payload,
79
+ body=response.content,
80
+ headers=dict(response.headers),
81
+ )
82
+
83
+ async def restart(self) -> None:
84
+ await self.close()
85
+ if self._restart_callback is not None:
86
+ value = self._restart_callback()
87
+ if inspect.isawaitable(value):
88
+ await value
89
+
90
+ async def close(self) -> None:
91
+ if self._client is not None:
92
+ await self._client.aclose()
93
+ self._client = None
94
+ if self._lifespan is not None:
95
+ await self._lifespan.__aexit__(None, None, None)
96
+ self._lifespan = None
97
+
98
+
99
+ class ConformanceProfile(str, Enum):
100
+ BASIC = "basic"
101
+ MONITORING = "monitoring"
102
+ ACTUATOR = "actuator"
103
+ RESTORABLE = "restorable"
104
+ SIDECAR = "sidecar"
105
+
106
+
107
+ @dataclass(frozen=True, slots=True)
108
+ class ConformanceCheck:
109
+ name: str
110
+ passed: bool
111
+ detail: str
112
+
113
+
114
+ @dataclass(frozen=True, slots=True)
115
+ class ConformanceReport:
116
+ profile: ConformanceProfile
117
+ checks: tuple[ConformanceCheck, ...]
118
+
119
+ @property
120
+ def passed(self) -> bool:
121
+ return all(check.passed for check in self.checks)
122
+
123
+ def assert_passed(self) -> None:
124
+ failures = [f"{check.name}: {check.detail}" for check in self.checks if not check.passed]
125
+ if failures:
126
+ raise AssertionError(
127
+ f"{self.profile.value} conformance failed:\n- " + "\n- ".join(failures)
128
+ )
129
+
130
+
131
+ class RuntimeHarness:
132
+ """Small scenario interface for Core/runtime conformance tests."""
133
+
134
+ def __init__(
135
+ self,
136
+ transport: RuntimeTransport,
137
+ *,
138
+ headers: Mapping[str, str] | None = None,
139
+ endpoints: Mapping[str, str] | None = None,
140
+ ) -> None:
141
+ self.transport = transport
142
+ self.headers = dict(headers or {})
143
+ self.endpoints = {
144
+ "health": "/health",
145
+ "config": "/config",
146
+ "config_sync": "/config/sync",
147
+ "entities": "/entities",
148
+ "state": "/state",
149
+ "command": "/command",
150
+ "deconfigure": "/deconfigure/{config_id}",
151
+ **dict(endpoints or {}),
152
+ }
153
+
154
+ @classmethod
155
+ def for_asgi(
156
+ cls,
157
+ app_or_factory: Any,
158
+ *,
159
+ headers: Mapping[str, str] | None = None,
160
+ endpoints: Mapping[str, str] | None = None,
161
+ ) -> RuntimeHarness:
162
+ factory = app_or_factory if callable(app_or_factory) and not hasattr(app_or_factory, "router") else None
163
+ app = None if factory is not None else app_or_factory
164
+ return cls(
165
+ HttpxRuntimeTransport(app=app, app_factory=factory),
166
+ headers=headers,
167
+ endpoints=endpoints,
168
+ )
169
+
170
+ @classmethod
171
+ def for_http(
172
+ cls,
173
+ base_url: str,
174
+ *,
175
+ headers: Mapping[str, str] | None = None,
176
+ endpoints: Mapping[str, str] | None = None,
177
+ timeout: float = 5.0,
178
+ restart: Callable[[], Any] | None = None,
179
+ ) -> RuntimeHarness:
180
+ return cls(
181
+ HttpxRuntimeTransport(
182
+ base_url=base_url,
183
+ timeout=timeout,
184
+ restart_callback=restart,
185
+ ),
186
+ headers=headers,
187
+ endpoints=endpoints,
188
+ )
189
+
190
+ async def __aenter__(self) -> RuntimeHarness:
191
+ return self
192
+
193
+ async def __aexit__(self, *_args: Any) -> None:
194
+ await self.close()
195
+
196
+ async def request(self, method: str, path: str, *, authenticated: bool = True, **kwargs: Any) -> RuntimeResponse:
197
+ headers = dict(kwargs.pop("headers", {}))
198
+ if authenticated:
199
+ headers = {**self.headers, **headers}
200
+ return await self.transport.request(method, path, headers=headers, **kwargs)
201
+
202
+ async def health(self) -> RuntimeResponse:
203
+ return await self.request("GET", self.endpoints["health"])
204
+
205
+ async def configure(self, payload: Mapping[str, Any], *, authenticated: bool = True) -> RuntimeResponse:
206
+ return await self.request("POST", self.endpoints["config"], authenticated=authenticated, json=dict(payload))
207
+
208
+ async def sync(self, snapshot: Mapping[str, Any]) -> RuntimeResponse:
209
+ return await self.request("POST", self.endpoints["config_sync"], json=dict(snapshot))
210
+
211
+ async def entities(self) -> RuntimeResponse:
212
+ return await self.request("GET", self.endpoints["entities"])
213
+
214
+ async def state(self, *, refresh: bool = False, request_id: str | None = None) -> RuntimeResponse:
215
+ params: dict[str, Any] = {"refresh": "true"} if refresh else {}
216
+ if request_id:
217
+ params["refresh_request_id"] = request_id
218
+ return await self.request("GET", self.endpoints["state"], params=params)
219
+
220
+ async def command(self, payload: CommandPayload | Mapping[str, Any]) -> RuntimeResponse:
221
+ if isinstance(payload, CommandPayload):
222
+ return await self.request("POST", self.endpoints["command"], json=payload.json, headers=payload.headers)
223
+ return await self.request("POST", self.endpoints["command"], json=dict(payload))
224
+
225
+ async def command_replay(self, payload: CommandPayload | Mapping[str, Any]) -> tuple[RuntimeResponse, RuntimeResponse]:
226
+ """Dispatch the exact same command twice and require explicit replay evidence."""
227
+
228
+ first = await self.command(payload)
229
+ replay = await self.command(payload)
230
+ assert_command_replay(first.json, replay.json)
231
+ return first, replay
232
+
233
+ async def command_restart_replay(
234
+ self,
235
+ payload: CommandPayload | Mapping[str, Any],
236
+ ) -> tuple[RuntimeResponse, RuntimeResponse]:
237
+ """Require a command ledger to survive a runtime restart."""
238
+
239
+ first = await self.command(payload)
240
+ await self.restart()
241
+ replay = await self.command(payload)
242
+ assert_command_replay(first.json, replay.json)
243
+ return first, replay
244
+
245
+ async def assert_command_rejected(
246
+ self,
247
+ payload: CommandPayload | Mapping[str, Any],
248
+ *,
249
+ status_codes: set[int] | frozenset[int] = frozenset({400, 404, 409, 422}),
250
+ ) -> RuntimeResponse:
251
+ """Exercise wrong-target, wrong-capability, or unsupported-command cases."""
252
+
253
+ response = await self.command(payload)
254
+ if response.status_code not in status_codes:
255
+ raise AssertionError(
256
+ f"Expected command rejection HTTP {sorted(status_codes)!r}, but received HTTP {response.status_code}: {response.json!r}."
257
+ )
258
+ return response
259
+
260
+ async def deconfigure(self, config_id: str) -> RuntimeResponse:
261
+ path = self.endpoints["deconfigure"]
262
+ if "{config_id}" in path:
263
+ return await self.request("POST", path.format(config_id=config_id))
264
+ return await self.request("POST", path, json={"config_id": config_id})
265
+
266
+ async def restart(self) -> None:
267
+ await self.transport.restart()
268
+
269
+ async def close(self) -> None:
270
+ await self.transport.close()
271
+
272
+ async def run_profile(
273
+ self,
274
+ profile: ConformanceProfile | str,
275
+ *,
276
+ config: Mapping[str, Any] | None = None,
277
+ snapshot: Mapping[str, Any] | None = None,
278
+ command: CommandPayload | Mapping[str, Any] | None = None,
279
+ ) -> ConformanceReport:
280
+ selected = ConformanceProfile(profile)
281
+ checks: list[ConformanceCheck] = []
282
+
283
+ async def check(name: str, operation: Any, expected: set[int] = {200}) -> RuntimeResponse:
284
+ try:
285
+ response = await operation
286
+ passed = response.status_code in expected
287
+ detail = "passed" if passed else f"HTTP {response.status_code}: {response.json!r}"
288
+ except Exception as exc: # noqa: BLE001 - profile aggregates readable diagnostics.
289
+ response = RuntimeResponse(0, None, b"", {})
290
+ passed = False
291
+ detail = f"{type(exc).__name__}: {exc}"
292
+ checks.append(ConformanceCheck(name, passed, detail))
293
+ return response
294
+
295
+ await check("health", self.health())
296
+ if selected is ConformanceProfile.SIDECAR:
297
+ return ConformanceReport(selected, tuple(checks))
298
+ if config is None:
299
+ checks.append(ConformanceCheck("config", False, "profile requires a config payload"))
300
+ return ConformanceReport(selected, tuple(checks))
301
+ await check("auth", self.configure(config, authenticated=False), {401, 403})
302
+ configured = await check("config", self.configure(config))
303
+ await check("entities", self.entities())
304
+ if selected in {ConformanceProfile.MONITORING, ConformanceProfile.ACTUATOR, ConformanceProfile.RESTORABLE}:
305
+ await check("state", self.state())
306
+ if selected is ConformanceProfile.ACTUATOR:
307
+ if command is None:
308
+ checks.append(ConformanceCheck("command", False, "actuator profile requires a command payload"))
309
+ else:
310
+ await check("command", self.command(command))
311
+ if selected is ConformanceProfile.RESTORABLE:
312
+ if snapshot is None:
313
+ checks.append(ConformanceCheck("config_sync", False, "restorable profile requires a snapshot"))
314
+ else:
315
+ await check("config_sync", self.sync(snapshot))
316
+ await self.restart()
317
+ await check("restart_health", self.health())
318
+ restarted_entities = await check("restart_entities", self.entities())
319
+ config_id = str(config.get("config_id") or config.get("id") or "")
320
+ restarted_ids = {
321
+ str(item.get("config_id") or item.get("configId") or "")
322
+ for item in (restarted_entities.json or {}).get("entities", [])
323
+ if isinstance(item, Mapping)
324
+ }
325
+ if restarted_entities.status_code == 200 and config_id not in restarted_ids:
326
+ checks.append(ConformanceCheck(
327
+ "restart_rehydration",
328
+ False,
329
+ f"config {config_id!r} was absent after restart",
330
+ ))
331
+ config_id = str(config.get("config_id") or config.get("id") or "")
332
+ if configured.status_code == 200 and config_id:
333
+ await check("deconfigure", self.deconfigure(config_id))
334
+ return ConformanceReport(selected, tuple(checks))