piphi-runtime-testkit-python 0.1.4__py3-none-any.whl → 0.3.0__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.
@@ -1,31 +1,101 @@
1
1
  """Pytest-first helpers for testing PiPhi runtime integrations."""
2
2
 
3
- from .assertions import assert_entities_response, assert_event_sent, assert_telemetry_sent
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,
9
+ assert_entities_response,
10
+ assert_onboarding_declaration,
11
+ assert_event_sent,
12
+ assert_state_refresh_response,
13
+ assert_telemetry_sent,
14
+ assert_telemetry_payload,
15
+ )
4
16
  from .builders import (
17
+ CommandPayload,
18
+ build_command_payload,
5
19
  build_config_payload,
6
20
  build_config_snapshot,
7
21
  build_core_config_row,
8
22
  build_runtime_headers,
9
23
  )
24
+ from .camera import (
25
+ CAMERA_MEDIA_CONTRACT_VERSION,
26
+ assert_camera_capability,
27
+ assert_public_camera_message_redacted,
28
+ build_camera_session_offer,
29
+ build_camera_sidecar_session_open,
30
+ build_camera_source,
31
+ )
10
32
  from .behavior_contract import (
11
33
  BehaviorTelemetryIssue,
12
34
  assert_behavior_conditions_match_telemetry,
13
35
  find_behavior_telemetry_issues,
14
36
  )
15
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
+ )
16
56
 
17
57
  __all__ = [
18
58
  "CapturedRequest",
59
+ "CommandPayload",
60
+ "ConformanceCheck",
61
+ "ConformanceProfile",
62
+ "ConformanceReport",
19
63
  "BehaviorTelemetryIssue",
64
+ "CAMERA_MEDIA_CONTRACT_VERSION",
20
65
  "MockCoreServer",
66
+ "HttpxRuntimeTransport",
21
67
  "RUNTIME_CONFIG_FETCH_PATH",
68
+ "RuntimeHarness",
69
+ "RuntimeResponse",
70
+ "RuntimeTransport",
22
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",
78
+ "assert_camera_capability",
23
79
  "assert_behavior_conditions_match_telemetry",
24
80
  "assert_event_sent",
81
+ "assert_event_payload",
82
+ "assert_never_event",
83
+ "assert_never_request",
84
+ "assert_never_telemetry",
85
+ "assert_state_refresh_response",
25
86
  "assert_telemetry_sent",
87
+ "assert_telemetry_payload",
88
+ "assert_public_camera_message_redacted",
89
+ "build_camera_session_offer",
90
+ "build_camera_sidecar_session_open",
91
+ "build_camera_source",
92
+ "build_command_payload",
26
93
  "build_config_payload",
27
94
  "build_config_snapshot",
28
95
  "build_core_config_row",
29
96
  "build_runtime_headers",
30
97
  "find_behavior_telemetry_issues",
98
+ "wait_for_event",
99
+ "wait_for_request",
100
+ "wait_for_telemetry",
31
101
  ]
@@ -1,9 +1,91 @@
1
1
  from __future__ import annotations
2
2
 
3
+ from datetime import datetime
4
+ import json
5
+ import math
3
6
  from typing import Any
4
7
 
5
8
  from .mock_core import CapturedRequest, MockCoreServer
6
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
+
7
89
 
8
90
  def _pick_alias(mapping: dict[str, Any], *names: str) -> Any:
9
91
  for name in names:
@@ -64,6 +146,116 @@ def _assert_entity_shape(entity: Any, *, index: int) -> dict[str, Any]:
64
146
  return entity
65
147
 
