Repository navigation
Expand file tree
/
Copy pathtest_phase_j_executable.py
More file actions
397 lines (330 loc) · 14.7 KB
/
Copy pathtest_phase_j_executable.py
File metadata and controls
397 lines (330 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
"""
Tests for Phase J executable layer:
scripts/ucp_check.py — UCP profile discovery + validation
scripts/iptc_ai_label.py — IPTC DigitalSourceType audit + inject
scripts/agent_ux_check.py — agent-friendly page scorer
scripts/render_page.py — extract_accessibility extension
Tests are pure (no network, no exiftool, no Playwright). External
dependencies are either mocked or short-circuited via the public API
surface of each script.
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
from unittest import mock
import pytest
_REPO_ROOT = Path(__file__).resolve().parents[1]
_SCRIPTS = _REPO_ROOT / "scripts"
if str(_SCRIPTS) not in sys.path:
sys.path.insert(0, str(_SCRIPTS))
pytest.importorskip("requests")
import agent_ux_check # noqa: E402
import iptc_ai_label # noqa: E402
import render_page # noqa: E402
import ucp_check # noqa: E402
# ---------------------------------------------------------------------------
# ucp_check
# ---------------------------------------------------------------------------
def test_discovery_url_for_normalizes_to_well_known():
assert (
ucp_check.discovery_url_for("https://store.example.com")
== "https://store.example.com/.well-known/ucp"
)
# Bare hostname gets https:// prefixed.
assert (
ucp_check.discovery_url_for("store.example.com")
== "https://store.example.com/.well-known/ucp"
)
# Path on the input is discarded.
assert (
ucp_check.discovery_url_for("https://store.example.com/path/here")
== "https://store.example.com/.well-known/ucp"
)
def test_parse_profile_rejects_malformed_json():
report = ucp_check.parse_profile("{ not json")
assert report["valid_json"] is False
assert any("invalid-json" in issue for issue in report["issues"])
def test_parse_profile_valid_spec_profile():
"""Shape from ucp.dev (2026-08-25) and a live Shopify profile."""
payload = json.dumps({"ucp": {
"version": "2026-08-25",
"supported_versions": {"2026-04-08": "https://s.example/.well-known/ucp/2026-04-08"},
"services": {"dev.ucp.shopping": [
{"version": "2026-08-25", "spec": "https://ucp.dev/x", "transport": "mcp",
"endpoint": "https://s.example/api/ucp/mcp", "schema": "https://ucp.dev/y"}]},
"capabilities": {"dev.ucp.shopping.checkout": [
{"version": "2026-08-25", "spec": "https://ucp.dev/c", "schema": "https://ucp.dev/s"}]},
}})
report = ucp_check.parse_profile(payload)
assert report["valid_json"] is True and report["issues"] == []
assert report["version"] == "2026-08-25"
assert report["capabilities"][0]["id"] == "dev.ucp.shopping.checkout"
assert report["capabilities"][0]["issues"] == []
assert report["services"][0]["endpoint"] == "https://s.example/api/ucp/mcp"
assert report["unknown_capabilities"] == []
def test_parse_profile_flags_a_flat_non_spec_profile():
payload = json.dumps({"version": "1.0", "merchant": {"name": "X"},
"capabilities": [{"id": "dev.ucp.shopping.checkout"}]})
report = ucp_check.parse_profile(payload)
assert "missing-ucp-root" in report["issues"]
assert any(i.startswith("flat-profile") for i in report["issues"])
def test_parse_profile_flags_missing_capability_fields():
payload = json.dumps({"ucp": {"version": "2026-08-25",
"services": {"dev.ucp.shopping": [{"version": "2026-08-25", "transport": "rest"}]},
"capabilities": {"dev.ucp.shopping.cart": [{"version": "2026-08-25"}]}}})
report = ucp_check.parse_profile(payload)
assert report["capabilities"][0]["issues"] == ["missing-spec", "missing-schema"]
assert report["services"][0]["issues"] == ["missing-endpoint"]
def test_parse_profile_flags_missing_fields_and_unknown_capability():
payload = json.dumps({"ucp": {
"services": {"dev.ucp.shopping": [{"transport": "carrier-pigeon"}]},
"capabilities": {"dev.ucp.unknown.thing": [{"spec": "https://ucp.dev/x"}]},
}})
report = ucp_check.parse_profile(payload)
assert "version-missing-or-not-a-date" in report["issues"]
assert "dev.ucp.unknown.thing" in report["unknown_capabilities"]
cap0 = report["capabilities"][0]
assert "missing-version" in cap0["issues"] and "missing-schema" in cap0["issues"]
svc0 = report["services"][0]
assert "unknown-transport" in svc0["issues"] and "missing-version" in svc0["issues"]
def test_parse_profile_rejects_non_object_root():
report = ucp_check.parse_profile(json.dumps(["not", "an", "object"]))
assert "profile-not-object" in report["issues"]
def test_known_capabilities_cover_core_commerce_verbs():
# Sanity check on the documented vocabulary.
for cap in ("dev.ucp.shopping.checkout",
"dev.ucp.shopping.fulfillment",
"dev.ucp.shopping.discount"):
assert cap in ucp_check.KNOWN_CAPABILITIES
# ---------------------------------------------------------------------------
# iptc_ai_label
# ---------------------------------------------------------------------------
def test_iptc_vocab_contains_required_merchant_center_value():
# Google Merchant Center requires this exact label on AI-generated images.
assert "trainedAlgorithmicMedia" in iptc_ai_label.IPTC_VOCAB
uri = iptc_ai_label.IPTC_VOCAB["trainedAlgorithmicMedia"]
assert uri.startswith("https://cv.iptc.org/")
assert uri.endswith("/trainedAlgorithmicMedia")
def test_audit_reports_target_not_found(tmp_path):
report = iptc_ai_label.audit(tmp_path / "nope.jpg")
assert report["summary"] == {"error": "target-not-found"}
def test_audit_reports_exiftool_unavailable(tmp_path, monkeypatch):
# Create a real file so we get past the target-exists check.
img = tmp_path / "a.jpg"
img.write_bytes(b"\xff\xd8\xff\xd9") # tiny stub
monkeypatch.setattr(iptc_ai_label, "exiftool_available", lambda: False)
report = iptc_ai_label.audit(img)
assert report["summary"] == {"error": "exiftool-not-installed"}
def test_inject_rejects_unknown_source_type(tmp_path):
img = tmp_path / "a.jpg"
img.write_bytes(b"\xff\xd8\xff\xd9")
out = iptc_ai_label.inject(img, "totallyMadeUpType")
assert out["ok"] is False
assert "unknown source_type" in out["error"]
def test_inject_reports_missing_exiftool(tmp_path, monkeypatch):
img = tmp_path / "a.jpg"
img.write_bytes(b"\xff\xd8\xff\xd9")
monkeypatch.setattr(iptc_ai_label, "exiftool_available", lambda: False)
out = iptc_ai_label.inject(img, "trainedAlgorithmicMedia")
assert out["ok"] is False
assert out["error"] == "exiftool-not-installed"
def test_inject_succeeds_when_subprocess_returns_zero(tmp_path, monkeypatch):
img = tmp_path / "a.jpg"
img.write_bytes(b"\xff\xd8\xff\xd9")
monkeypatch.setattr(iptc_ai_label, "exiftool_available", lambda: True)
fake_result = mock.Mock(returncode=0, stdout="ok", stderr="")
with mock.patch.object(iptc_ai_label.subprocess, "run", return_value=fake_result):
out = iptc_ai_label.inject(img, "trainedAlgorithmicMedia")
assert out["ok"] is True
assert out["error"] is None
def test_audit_classifies_files_via_mocked_exiftool(tmp_path, monkeypatch):
# Lay out three images: one labeled correctly, one unlabeled, one with a
# different source type. Mock _read_source_type to return canned values.
for name in ("ai.jpg", "missing.jpg", "real.jpg"):
(tmp_path / name).write_bytes(b"\xff\xd8\xff\xd9")
monkeypatch.setattr(iptc_ai_label, "exiftool_available", lambda: True)
values = {
tmp_path / "ai.jpg": (
"https://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMedia"
),
tmp_path / "missing.jpg": None,
tmp_path / "real.jpg": (
"https://cv.iptc.org/newscodes/digitalsourcetype/digitalCapture"
),
}
monkeypatch.setattr(iptc_ai_label, "_read_source_type",
lambda p: values[p])
report = iptc_ai_label.audit(tmp_path)
summary = report["summary"]
assert summary["total"] == 3
assert summary["trainedAlgorithmicMedia"] == 1
assert summary["digitalCapture"] == 1
assert summary["missing"] == 1
# ---------------------------------------------------------------------------
# agent_ux_check
# ---------------------------------------------------------------------------
def test_analyze_html_counts_semantic_tags_and_widgets():
html = """
<html><body>
<nav><a href="/x">x</a></nav>
<main>
<button>Click</button>
<button>Other</button>
<div onclick="doThing()">Fake button</div>
</main>
</body></html>
"""
findings = agent_ux_check.analyze_html(html)
assert findings["real_buttons"] == 2
assert findings["real_anchors"] == 1
assert findings["div_onclick_widgets"] == 1
assert findings["semantic_landmarks"] >= 2 # nav + main
def test_analyze_html_detects_unlabeled_inputs():
html = """
<form>
<label for="email">Email</label>
<input id="email" type="email">
<input id="phone" type="tel">
</form>
"""
findings = agent_ux_check.analyze_html(html)
# phone has no <label for="phone"> — should count as unlabeled.
assert findings["inputs_without_label"] == 1
# Both inputs lack ARIA labels (one has visible label, but no aria-*).
assert findings["inputs_without_aria"] >= 1
def test_analyze_accessibility_tree_handles_none_input():
findings = agent_ux_check.analyze_accessibility_tree(None)
assert findings["tree_present"] is False
assert findings["total_nodes"] == 0
def test_agent_ux_rejects_empty_rendered_document(monkeypatch):
monkeypatch.setattr(
agent_ux_check,
"render_page",
lambda *_args, **_kwargs: {
"url": "https://empty.example/",
"status_code": 200,
"error": None,
"content": "<html><head></head><body></body></html>",
"accessibility_tree": None,
"accessibility_error": "no nodes",
"accessibility_partial": True,
},
)
report = agent_ux_check.audit("https://empty.example/")
assert report["score"] is None
assert report["score_status"] == "unavailable"
assert "no meaningful body content" in report["render_error"]
def test_agent_ux_labels_missing_accessibility_tree_as_partial(monkeypatch):
monkeypatch.setattr(
agent_ux_check,
"render_page",
lambda *_args, **_kwargs: {
"url": "https://partial.example/",
"status_code": 200,
"error": None,
"content": "<html><body><main>Useful content</main></body></html>",
"accessibility_tree": None,
"accessibility_error": "CDP unavailable",
"accessibility_partial": True,
},
)
report = agent_ux_check.audit("https://partial.example/")
assert report["score"] is not None
assert report["score_status"] == "partial"
assert report["partial"] is True
assert report["partial_reasons"] == ["CDP unavailable"]
def test_analyze_accessibility_tree_counts_roles_and_names():
tree = {
"role": "WebArea",
"name": "Example",
"children": [
{"role": "button", "name": "Submit"},
{"role": "button", "name": ""}, # unnamed interactive
{"role": "link", "name": "Home"},
{"role": "generic", "name": "", "children": [
{"role": "generic", "name": ""},
]},
],
}
findings = agent_ux_check.analyze_accessibility_tree(tree)
assert findings["tree_present"] is True
assert findings["role_button"] == 2
assert findings["role_link"] == 1
assert findings["role_generic"] == 2
assert findings["unnamed_interactive"] == 1
# WebArea + 2 buttons + 1 link + 2 generics
assert findings["total_nodes"] == 6
def test_score_clean_page_scores_high():
html_findings = {
"real_buttons": 5,
"real_anchors": 10,
"div_onclick_widgets": 0,
"semantic_landmarks": 3,
"inputs_without_aria": 0,
"inputs_without_label": 0,
}
a11y_findings = {
"tree_present": True,
"total_nodes": 50,
"interactive_nodes": 15,
"role_button": 5,
"role_link": 10,
"role_generic": 10,
"unnamed_interactive": 0,
}
scored = agent_ux_check.score(html_findings, a11y_findings)
assert scored["score"] == 100
assert scored["issues"] == []
def test_score_deducts_for_div_onclick_and_unnamed_interactives():
html_findings = {
"real_buttons": 0,
"real_anchors": 0,
"div_onclick_widgets": 3, # -> -15
"semantic_landmarks": 1,
"inputs_without_aria": 0,
"inputs_without_label": 0,
}
a11y_findings = {
"tree_present": True,
"total_nodes": 20,
"interactive_nodes": 5,
"role_button": 0,
"role_link": 0,
"role_generic": 2,
"unnamed_interactive": 2, # -> -6
}
scored = agent_ux_check.score(html_findings, a11y_findings)
assert scored["score"] < 100
assert any("div onclick" in issue for issue in scored["issues"])
assert any("accessible name" in issue for issue in scored["issues"])
# ---------------------------------------------------------------------------
# render_page extension
# ---------------------------------------------------------------------------
def test_render_page_result_dict_includes_accessibility_tree_key():
# The new key must always be present, defaulting to None when not requested,
# so downstream consumers can treat the field as optional without KeyError.
result = render_page.render_page(
"http://this-host-should-not-resolve.invalid.example/",
mode="never",
)
assert "accessibility_tree" in result
assert result["accessibility_tree"] is None
def test_render_page_accepts_extract_accessibility_kwarg():
# Pure signature check: passing extract_accessibility must not raise.
# The actual URL fails (intentional invalid host), but the kwarg must be
# accepted by the function signature even on the error path.
result = render_page.render_page(
"http://this-host-should-not-resolve.invalid.example/",
mode="never",
extract_accessibility=True,
)
assert "accessibility_tree" in result
def test_render_page_cli_exposes_a11y_tree_flag():
# Smoke check: the argparse parser knows --a11y-tree. Invoking the parser
# via render_page._cli with --help would sys.exit, so just inspect the
# source module instead.
import inspect
src = inspect.getsource(render_page._cli)
assert "--a11y-tree" in src
assert "extract_accessibility" in src