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.
- piphi_runtime_testkit_python/__init__.py +50 -0
- piphi_runtime_testkit_python/assertions.py +231 -1
- piphi_runtime_testkit_python/behavior_contract.py +4 -0
- piphi_runtime_testkit_python/builders.py +56 -0
- piphi_runtime_testkit_python/cross_contract.py +78 -0
- piphi_runtime_testkit_python/harness.py +334 -0
- piphi_runtime_testkit_python/mock_core.py +253 -66
- piphi_runtime_testkit_python/waits.py +83 -0
- {piphi_runtime_testkit_python-0.2.0.dist-info → piphi_runtime_testkit_python-0.3.1.dist-info}/METADATA +106 -5
- piphi_runtime_testkit_python-0.3.1.dist-info/RECORD +15 -0
- piphi_runtime_testkit_python-0.2.0.dist-info/RECORD +0 -12
- {piphi_runtime_testkit_python-0.2.0.dist-info → piphi_runtime_testkit_python-0.3.1.dist-info}/WHEEL +0 -0
- {piphi_runtime_testkit_python-0.2.0.dist-info → piphi_runtime_testkit_python-0.3.1.dist-info}/entry_points.txt +0 -0
- {piphi_runtime_testkit_python-0.2.0.dist-info → piphi_runtime_testkit_python-0.3.1.dist-info}/licenses/LICENSE +0 -0
|
@@ -1,12 +1,21 @@
|
|
|
1
1
|
"""Pytest-first helpers for testing PiPhi runtime integrations."""
|
|
2
2
|
|
|
3
3
|
from .assertions import (
|
|
4
|
+
assert_command_failure,
|
|
5
|
+
assert_command_replay,
|
|
6
|
+
assert_command_success,
|
|
7
|
+
assert_config_sync_response,
|
|
8
|
+
assert_event_payload,
|
|
4
9
|
assert_entities_response,
|
|
10
|
+
assert_onboarding_declaration,
|
|
5
11
|
assert_event_sent,
|
|
6
12
|
assert_state_refresh_response,
|
|
7
13
|
assert_telemetry_sent,
|
|
14
|
+
assert_telemetry_payload,
|
|
8
15
|
)
|
|
9
16
|
from .builders import (
|
|
17
|
+
CommandPayload,
|
|
18
|
+
build_command_payload,
|
|
10
19
|
build_config_payload,
|
|
11
20
|
build_config_snapshot,
|
|
12
21
|
build_core_config_row,
|
|
@@ -26,26 +35,67 @@ from .behavior_contract import (
|
|
|
26
35
|
find_behavior_telemetry_issues,
|
|
27
36
|
)
|
|
28
37
|
from .mock_core import CapturedRequest, MockCoreServer, RUNTIME_CONFIG_FETCH_PATH
|
|
38
|
+
from .cross_contract import assert_cross_contract
|
|
39
|
+
from .harness import (
|
|
40
|
+
ConformanceCheck,
|
|
41
|
+
ConformanceProfile,
|
|
42
|
+
ConformanceReport,
|
|
43
|
+
HttpxRuntimeTransport,
|
|
44
|
+
RuntimeHarness,
|
|
45
|
+
RuntimeResponse,
|
|
46
|
+
RuntimeTransport,
|
|
47
|
+
)
|
|
48
|
+
from .waits import (
|
|
49
|
+
assert_never_event,
|
|
50
|
+
assert_never_request,
|
|
51
|
+
assert_never_telemetry,
|
|
52
|
+
wait_for_event,
|
|
53
|
+
wait_for_request,
|
|
54
|
+
wait_for_telemetry,
|
|
55
|
+
)
|
|
29
56
|
|
|
30
57
|
__all__ = [
|
|
31
58
|
"CapturedRequest",
|
|
59
|
+
"CommandPayload",
|
|
60
|
+
"ConformanceCheck",
|
|
61
|
+
"ConformanceProfile",
|
|
62
|
+
"ConformanceReport",
|
|
32
63
|
"BehaviorTelemetryIssue",
|
|
33
64
|
"CAMERA_MEDIA_CONTRACT_VERSION",
|
|
34
65
|
"MockCoreServer",
|
|
66
|
+
"HttpxRuntimeTransport",
|
|
35
67
|
"RUNTIME_CONFIG_FETCH_PATH",
|
|
68
|
+
"RuntimeHarness",
|
|
69
|
+
"RuntimeResponse",
|
|
70
|
+
"RuntimeTransport",
|
|
36
71
|
"assert_entities_response",
|
|
72
|
+
"assert_command_failure",
|
|
73
|
+
"assert_command_replay",
|
|
74
|
+
"assert_command_success",
|
|
75
|
+
"assert_config_sync_response",
|
|
76
|
+
"assert_cross_contract",
|
|
77
|
+
"assert_onboarding_declaration",
|
|
37
78
|
"assert_camera_capability",
|
|
38
79
|
"assert_behavior_conditions_match_telemetry",
|
|
39
80
|
"assert_event_sent",
|
|
81
|
+
"assert_event_payload",
|
|
82
|
+
"assert_never_event",
|
|
83
|
+
"assert_never_request",
|
|
84
|
+
"assert_never_telemetry",
|
|
40
85
|
"assert_state_refresh_response",
|
|
41
86
|
"assert_telemetry_sent",
|
|
87
|
+
"assert_telemetry_payload",
|
|
42
88
|
"assert_public_camera_message_redacted",
|
|
43
89
|
"build_camera_session_offer",
|
|
44
90
|
"build_camera_sidecar_session_open",
|
|
45
91
|
"build_camera_source",
|
|
92
|
+
"build_command_payload",
|
|
46
93
|
"build_config_payload",
|
|
47
94
|
"build_config_snapshot",
|
|
48
95
|
"build_core_config_row",
|
|
49
96
|
"build_runtime_headers",
|
|
50
97
|
"find_behavior_telemetry_issues",
|
|
98
|
+
"wait_for_event",
|
|
99
|
+
"wait_for_request",
|
|
100
|
+
"wait_for_telemetry",
|
|
51
101
|
]
|
|
@@ -1,10 +1,91 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
3
|
from datetime import datetime
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
4
6
|
from typing import Any
|
|
5
7
|
|
|
6
8
|
from .mock_core import CapturedRequest, MockCoreServer
|
|
7
9
|
|
|
10
|
+
ONBOARDING_MODES = frozenset({"manual", "discovery", "account", "service", "none"})
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def assert_command_success(payload: Any, *, replayed: bool | None = None) -> dict[str, Any]:
|
|
14
|
+
"""Assert the runtime returned a successful command result envelope."""
|
|
15
|
+
|
|
16
|
+
if not isinstance(payload, dict):
|
|
17
|
+
raise AssertionError(f"Expected command result to be an object, but received {payload!r}.")
|
|
18
|
+
status = payload.get("status")
|
|
19
|
+
successful = status == "success" or payload.get("ok") is True
|
|
20
|
+
if not successful:
|
|
21
|
+
raise AssertionError(f"Expected a successful command result, but received {payload!r}.")
|
|
22
|
+
if "result" in payload and not isinstance(payload["result"], dict):
|
|
23
|
+
raise AssertionError("Expected command result.result to be an object.")
|
|
24
|
+
if replayed is not None and payload.get("replayed", False) is not replayed:
|
|
25
|
+
raise AssertionError(f"Expected command replayed={replayed!r}, but received {payload.get('replayed')!r}.")
|
|
26
|
+
return payload
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def assert_command_failure(
|
|
30
|
+
payload: Any,
|
|
31
|
+
*,
|
|
32
|
+
retryable: bool | None = None,
|
|
33
|
+
unknown_outcome: bool = False,
|
|
34
|
+
) -> dict[str, Any]:
|
|
35
|
+
"""Assert a typed command failure, optionally requiring ambiguous delivery."""
|
|
36
|
+
|
|
37
|
+
if not isinstance(payload, dict):
|
|
38
|
+
raise AssertionError(f"Expected command failure to be an object, but received {payload!r}.")
|
|
39
|
+
failed = payload.get("status") == "failed" or payload.get("ok") is False
|
|
40
|
+
if not failed:
|
|
41
|
+
raise AssertionError(f"Expected a failed command result, but received {payload!r}.")
|
|
42
|
+
if retryable is not None and payload.get("retryable", False) is not retryable:
|
|
43
|
+
raise AssertionError(f"Expected command retryable={retryable!r}, but received {payload.get('retryable')!r}.")
|
|
44
|
+
metadata = payload.get("metadata")
|
|
45
|
+
ambiguous = (
|
|
46
|
+
payload.get("confirmation_status") == "unknown"
|
|
47
|
+
or isinstance(metadata, dict) and metadata.get("delivery_status") == "ambiguous"
|
|
48
|
+
)
|
|
49
|
+
if unknown_outcome and not ambiguous:
|
|
50
|
+
raise AssertionError("Expected command failure to report an unknown outcome.")
|
|
51
|
+
return payload
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def assert_command_replay(first: Any, replay: Any) -> tuple[dict[str, Any], dict[str, Any]]:
|
|
55
|
+
"""Assert same-key replay returns the original result with explicit evidence."""
|
|
56
|
+
|
|
57
|
+
first_result = assert_command_success(first)
|
|
58
|
+
replay_result = assert_command_success(replay)
|
|
59
|
+
acknowledged = (
|
|
60
|
+
replay_result.get("replayed") is True
|
|
61
|
+
or replay_result.get("deduplicated") is True
|
|
62
|
+
or replay_result.get("status") == "replayed"
|
|
63
|
+
)
|
|
64
|
+
if not acknowledged:
|
|
65
|
+
raise AssertionError("Expected replayed command to explicitly acknowledge deduplication.")
|
|
66
|
+
if first_result.get("result", {}) != replay_result.get("result", {}):
|
|
67
|
+
raise AssertionError("Expected replayed command to return the original command result.")
|
|
68
|
+
return first_result, replay_result
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def assert_onboarding_declaration(manifest: Any) -> dict[str, str]:
|
|
72
|
+
"""Assert that a manifest uses the closed Core-owned onboarding contract."""
|
|
73
|
+
|
|
74
|
+
if not isinstance(manifest, dict):
|
|
75
|
+
raise AssertionError(f"Expected integration manifest to be an object, but received {manifest!r}.")
|
|
76
|
+
onboarding = manifest.get("onboarding")
|
|
77
|
+
if not isinstance(onboarding, dict):
|
|
78
|
+
raise AssertionError(f"Expected manifest.onboarding to be an object, but received {onboarding!r}.")
|
|
79
|
+
if set(onboarding) != {"mode"}:
|
|
80
|
+
raise AssertionError("Expected manifest.onboarding to contain only the Core-owned mode declaration.")
|
|
81
|
+
mode = onboarding.get("mode")
|
|
82
|
+
if mode not in ONBOARDING_MODES:
|
|
83
|
+
allowed = ", ".join(sorted(ONBOARDING_MODES))
|
|
84
|
+
raise AssertionError(
|
|
85
|
+
f"Expected manifest.onboarding.mode to be one of {allowed}, but received {mode!r}."
|
|
86
|
+
)
|
|
87
|
+
return onboarding
|
|
88
|
+
|
|
8
89
|
|
|
9
90
|
def _pick_alias(mapping: dict[str, Any], *names: str) -> Any:
|
|
10
91
|
for name in names:
|
|
@@ -65,6 +146,116 @@ def _assert_entity_shape(entity: Any, *, index: int) -> dict[str, Any]:
|
|
|
65
146
|
return entity
|
|
66
147
|
|
|
67
148
|
|
|
149
|
+
def _assert_timestamp(value: Any, *, label: str) -> None:
|
|
150
|
+
try:
|
|
151
|
+
parsed = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
|
|
152
|
+
except (TypeError, ValueError) as exc:
|
|
153
|
+
raise AssertionError(f"Expected {label} to be a valid ISO-8601 timestamp.") from exc
|
|
154
|
+
if parsed.tzinfo is None:
|
|
155
|
+
raise AssertionError(f"Expected {label} to include a timezone.")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _assert_runtime_auth(headers: Any) -> None:
|
|
159
|
+
if not isinstance(headers, dict):
|
|
160
|
+
raise AssertionError("Expected outbound request headers to be an object.")
|
|
161
|
+
lowered = {str(key).lower(): str(value).strip() for key, value in headers.items()}
|
|
162
|
+
for name in ("x-container-id", "x-piphi-integration-token"):
|
|
163
|
+
if not lowered.get(name):
|
|
164
|
+
raise AssertionError(f"Expected outbound request header {name} to be present and non-empty.")
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _assert_secret_canary_absent(value: Any, secret_canary: str | None) -> None:
|
|
168
|
+
if secret_canary and secret_canary in json.dumps(value, sort_keys=True, default=str):
|
|
169
|
+
raise AssertionError("Expected secret canary to be redacted from the public payload.")
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def assert_telemetry_payload(
|
|
173
|
+
payload: Any,
|
|
174
|
+
*,
|
|
175
|
+
headers: dict[str, str],
|
|
176
|
+
secret_canary: str | None = None,
|
|
177
|
+
) -> dict[str, Any]:
|
|
178
|
+
"""Assert Core's canonical outbound telemetry contract."""
|
|
179
|
+
|
|
180
|
+
if not isinstance(payload, dict):
|
|
181
|
+
raise AssertionError("Expected telemetry payload to be an object.")
|
|
182
|
+
if not isinstance(_pick_alias(payload, "device_id", "deviceId"), str):
|
|
183
|
+
raise AssertionError("Expected telemetry device_id to be a string.")
|
|
184
|
+
metrics = payload.get("metrics")
|
|
185
|
+
if not isinstance(metrics, dict) or not metrics:
|
|
186
|
+
raise AssertionError("Expected telemetry metrics to be a non-empty object.")
|
|
187
|
+
for metric, value in metrics.items():
|
|
188
|
+
if not isinstance(metric, str) or not metric.strip():
|
|
189
|
+
raise AssertionError("Expected telemetry metric names to be non-empty strings.")
|
|
190
|
+
if not isinstance(value, (bool, int, float, str)):
|
|
191
|
+
raise AssertionError(f"Expected telemetry metric {metric!r} to be scalar.")
|
|
192
|
+
if isinstance(value, float) and not math.isfinite(value):
|
|
193
|
+
raise AssertionError(f"Expected telemetry metric {metric!r} to be finite.")
|
|
194
|
+
units = payload.get("units", {})
|
|
195
|
+
if not isinstance(units, dict):
|
|
196
|
+
raise AssertionError("Expected telemetry units to be an object.")
|
|
197
|
+
unknown_units = set(units) - set(metrics)
|
|
198
|
+
if unknown_units:
|
|
199
|
+
raise AssertionError(f"Expected telemetry units to reference metrics; unknown={sorted(unknown_units)!r}.")
|
|
200
|
+
if any(not isinstance(value, str) or not value.strip() for value in units.values()):
|
|
201
|
+
raise AssertionError("Expected telemetry units to be non-empty strings.")
|
|
202
|
+
_assert_timestamp(payload.get("timestamp"), label="telemetry timestamp")
|
|
203
|
+
_assert_runtime_auth(headers)
|
|
204
|
+
_assert_secret_canary_absent(payload, secret_canary)
|
|
205
|
+
return payload
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def assert_event_payload(
|
|
209
|
+
payload: Any,
|
|
210
|
+
*,
|
|
211
|
+
headers: dict[str, str],
|
|
212
|
+
secret_canary: str | None = None,
|
|
213
|
+
) -> dict[str, Any]:
|
|
214
|
+
"""Assert Core's canonical outbound event contract."""
|
|
215
|
+
|
|
216
|
+
if not isinstance(payload, dict):
|
|
217
|
+
raise AssertionError("Expected event payload to be an object.")
|
|
218
|
+
for field in ("event_id", "type"):
|
|
219
|
+
if not isinstance(payload.get(field), str) or not payload[field].strip():
|
|
220
|
+
raise AssertionError(f"Expected event {field} to be a non-empty string.")
|
|
221
|
+
_assert_timestamp(payload.get("ts"), label="event ts")
|
|
222
|
+
if payload.get("severity", "info") not in {"info", "warning", "error", "critical"}:
|
|
223
|
+
raise AssertionError("Expected event severity to be info, warning, error, or critical.")
|
|
224
|
+
if payload.get("transport", "rest") not in {"rest", "mqtt"}:
|
|
225
|
+
raise AssertionError("Expected event transport to be rest or mqtt.")
|
|
226
|
+
if not isinstance(payload.get("data", {}), dict):
|
|
227
|
+
raise AssertionError("Expected event data to be an object.")
|
|
228
|
+
_assert_runtime_auth(headers)
|
|
229
|
+
_assert_secret_canary_absent(payload, secret_canary)
|
|
230
|
+
return payload
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def assert_config_sync_response(
|
|
234
|
+
payload: Any,
|
|
235
|
+
*,
|
|
236
|
+
generation: int,
|
|
237
|
+
active_config_ids: set[str] | None = None,
|
|
238
|
+
removed_config_ids: set[str] | None = None,
|
|
239
|
+
) -> dict[str, Any]:
|
|
240
|
+
"""Assert an accepted config snapshot echoes generation and reconciliation."""
|
|
241
|
+
|
|
242
|
+
if not isinstance(payload, dict):
|
|
243
|
+
raise AssertionError("Expected config-sync response to be an object.")
|
|
244
|
+
if payload.get("status") not in {"synced", "stale_ignored"}:
|
|
245
|
+
raise AssertionError(f"Expected config-sync status to be synced or stale_ignored, but received {payload.get('status')!r}.")
|
|
246
|
+
if payload.get("generation") != generation:
|
|
247
|
+
raise AssertionError(f"Expected config-sync generation {generation}, but received {payload.get('generation')!r}.")
|
|
248
|
+
if active_config_ids is not None and set(payload.get("active_config_ids", [])) != active_config_ids:
|
|
249
|
+
raise AssertionError(
|
|
250
|
+
f"Expected active config ids {sorted(active_config_ids)!r}, but received {payload.get('active_config_ids')!r}."
|
|
251
|
+
)
|
|
252
|
+
if removed_config_ids is not None and set(payload.get("removed", [])) != removed_config_ids:
|
|
253
|
+
raise AssertionError(
|
|
254
|
+
f"Expected removed config ids {sorted(removed_config_ids)!r}, but received {payload.get('removed')!r}."
|
|
255
|
+
)
|
|
256
|
+
return payload
|
|
257
|
+
|
|
258
|
+
|
|
68
259
|
def _find_request(
|
|
69
260
|
requests: list[CapturedRequest],
|
|
70
261
|
*,
|
|
@@ -145,7 +336,12 @@ def assert_event_sent(
|
|
|
145
336
|
return request
|
|
146
337
|
|
|
147
338
|
|
|
148
|
-
def assert_entities_response(
|
|
339
|
+
def assert_entities_response(
|
|
340
|
+
payload: Any,
|
|
341
|
+
*,
|
|
342
|
+
strict: bool = False,
|
|
343
|
+
expected_config_ids: set[str] | None = None,
|
|
344
|
+
) -> dict[str, Any]:
|
|
149
345
|
"""Assert that a runtime /entities payload matches the PiPhi contract."""
|
|
150
346
|
|
|
151
347
|
if not isinstance(payload, dict):
|
|
@@ -166,6 +362,40 @@ def assert_entities_response(payload: Any) -> dict[str, Any]:
|
|
|
166
362
|
if commands is not None and not isinstance(commands, dict):
|
|
167
363
|
raise AssertionError(f"Expected /entities payload commands to be an object, but received {commands!r}.")
|
|
168
364
|
|
|
365
|
+
if strict:
|
|
366
|
+
capability_ids = set(capabilities or {})
|
|
367
|
+
command_ids = set(commands or {})
|
|
368
|
+
entity_ids: set[str] = set()
|
|
369
|
+
for index, entity in enumerate(entities):
|
|
370
|
+
entity_id = entity["id"]
|
|
371
|
+
if entity_id in entity_ids:
|
|
372
|
+
raise AssertionError(f"Expected unique entity ids, but found duplicate entity id {entity_id!r}.")
|
|
373
|
+
entity_ids.add(entity_id)
|
|
374
|
+
for capability_id in entity["capabilities"]:
|
|
375
|
+
if capability_id not in capability_ids:
|
|
376
|
+
raise AssertionError(
|
|
377
|
+
f"Expected entities[{index}] not to reference unknown capability {capability_id!r}."
|
|
378
|
+
)
|
|
379
|
+
config_id = _pick_alias(entity, "config_id", "configId")
|
|
380
|
+
if expected_config_ids is not None and config_id not in expected_config_ids:
|
|
381
|
+
raise AssertionError(
|
|
382
|
+
f"Expected entities[{index}] to be owned by one of {sorted(expected_config_ids)!r}, but received {config_id!r}."
|
|
383
|
+
)
|
|
384
|
+
available = _pick_alias(
|
|
385
|
+
entity,
|
|
386
|
+
"available_commands",
|
|
387
|
+
"availableCommands",
|
|
388
|
+
"supported_commands",
|
|
389
|
+
"supportedCommands",
|
|
390
|
+
) or []
|
|
391
|
+
if not isinstance(available, list):
|
|
392
|
+
raise AssertionError(f"Expected entities[{index}].available_commands to be a list.")
|
|
393
|
+
for command in available:
|
|
394
|
+
command_id = command if isinstance(command, str) else command.get("id") if isinstance(command, dict) else None
|
|
395
|
+
if not command_id or command_id not in command_ids:
|
|
396
|
+
raise AssertionError(
|
|
397
|
+
f"Expected entities[{index}] to reference a known command, but {command_id!r} is unknown."
|
|
398
|
+
)
|
|
169
399
|
return payload
|
|
170
400
|
|
|
171
401
|
|
|
@@ -162,6 +162,10 @@ def _condition_leaves(node: Any) -> Iterable[Mapping[str, Any]]:
|
|
|
162
162
|
for child in children:
|
|
163
163
|
yield from _condition_leaves(child)
|
|
164
164
|
return
|
|
165
|
+
if current.get("op") in {"and", "or"} and not any(
|
|
166
|
+
key in current for key in ("id", "field", "sourceRef", "source_ref")
|
|
167
|
+
):
|
|
168
|
+
return
|
|
165
169
|
yield current
|
|
166
170
|
|
|
167
171
|
|
|
@@ -1,6 +1,16 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
|
+
from dataclasses import dataclass
|
|
3
4
|
from typing import Any
|
|
5
|
+
from uuid import uuid4
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True, slots=True)
|
|
9
|
+
class CommandPayload:
|
|
10
|
+
"""Canonical command request body and matching transport headers."""
|
|
11
|
+
|
|
12
|
+
json: dict[str, Any]
|
|
13
|
+
headers: dict[str, str]
|
|
4
14
|
|
|
5
15
|
|
|
6
16
|
def build_runtime_headers(
|
|
@@ -20,6 +30,52 @@ def build_runtime_headers(
|
|
|
20
30
|
return headers
|
|
21
31
|
|
|
22
32
|
|
|
33
|
+
def build_command_payload(
|
|
34
|
+
*,
|
|
35
|
+
command: str,
|
|
36
|
+
config_id: str | None = None,
|
|
37
|
+
device_id: str | None = None,
|
|
38
|
+
entity_id: str | None = None,
|
|
39
|
+
capability_id: str | None = None,
|
|
40
|
+
args: dict[str, Any] | None = None,
|
|
41
|
+
command_id: str | None = None,
|
|
42
|
+
correlation_id: str | None = None,
|
|
43
|
+
idempotency_key: str | None = None,
|
|
44
|
+
contract_version: str = "automation.runtime.command.v1",
|
|
45
|
+
) -> CommandPayload:
|
|
46
|
+
"""Build Core's canonical runtime command body and identity headers."""
|
|
47
|
+
|
|
48
|
+
normalized_command = str(command or "").strip()
|
|
49
|
+
if not normalized_command:
|
|
50
|
+
raise ValueError("command cannot be empty")
|
|
51
|
+
resolved_command_id = str(command_id or uuid4().hex)
|
|
52
|
+
resolved_correlation_id = str(correlation_id or resolved_command_id)
|
|
53
|
+
resolved_idempotency_key = str(idempotency_key or resolved_command_id)
|
|
54
|
+
command_args = dict(args or {})
|
|
55
|
+
payload = {
|
|
56
|
+
"contract_version": contract_version,
|
|
57
|
+
"command_id": resolved_command_id,
|
|
58
|
+
"correlation_id": resolved_correlation_id,
|
|
59
|
+
"idempotency_key": resolved_idempotency_key,
|
|
60
|
+
"command": normalized_command,
|
|
61
|
+
"capability_id": capability_id,
|
|
62
|
+
"config_id": config_id,
|
|
63
|
+
"device_id": device_id,
|
|
64
|
+
"entity_id": entity_id,
|
|
65
|
+
"args": command_args,
|
|
66
|
+
"params": dict(command_args),
|
|
67
|
+
"target": {"config_id": config_id, "device_id": device_id},
|
|
68
|
+
}
|
|
69
|
+
return CommandPayload(
|
|
70
|
+
json=payload,
|
|
71
|
+
headers={
|
|
72
|
+
"X-PiPhi-Command-Id": resolved_command_id,
|
|
73
|
+
"X-PiPhi-Correlation-Id": resolved_correlation_id,
|
|
74
|
+
"X-PiPhi-Idempotency-Key": resolved_idempotency_key,
|
|
75
|
+
},
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
|
|
23
79
|
def build_config_payload(
|
|
24
80
|
*,
|
|
25
81
|
config_id: str = "config-1",
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping, Set
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from .assertions import assert_entities_response
|
|
7
|
+
from .behavior_contract import assert_behavior_conditions_match_telemetry
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _mapping_keys(value: Any) -> set[str]:
|
|
11
|
+
return {str(key) for key in value} if isinstance(value, Mapping) else set()
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def assert_cross_contract(
|
|
15
|
+
*,
|
|
16
|
+
manifest: Mapping[str, Any],
|
|
17
|
+
runtime_entities: Mapping[str, Any],
|
|
18
|
+
behaviors: Mapping[str, Any],
|
|
19
|
+
exercised_commands: Set[str],
|
|
20
|
+
captured_event_types: Set[str],
|
|
21
|
+
telemetry_samples: list[Mapping[str, Any]] | None = None,
|
|
22
|
+
dynamic_condition_ids: Set[str] = frozenset(),
|
|
23
|
+
) -> None:
|
|
24
|
+
"""Check manifest, runtime, behaviors, and observed execution as one contract."""
|
|
25
|
+
|
|
26
|
+
assert_entities_response(runtime_entities, strict=True)
|
|
27
|
+
manifest_capabilities = _mapping_keys(manifest.get("capabilities"))
|
|
28
|
+
manifest_commands = _mapping_keys(manifest.get("commands"))
|
|
29
|
+
runtime_capabilities = _mapping_keys(runtime_entities.get("capabilities"))
|
|
30
|
+
runtime_commands = _mapping_keys(runtime_entities.get("commands"))
|
|
31
|
+
issues: list[str] = []
|
|
32
|
+
if manifest_capabilities != runtime_capabilities:
|
|
33
|
+
issues.append(
|
|
34
|
+
"manifest/runtime capabilities differ: "
|
|
35
|
+
f"manifest={sorted(manifest_capabilities)!r} runtime={sorted(runtime_capabilities)!r}"
|
|
36
|
+
)
|
|
37
|
+
if manifest_commands != runtime_commands:
|
|
38
|
+
issues.append(
|
|
39
|
+
"manifest/runtime commands differ: "
|
|
40
|
+
f"manifest={sorted(manifest_commands)!r} runtime={sorted(runtime_commands)!r}"
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
for device in behaviors.get("devices", []):
|
|
44
|
+
if not isinstance(device, Mapping):
|
|
45
|
+
continue
|
|
46
|
+
for capability in device.get("capabilities", []):
|
|
47
|
+
if capability not in runtime_capabilities:
|
|
48
|
+
issues.append(f"behavior references unknown capability {capability!r}")
|
|
49
|
+
for action in device.get("actions", []):
|
|
50
|
+
runtime = action.get("runtime", {}) if isinstance(action, Mapping) else {}
|
|
51
|
+
command = str(runtime.get("command") or "") if isinstance(runtime, Mapping) else ""
|
|
52
|
+
if command not in runtime_commands:
|
|
53
|
+
issues.append(f"behavior action references unknown command {command!r}")
|
|
54
|
+
elif command not in exercised_commands:
|
|
55
|
+
issues.append(f"advertised action {command!r} was not exercised")
|
|
56
|
+
for trigger in device.get("triggers", []):
|
|
57
|
+
runtime = trigger.get("runtime", {}) if isinstance(trigger, Mapping) else {}
|
|
58
|
+
event_type = str(runtime.get("event") or "") if isinstance(runtime, Mapping) else ""
|
|
59
|
+
if event_type and event_type not in captured_event_types:
|
|
60
|
+
issues.append(f"advertised trigger {event_type!r} was not captured")
|
|
61
|
+
has_conditions = any(
|
|
62
|
+
isinstance(device, Mapping) and bool(device.get("conditions"))
|
|
63
|
+
for device in behaviors.get("devices", [])
|
|
64
|
+
)
|
|
65
|
+
if has_conditions:
|
|
66
|
+
if telemetry_samples is None:
|
|
67
|
+
issues.append("behavior conditions were advertised but no telemetry samples were supplied")
|
|
68
|
+
else:
|
|
69
|
+
try:
|
|
70
|
+
assert_behavior_conditions_match_telemetry(
|
|
71
|
+
behaviors,
|
|
72
|
+
telemetry_samples,
|
|
73
|
+
dynamic_condition_ids=dynamic_condition_ids,
|
|
74
|
+
)
|
|
75
|
+
except AssertionError as exc:
|
|
76
|
+
issues.append(str(exc))
|
|
77
|
+
if issues:
|
|
78
|
+
raise AssertionError("Cross-contract conformance failed:\n- " + "\n- ".join(issues))
|