66
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
+
67
259
  def _find_request(
68
260
  requests: list[CapturedRequest],
69
261
  *,
@@ -144,7 +336,12 @@ def assert_event_sent(
144
336
  return request
145
337
 
146
338
 
147
- def assert_entities_response(payload: Any) -> dict[str, Any]:
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]:
148
345
  """Assert that a runtime /entities payload matches the PiPhi contract."""
149
346
 
150
347
  if not isinstance(payload, dict):
@@ -165,4 +362,73 @@ def assert_entities_response(payload: Any) -> dict[str, Any]:
165
362
  if commands is not None and not isinstance(commands, dict):
166
363
  raise AssertionError(f"Expected /entities payload commands to be an object, but received {commands!r}.")
167
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
+ )
399
+ return payload
400
+
401
+
402
+ def assert_state_refresh_response(
403
+ payload: Any,
404
+ *,
405
+ request_id: str,
406
+ ) -> dict[str, Any]:
407
+ """Assert that ``/state?refresh=true`` proves an upstream state read."""
408
+
409
+ if not isinstance(payload, dict):
410
+ raise AssertionError(
411
+ f"Expected refreshed /state payload to be an object, but received {payload!r}."
412
+ )
413
+ receipt = payload.get("refresh")
414
+ if not isinstance(receipt, dict):
415
+ raise AssertionError("Expected refreshed /state payload to include a refresh receipt.")
416
+ if receipt.get("request_id") != request_id:
417
+ raise AssertionError("Expected refresh receipt to echo the current refresh request id.")
418
+ if receipt.get("performed") is not True or receipt.get("status") != "refreshed":
419
+ raise AssertionError("Expected refresh receipt to confirm an upstream read.")
420
+ source = receipt.get("source")
421
+ if not isinstance(source, str) or not source.strip():
422
+ raise AssertionError("Expected refresh receipt to name its upstream source.")
423
+ observed_at = receipt.get("observed_at")
424
+ try:
425
+ parsed = datetime.fromisoformat(str(observed_at).replace("Z", "+00:00"))
426
+ except ValueError as exc:
427
+ raise AssertionError(
428
+ "Expected refresh receipt to include a valid observation timestamp."
429
+ ) from exc
430
+ if parsed.tzinfo is None:
431
+ raise AssertionError(
432
+ "Expected refresh observation timestamp to include a timezone."
433
+ )
168
434
  return payload
