Repository navigation
Expand file tree
/
Copy pathtest_installed_parity.py
More file actions
227 lines (197 loc) · 8.21 KB
/
Copy pathtest_installed_parity.py
File metadata and controls
227 lines (197 loc) · 8.21 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
"""One small workflow through every door of the installed wheel, and the answers compared.
`tests/surfaces/` proves the four surfaces agree in the source tree; this proves the
same of the artifact a user installs. Each surface creates a project, ingests the same
folder (two distinct images, a byte-identical copy and a file that is not an image) and
reads the batch back. What is compared is what a client branches on: the content hashes
of the assets, which files failed and why, and the code of one shared refusal, ingesting
into a project that does not exist.
An operation a surface does not offer is skipped for that surface, never invented: see
`NOT_OFFERED` in `tests/surfaces/test_cross_surface_parity.py`. Every verb used here is
offered by all four.
"""
from __future__ import annotations
import json
import subprocess
import time
from pathlib import Path
from typing import Any
from uuid import uuid4
import httpx
from tests.packaging._wheel import clean_env, console_script, interpreter, wheel_path
from tests.packaging.test_installed_conformance import _mcp_env, _Stdio
from tests.packaging.test_wheel import _free_port, _serving
from tests.surfaces._world import PROJECT, write_folder
wheel_path()
Outcome = dict[str, Any]
UNKNOWN_PROJECT = "no-such-project"
SDK_SCRIPT = """
import json, sys
from pathlib import Path
from uuid import uuid4
from visionset.kernel.error_codes import error_code
from visionset.kernel.services import (
BatchService, IngestService, ProjectService, SourceService, WorkspaceService,
)
root, folder, project = sys.argv[1], Path(sys.argv[2]), sys.argv[3]
with WorkspaceService.init(root) as ws:
created = ProjectService(ws).create(project)
source = SourceService(ws).register_images(created.id, folder)
run = IngestService(ws).ingest(source.id)
assets = BatchService(ws).assets(run.batch_id)
try:
SourceService(ws).register_images(uuid4(), folder)
except Exception as error:
refusal = error_code(error)
print(json.dumps({
"hashes": sorted(a.content_hash for a in assets),
"failures": sorted([f.name.split("/")[-1], f.kind.value] for f in run.failures),
"refusal": refusal,
}))
"""
def _failures(items: list[dict[str, Any]]) -> list[list[str]]:
return sorted([Path(item["name"]).name, item["kind"]] for item in items)
def _sdk(installed: Path, cwd: Path, root: Path, folder: Path) -> Outcome:
result = subprocess.run(
[str(interpreter(installed)), "-I", "-c", SDK_SCRIPT, str(root), str(folder), PROJECT],
cwd=cwd,
env=clean_env(),
capture_output=True,
text=True,
check=False,
)
assert result.returncode == 0, result.stderr
return dict(json.loads(result.stdout))
def _cli_run(installed: Path, cwd: Path, *argv: str) -> tuple[int, Any]:
result = subprocess.run(
[str(console_script(installed)), *argv, "--json"],
cwd=cwd,
env=clean_env(),
capture_output=True,
text=True,
check=False,
)
return result.returncode, json.loads(result.stdout)
def _cli(installed: Path, cwd: Path, workspace: Path, folder: Path) -> Outcome:
def run(*argv: str) -> Any:
code, body = _cli_run(installed, cwd, *argv, "--workspace", str(workspace))
assert code == 0, body
return body
run("project", "create", PROJECT)
ingested = run("ingest", str(folder), "--project", PROJECT)
assets = run("batch", "assets", ingested["batch_id"])["items"]
code, refused = _cli_run(
installed,
cwd,
"ingest",
str(folder),
"--project",
UNKNOWN_PROJECT,
"--workspace",
str(workspace),
)
assert code == 1, refused
return {
"hashes": sorted(asset["content_hash"] for asset in assets),
"failures": _failures(ingested["failures"]),
"refusal": refused["error"]["code"],
}
def _mcp(installed: Path, cwd: Path, workspace: Path, folder: Path) -> Outcome:
client = _Stdio(
[str(console_script(installed)), "mcp", "--workspace", str(workspace)],
cwd=cwd,
env=_mcp_env(),
)
def call(tool: str, **arguments: Any) -> Any:
result = client.request("tools/call", {"name": tool, "arguments": arguments})
assert not result.get("isError"), result
return result["structuredContent"]
try:
client.request(
"initialize",
{
"protocolVersion": "2025-06-18",
"capabilities": {},
"clientInfo": {"name": "visionset-packaging-tests", "version": "0"},
},
)
client.notify("notifications/initialized")
call("create_project", name=PROJECT)
ingested = call("ingest", project=PROJECT, path=str(folder))
assets = call("list_batch_assets", batch_id=ingested["batch_id"])["items"]
refused = call("ingest", project=UNKNOWN_PROJECT, path=str(folder))
finally:
assert client.close() == 0, client.stderr
return {
"hashes": sorted(asset["content_hash"] for asset in assets),
"failures": _failures(ingested["failures"]),
"refusal": refused["error"]["code"],
}
def issue_token(installed: Path, cwd: Path, workspace: Path, name: str = "parity") -> str:
result = subprocess.run(
[str(console_script(installed)), "token", "create", "--name", name, "--workspace"]
+ [str(workspace)],
cwd=cwd,
env=clean_env(),
capture_output=True,
text=True,
check=False,
)
assert result.returncode == 0, result.stderr
return result.stdout.strip()
def _rest(installed: Path, cwd: Path, workspace: Path, folder: Path) -> Outcome:
headers = {"Authorization": f"Bearer {issue_token(installed, cwd, workspace)}"}
parts = [
("files", (path.name, path.read_bytes(), "application/octet-stream"))
for path in sorted(folder.iterdir())
]
with (
_serving(installed, workspace, _free_port(), cwd) as base,
httpx.Client(base_url=base, headers=headers, timeout=30) as client,
):
project = client.post("/projects", json={"name": PROJECT})
assert project.status_code == 201, project.text
source = client.post(f"/projects/{project.json()['id']}/sources/images", files=parts)
assert source.status_code == 201, source.text
launched = client.post(f"/sources/{source.json()['id']}/ingest-jobs", json={})
assert launched.status_code == 202, launched.text
deadline = time.monotonic() + 60
while True:
job = client.get(f"/ingest-jobs/{launched.json()['id']}").json()
if job["state"] not in {"pending", "queued", "running"}:
break
assert time.monotonic() < deadline, job
time.sleep(0.2)
assert job["state"] == "completed", job
assets = client.get(f"/batches/{job['batch_id']}/assets").json()["items"]
refused = client.post(f"/projects/{uuid4()}/sources/images", files=parts)
assert refused.status_code == 404, refused.text
return {
"hashes": sorted(asset["content_hash"] for asset in assets),
"failures": _failures(job["failures"]),
"refusal": refused.json()["code"],
}
def test_the_installed_wheel_answers_the_same_on_every_surface(
installed: Path, foreign_cwd: Path, tmp_path: Path
) -> None:
folder = write_folder(tmp_path / "drop", "mixed")
results: dict[str, Outcome] = {}
for name, drive in {"cli": _cli, "mcp": _mcp, "rest": _rest}.items():
workspace = tmp_path / f"ws-{name}"
init = subprocess.run(
[str(console_script(installed)), "init", str(workspace)],
cwd=foreign_cwd,
env=clean_env(),
capture_output=True,
text=True,
check=False,
)
assert init.returncode == 0, init.stderr
results[name] = drive(installed, foreign_cwd, workspace, folder)
results["sdk"] = _sdk(installed, foreign_cwd, tmp_path / "ws-sdk", folder)
expected = results["sdk"]
assert len(expected["hashes"]) == 2
assert expected["failures"] == [["notes.txt", "unsupported"]]
assert expected["refusal"] == "PROJECT_NOT_FOUND"
for name, outcome in results.items():
assert outcome == expected, name
assert list(foreign_cwd.iterdir()) == []