@@ -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,150 @@
1
+ """Camera-media v1 builders and conformance assertions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+ from urllib.parse import urlsplit
7
+
8
+ CAMERA_MEDIA_CONTRACT_VERSION = "camera.media.v1"
9
+ PUBLIC_CAMERA_AUDIENCES = {"browser-core"}
10
+ CAMERA_SECRET_FIELDS = {
11
+ "authorization",
12
+ "password",
13
+ "source_url",
14
+ "token",
15
+ "username",
16
+ }
17
+
18
+
19
+ def build_camera_source(
20
+ *,
21
+ camera_id: str = "camera-1",
22
+ source_url: str = "rtsp://camera.local/live",
23
+ preferred_transport: str = "tcp",
24
+ connect_timeout_seconds: int = 10,
25
+ ) -> dict[str, Any]:
26
+ """Build an internal camera source descriptor for runtime/sidecar tests."""
27
+
28
+ parsed = urlsplit(source_url)
29
+ return {
30
+ "contract_version": CAMERA_MEDIA_CONTRACT_VERSION,
31
+ "message_type": "camera.source",
32
+ "audience": "core-sidecar",
33
+ "camera_id": camera_id,
34
+ "source_url": source_url,
35
+ "source_protocol": parsed.scheme.lower(),
36
+ "preferred_transport": preferred_transport,
37
+ "connect_timeout_seconds": connect_timeout_seconds,
38
+ }
39
+
40
+
41
+ def build_camera_session_offer(
42
+ *,
43
+ sdp: str = "v=0\r\na=recvonly\r\n",
44
+ include_audio: bool = False,
45
+ ) -> dict[str, Any]:
46
+ """Build a browser-to-Core WebRTC offer."""
47
+
48
+ return {
49
+ "contract_version": CAMERA_MEDIA_CONTRACT_VERSION,
50
+ "message_type": "camera.session.offer",
51
+ "audience": "browser-core",
52
+ "type": "offer",
53
+ "sdp": sdp,
54
+ "include_audio": include_audio,
55
+ }
56
+
57
+
58
+ def build_camera_sidecar_session_open(
59
+ *,
60
+ source: dict[str, Any] | None = None,
61
+ offer: dict[str, Any] | None = None,
62
+ idle_timeout_seconds: int = 60,
63
+ ) -> dict[str, Any]:
64
+ """Build the private Core-to-sidecar session request."""
65
+
66
+ browser_offer = offer or build_camera_session_offer()
67
+ return {
68
+ "contract_version": CAMERA_MEDIA_CONTRACT_VERSION,
69
+ "message_type": "camera.sidecar.session.open",
70
+ "audience": "core-sidecar",
71
+ "source": source or build_camera_source(),
72
+ "offer": {
73
+ "type": browser_offer["type"],
74
+ "sdp": browser_offer["sdp"],
75
+ "include_audio": bool(browser_offer.get("include_audio", False)),
76
+ },
77
+ "idle_timeout_seconds": idle_timeout_seconds,
78
+ }
79
+
80
+
81
+ def _field_names(value: object) -> set[str]:
82
+ if isinstance(value, dict):
83
+ names = {str(key).lower() for key in value}
84
+ for nested in value.values():
85
+ names.update(_field_names(nested))
86
+ return names
87
+ if isinstance(value, list):
88
+ names: set[str] = set()
89
+ for nested in value:
90
+ names.update(_field_names(nested))
91
+ return names
92
+ return set()
93
+
94
+
95
+ def assert_public_camera_message_redacted(payload: Any) -> dict[str, Any]:
96
+ """Assert that a browser-facing camera message contains no source secrets."""
97
+
98
+ if not isinstance(payload, dict):
99
+ raise AssertionError( # noqa: TRY004 - assertion helper intentionally raises AssertionError
100
+ f"Expected camera message object, received {payload!r}."
101
+ )
102
+ if payload.get("contract_version") != CAMERA_MEDIA_CONTRACT_VERSION:
103
+ raise AssertionError("Expected camera.media.v1 contract_version.")
104
+ if payload.get("audience") not in PUBLIC_CAMERA_AUDIENCES:
105
+ raise AssertionError("Expected a browser-facing camera message.")
106
+ leaked = _field_names(payload) & CAMERA_SECRET_FIELDS
107
+ if leaked:
108
+ raise AssertionError(f"Browser-facing camera message leaked secret fields: {sorted(leaked)!r}.")
109
+ return payload
110
+
111
+
112
+ def assert_camera_capability(
113
+ entities_payload: Any,
114
+ *,
115
+ capability_id: str = "camera_stream",
116
+ ) -> dict[str, Any]:
117
+ """Assert that an entities response advertises a usable camera capability."""
118
+
119
+ if not isinstance(entities_payload, dict):
120
+ raise AssertionError( # noqa: TRY004 - assertion helper intentionally raises AssertionError
121
+ "Expected /entities payload to be an object."
122
+ )
123
+ capabilities = entities_payload.get("capabilities")
124
+ if not isinstance(capabilities, dict):
125
+ raise AssertionError( # noqa: TRY004 - assertion helper intentionally raises AssertionError
126
+ "Expected /entities capabilities to be an object."
127
+ )
128
+ capability = capabilities.get(capability_id)
129
+ if not isinstance(capability, dict) or capability.get("kind") != "camera":
130
+ raise AssertionError(f"Expected {capability_id!r} to be a camera capability.")
131
+ camera = capability.get("camera")
132
+ if not isinstance(camera, dict):
133
+ raise AssertionError( # noqa: TRY004 - assertion helper intentionally raises AssertionError
134
+ f"Expected {capability_id!r} to declare camera media endpoints."
135
+ )
136
+ endpoint_names = {
137
+ "gateway_source_endpoint",
138
+ "snapshot_endpoint",
139
+ "stream_endpoint",
140
+ "webrtc_endpoint",
141
+ }
142
+ if not endpoint_names.intersection(camera):
143
+ raise AssertionError(f"Expected {capability_id!r} to declare at least one media endpoint.")
144
+ entities = entities_payload.get("entities")
145
+ if not isinstance(entities, list) or not any(
146
+ isinstance(entity, dict) and capability_id in (entity.get("capabilities") or [])
147
+ for entity in entities
148
+ ):
149
+ raise AssertionError(f"Expected an entity to advertise {capability_id!r}.")
150
+ return capability