gabriel / muse public
test_mist_plugin.py python
588 lines 21.7 KB
Raw
sha256:88ac91129873e6a496e9189515aa690eb893ae25d69c8f72af141a2be5068eb3 docs: docstring sprint contract→find-symbol — idiomatic run… Sonnet 4.6 patch 140 days ago
1 """Tests for the Mist domain plugin — Phase 1.
2
3 Test tiers covered
4 ------------------
5 Tier 1 — Shape / API surface
6 MistPlugin satisfies MuseDomainPlugin; all 6 required methods present;
7 schema() returns a well-formed DomainSchema.
8
9 Tier 5 — Data integrity
10 compute_mist_id: determinism, uniqueness, length, alphabet;
11 detect_artifact_type: magic bytes, JSON key inspection, extension fallback;
12 _validate_mist_filename: accepts valid names, rejects all attack vectors;
13 extract_mist_symbol_anchors: anchors for Python source, empty for binary.
14
15 Tier 6 — Performance
16 compute_mist_id on a 1 MiB blob completes in under 100 ms.
17
18 Tier 8 — Docstring completeness
19 All public symbols in plugin.py carry a docstring.
20 """
21
22 from __future__ import annotations
23
24 import hashlib
25 import inspect
26 import pathlib
27 import sys
28 import time
29
30 import pytest
31
32 # ---------------------------------------------------------------------------
33 # Fixtures
34 # ---------------------------------------------------------------------------
35
36
37 @pytest.fixture()
38 def plugin():
39 from muse.plugins.mist.plugin import MistPlugin
40
41 return MistPlugin()
42
43
44 @pytest.fixture()
45 def empty_snap():
46 from muse.domain import SnapshotManifest
47
48 return SnapshotManifest(files={}, domain="mist", directories=[])
49
50
51 @pytest.fixture()
52 def snap_with_one(tmp_path):
53 """A SnapshotManifest containing one file keyed by its SHA-256 hex digest."""
54 content = b"hello mist"
55 digest = hashlib.sha256(content).hexdigest()
56 from muse.domain import SnapshotManifest
57
58 return SnapshotManifest(files={"aB3xQ9fWmK2r.py": digest}, domain="mist", directories=[])
59
60
61 # ---------------------------------------------------------------------------
62 # Tier 1 — Shape / API surface
63 # ---------------------------------------------------------------------------
64
65
66 class TestMistPluginShape:
67 """Verify MistPlugin satisfies the MuseDomainPlugin protocol."""
68
69 REQUIRED_METHODS = ("snapshot", "diff", "merge", "drift", "apply", "schema")
70
71 def test_all_required_methods_present(self, plugin):
72 for method in self.REQUIRED_METHODS:
73 assert hasattr(plugin, method), f"MistPlugin missing method: {method}"
74 assert callable(getattr(plugin, method))
75
76 def test_schema_returns_domain_schema(self, plugin):
77 schema = plugin.schema()
78 # DomainSchema is a TypedDict (a dict subclass) — check required keys
79 assert isinstance(schema, dict)
80 assert "domain" in schema
81 assert "description" in schema
82 assert "top_level" in schema
83 assert "dimensions" in schema
84 assert "merge_mode" in schema
85
86 def test_schema_domain_is_mist(self, plugin):
87 assert plugin.schema()["domain"] == "mist"
88
89 def test_schema_top_level_is_set(self, plugin):
90 top = plugin.schema()["top_level"]
91 # SetSchema is a TypedDict
92 assert isinstance(top, dict)
93 assert top["kind"] == "set"
94 assert top["element_type"] == "artifact"
95 assert top["identity"] == "by_content"
96
97 def test_schema_has_two_dimensions(self, plugin):
98 dims = plugin.schema()["dimensions"]
99 assert len(dims) == 2
100 names = {d["name"] for d in dims}
101 assert names == {"artifacts", "metadata"}
102
103 def test_schema_merge_mode_three_way(self, plugin):
104 assert plugin.schema()["merge_mode"] == "three_way"
105
106 def test_schema_version_is_string(self, plugin):
107 assert isinstance(plugin.schema()["schema_version"], str)
108 assert len(plugin.schema()["schema_version"]) > 0
109
110 def test_registered_in_registry(self):
111 from muse.plugins.registry import _REGISTRY
112
113 assert "mist" in _REGISTRY
114 from muse.plugins.mist.plugin import MistPlugin
115
116 assert isinstance(_REGISTRY["mist"], MistPlugin)
117
118 def test_resolve_plugin_by_domain(self):
119 from muse.plugins.registry import resolve_plugin_by_domain
120 from muse.plugins.mist.plugin import MistPlugin
121
122 plugin = resolve_plugin_by_domain("mist")
123 assert isinstance(plugin, MistPlugin)
124
125 def test_registered_domains_includes_mist(self):
126 from muse.plugins.registry import registered_domains
127
128 assert "mist" in registered_domains()
129
130
131 # ---------------------------------------------------------------------------
132 # Tier 5 — Data integrity: compute_mist_id
133 # ---------------------------------------------------------------------------
134
135
136 class TestComputeMistId:
137 """Tests for the compute_mist_id pure function."""
138
139 def test_deterministic(self):
140 from muse.plugins.mist.plugin import compute_mist_id
141
142 content = b"repeatability is key"
143 assert compute_mist_id(content) == compute_mist_id(content)
144
145 def test_length_is_12(self):
146 from muse.plugins.mist.plugin import compute_mist_id
147
148 assert len(compute_mist_id(b"")) == 12
149 assert len(compute_mist_id(b"x" * 1_000_000)) == 12
150
151 def test_only_base58_alphabet(self):
152 from muse.plugins.mist.plugin import _BASE58_ALPHABET, compute_mist_id
153
154 for content in (b"", b"a", b"\x00" * 32, b"\xff" * 32):
155 mist_id = compute_mist_id(content)
156 for ch in mist_id:
157 assert ch in _BASE58_ALPHABET, f"Unexpected char {ch!r} in mist_id {mist_id!r}"
158
159 def test_no_ambiguous_chars(self):
160 from muse.plugins.mist.plugin import compute_mist_id
161
162 ambiguous = set("0OIl")
163 for i in range(256):
164 mist_id = compute_mist_id(bytes([i]))
165 for ch in mist_id:
166 assert ch not in ambiguous, (
167 f"Ambiguous char {ch!r} found in mist_id {mist_id!r} for byte {i}"
168 )
169
170 def test_uniqueness_across_different_content(self):
171 from muse.plugins.mist.plugin import compute_mist_id
172
173 ids = {compute_mist_id(f"artifact_{i}".encode()) for i in range(200)}
174 assert len(ids) == 200, "mist IDs collided for distinct content"
175
176 def test_empty_bytes_stable_id(self):
177 """Empty content always maps to the same ID (regression guard)."""
178 from muse.plugins.mist.plugin import compute_mist_id
179
180 id1 = compute_mist_id(b"")
181 id2 = compute_mist_id(b"")
182 assert id1 == id2
183
184 def test_single_bit_change_produces_different_id(self):
185 from muse.plugins.mist.plugin import compute_mist_id
186
187 base = b"hello"
188 modified = b"hfllo"
189 assert compute_mist_id(base) != compute_mist_id(modified)
190
191
192 # ---------------------------------------------------------------------------
193 # Tier 5 — Data integrity: detect_artifact_type
194 # ---------------------------------------------------------------------------
195
196
197 class TestDetectArtifactType:
198 """Tests for the detect_artifact_type pure function."""
199
200 def test_midi_magic_bytes(self):
201 from muse.plugins.mist.plugin import detect_artifact_type
202
203 result = detect_artifact_type("track.mid", b"MThd\x00\x00\x00\x06\x00\x01")
204 assert result == {"artifact_type": "midi", "language": "midi"}
205
206 def test_midi_magic_bytes_wrong_extension(self):
207 """Magic bytes take priority over extension."""
208 from muse.plugins.mist.plugin import detect_artifact_type
209
210 result = detect_artifact_type("track.dat", b"MThd\x00\x00\x00\x06\x00\x01")
211 assert result == {"artifact_type": "midi", "language": "midi"}
212
213 def test_abi_json(self):
214 import json
215 from muse.plugins.mist.plugin import detect_artifact_type
216
217 abi = json.dumps([{"type": "function", "name": "transfer", "inputs": []}]).encode()
218 result = detect_artifact_type("contract.abi.json", abi)
219 assert result == {"artifact_type": "abi", "language": "json"}
220
221 def test_json_schema(self):
222 import json
223 from muse.plugins.mist.plugin import detect_artifact_type
224
225 schema = json.dumps({"$schema": "http://json-schema.org/draft-07/schema#"}).encode()
226 result = detect_artifact_type("schema.json", schema)
227 assert result == {"artifact_type": "json_schema", "language": "json"}
228
229 def test_python_extension(self):
230 from muse.plugins.mist.plugin import detect_artifact_type
231
232 result = detect_artifact_type("utils.py", b"def add(a, b): return a + b")
233 assert result == {"artifact_type": "code", "language": "python"}
234
235 def test_typescript_extension(self):
236 from muse.plugins.mist.plugin import detect_artifact_type
237
238 result = detect_artifact_type("app.ts", b"export function hello(): void {}")
239 assert result == {"artifact_type": "code", "language": "typescript"}
240
241 def test_markdown_extension(self):
242 from muse.plugins.mist.plugin import detect_artifact_type
243
244 result = detect_artifact_type("README.md", b"# Hello\n\nWorld")
245 assert result == {"artifact_type": "prose", "language": "markdown"}
246
247 def test_solidity_extension(self):
248 from muse.plugins.mist.plugin import detect_artifact_type
249
250 result = detect_artifact_type("Token.sol", b"// SPDX-License-Identifier: MIT")
251 assert result == {"artifact_type": "code", "language": "solidity"}
252
253 def test_unknown_extension_fallback(self):
254 from muse.plugins.mist.plugin import detect_artifact_type
255
256 result = detect_artifact_type("blob.xyzzy", b"\xde\xad\xbe\xef")
257 assert result == {"artifact_type": "unknown", "language": "binary"}
258
259 def test_returns_dict_with_required_keys(self):
260 from muse.plugins.mist.plugin import detect_artifact_type
261
262 for fname in ("a.py", "b.mid", "c.json", "d.unknown"):
263 result = detect_artifact_type(fname, b"content")
264 assert "artifact_type" in result
265 assert "language" in result
266
267
268 # ---------------------------------------------------------------------------
269 # Tier 5 — Data integrity: _validate_mist_filename
270 # ---------------------------------------------------------------------------
271
272
273 class TestValidateMistFilename:
274 """Tests for the _validate_mist_filename security gate."""
275
276 def test_valid_simple_name(self):
277 from muse.plugins.mist.plugin import _validate_mist_filename
278
279 _validate_mist_filename("aB3xQ9fWmK2r.py") # must not raise
280
281 def test_valid_name_with_dots_and_dashes(self):
282 from muse.plugins.mist.plugin import _validate_mist_filename
283
284 _validate_mist_filename("my-artifact.abi.json") # must not raise
285
286 def test_rejects_null_byte(self):
287 from muse.plugins.mist.plugin import _validate_mist_filename
288
289 with pytest.raises(ValueError, match="null byte"):
290 _validate_mist_filename("evil\x00.py")
291
292 def test_rejects_forward_slash(self):
293 from muse.plugins.mist.plugin import _validate_mist_filename
294
295 with pytest.raises(ValueError, match="path separator"):
296 _validate_mist_filename("path/traversal.py")
297
298 def test_rejects_backslash(self):
299 from muse.plugins.mist.plugin import _validate_mist_filename
300
301 with pytest.raises(ValueError, match="path separator"):
302 _validate_mist_filename("win\\traversal.py")
303
304 def test_rejects_dotdot(self):
305 from muse.plugins.mist.plugin import _validate_mist_filename
306
307 with pytest.raises(ValueError, match="path traversal"):
308 _validate_mist_filename("../evil")
309
310 def test_rejects_control_characters(self):
311 from muse.plugins.mist.plugin import _validate_mist_filename
312
313 for cp in range(0x01, 0x20):
314 with pytest.raises(ValueError, match="control char"):
315 _validate_mist_filename(f"evil{chr(cp)}.py")
316
317 def test_rejects_del_character(self):
318 from muse.plugins.mist.plugin import _validate_mist_filename
319
320 with pytest.raises(ValueError, match="control char"):
321 _validate_mist_filename("evil\x7f.py")
322
323 def test_rejects_ansi_escape(self):
324 from muse.plugins.mist.plugin import _validate_mist_filename
325
326 with pytest.raises(ValueError, match="ANSI escape"):
327 _validate_mist_filename("\x1b[31mevil\x1b[0m.py")
328
329 def test_rejects_name_exceeding_255_chars(self):
330 from muse.plugins.mist.plugin import _validate_mist_filename
331
332 with pytest.raises(ValueError, match="255"):
333 _validate_mist_filename("a" * 256)
334
335 def test_accepts_name_of_exactly_255_chars(self):
336 from muse.plugins.mist.plugin import _validate_mist_filename
337
338 _validate_mist_filename("a" * 255) # must not raise
339
340
341 # ---------------------------------------------------------------------------
342 # Tier 5 — Data integrity: extract_mist_symbol_anchors
343 # ---------------------------------------------------------------------------
344
345
346 class TestExtractMistSymbolAnchors:
347 """Tests for extract_mist_symbol_anchors."""
348
349 def test_python_function_anchor(self):
350 from muse.plugins.mist.plugin import extract_mist_symbol_anchors
351
352 source = b"def add(a, b):\n return a + b\n"
353 anchors = extract_mist_symbol_anchors("add.py", source)
354 assert any("add" in a for a in anchors), f"Expected 'add' in {anchors}"
355
356 def test_python_class_anchor(self):
357 from muse.plugins.mist.plugin import extract_mist_symbol_anchors
358
359 source = b"class Foo:\n pass\n"
360 anchors = extract_mist_symbol_anchors("foo.py", source)
361 assert any("Foo" in a for a in anchors), f"Expected 'Foo' in {anchors}"
362
363 def test_binary_returns_empty(self):
364 from muse.plugins.mist.plugin import extract_mist_symbol_anchors
365
366 binary = bytes(range(256))
367 anchors = extract_mist_symbol_anchors("blob.bin", binary)
368 assert isinstance(anchors, list)
369 # Binary may have anchors or not; it must not raise
370 # (FallbackAdapter may return empty or line-based symbols)
371
372 def test_returns_list_always(self):
373 from muse.plugins.mist.plugin import extract_mist_symbol_anchors
374
375 for fname, content in [
376 ("a.py", b"x = 1"),
377 ("b.mid", b"MThd\x00\x00"),
378 ("c.unknown", b"\xff\xfe"),
379 ]:
380 result = extract_mist_symbol_anchors(fname, content)
381 assert isinstance(result, list)
382
383 def test_no_import_pseudo_symbols(self):
384 from muse.plugins.mist.plugin import extract_mist_symbol_anchors
385
386 source = b"import os\nimport sys\ndef f(): pass\n"
387 anchors = extract_mist_symbol_anchors("f.py", source)
388 for anchor in anchors:
389 assert "::import::" not in anchor, f"Import symbol leaked: {anchor}"
390
391
392 # ---------------------------------------------------------------------------
393 # Tier 5 — Data integrity: snapshot / diff / merge / drift via in-memory paths
394 # ---------------------------------------------------------------------------
395
396
397 class TestMistPluginInMemory:
398 """Validate plugin behaviour using SnapshotManifest dicts (no filesystem)."""
399
400 def test_snapshot_passes_through_manifest(self, plugin, empty_snap):
401 result = plugin.snapshot(empty_snap)
402 assert result["domain"] == "mist"
403 assert result["files"] == {}
404
405 def test_diff_empty_to_empty_has_no_ops(self, plugin, empty_snap):
406 delta = plugin.diff(empty_snap, empty_snap)
407 assert delta["ops"] == []
408
409 def test_diff_add_file(self, plugin, empty_snap, snap_with_one):
410 delta = plugin.diff(empty_snap, snap_with_one)
411 assert len(delta["ops"]) == 1
412 assert delta["ops"][0]["op"] == "insert"
413
414 def test_diff_remove_file(self, plugin, empty_snap, snap_with_one):
415 delta = plugin.diff(snap_with_one, empty_snap)
416 assert len(delta["ops"]) == 1
417 assert delta["ops"][0]["op"] == "delete"
418
419 def test_merge_no_conflict_both_sides_add_different(self, plugin, empty_snap):
420 from muse.domain import SnapshotManifest
421
422 left = SnapshotManifest(files={"a.py": "hash_a"}, domain="mist", directories=[])
423 right = SnapshotManifest(files={"b.py": "hash_b"}, domain="mist", directories=[])
424 result = plugin.merge(empty_snap, left, right)
425 assert result.conflicts == []
426 assert "a.py" in result.merged["files"]
427 assert "b.py" in result.merged["files"]
428
429 def test_merge_conflict_both_sides_change_same_path(self, plugin):
430 from muse.domain import SnapshotManifest
431
432 base = SnapshotManifest(files={"x.py": "hash_base"}, domain="mist", directories=[])
433 left = SnapshotManifest(files={"x.py": "hash_left"}, domain="mist", directories=[])
434 right = SnapshotManifest(files={"x.py": "hash_right"}, domain="mist", directories=[])
435 result = plugin.merge(base, left, right)
436 assert "x.py" in result.conflicts
437
438 def test_merge_no_conflict_same_add_both_sides(self, plugin, empty_snap):
439 """Both sides adding the same mist (same content) is not a conflict."""
440 from muse.domain import SnapshotManifest
441
442 left = SnapshotManifest(files={"z.py": "hash_z"}, domain="mist", directories=[])
443 right = SnapshotManifest(files={"z.py": "hash_z"}, domain="mist", directories=[])
444 result = plugin.merge(empty_snap, left, right)
445 assert result.conflicts == []
446 assert result.merged["files"]["z.py"] == "hash_z"
447
448 def test_drift_no_drift_when_identical(self, plugin, snap_with_one):
449 report = plugin.drift(snap_with_one, snap_with_one)
450 assert not report.has_drift
451
452 def test_drift_detects_change(self, plugin, empty_snap, snap_with_one):
453 report = plugin.drift(empty_snap, snap_with_one)
454 assert report.has_drift
455
456 def test_apply_returns_live_state_unchanged(self, plugin, empty_snap):
457 delta = plugin.diff(empty_snap, empty_snap)
458 result = plugin.apply(delta, empty_snap)
459 assert result is empty_snap
460
461
462 # ---------------------------------------------------------------------------
463 # Tier 5 — Data integrity: filesystem snapshot
464 # ---------------------------------------------------------------------------
465
466
467 class TestMistPluginFilesystemSnapshot:
468 """Snapshot of a real directory on disk."""
469
470 def test_snapshot_empty_directory(self, plugin, tmp_path):
471 from muse.domain import SnapshotManifest
472
473 snap = plugin.snapshot(tmp_path)
474 assert isinstance(snap, dict)
475 assert snap["domain"] == "mist"
476 assert snap["files"] == {}
477
478 def test_snapshot_single_file(self, plugin, tmp_path):
479 f = tmp_path / "hello.py"
480 f.write_bytes(b"print('hello')")
481 snap = plugin.snapshot(tmp_path)
482 assert "hello.py" in snap["files"]
483 assert isinstance(snap["files"]["hello.py"], str)
484
485 def test_snapshot_hidden_files_excluded(self, plugin, tmp_path):
486 hidden = tmp_path / ".hidden"
487 hidden.write_bytes(b"secret")
488 visible = tmp_path / "visible.txt"
489 visible.write_bytes(b"public")
490 snap = plugin.snapshot(tmp_path)
491 assert ".hidden" not in snap["files"]
492 assert "visible.txt" in snap["files"]
493
494 def test_snapshot_nested_files_included(self, plugin, tmp_path):
495 subdir = tmp_path / "subdir"
496 subdir.mkdir()
497 (subdir / "nested.py").write_bytes(b"x = 1")
498 snap = plugin.snapshot(tmp_path)
499 assert "subdir/nested.py" in snap["files"]
500
501 def test_drift_detects_new_file_on_disk(self, plugin, tmp_path):
502 from muse.domain import SnapshotManifest
503
504 committed = SnapshotManifest(files={}, domain="mist", directories=[])
505 (tmp_path / "new.py").write_bytes(b"def new(): pass")
506 report = plugin.drift(committed, tmp_path)
507 assert report.has_drift
508
509
510 # ---------------------------------------------------------------------------
511 # Tier 6 — Performance
512 # ---------------------------------------------------------------------------
513
514
515 class TestMistPluginPerformance:
516 """Ensure compute_mist_id is fast enough for large artifacts."""
517
518 def test_compute_mist_id_1mb_under_100ms(self):
519 from muse.plugins.mist.plugin import compute_mist_id
520
521 blob = b"x" * (1024 * 1024) # 1 MiB
522 start = time.perf_counter()
523 mist_id = compute_mist_id(blob)
524 elapsed = time.perf_counter() - start
525 assert len(mist_id) == 12
526 assert elapsed < 0.100, f"compute_mist_id took {elapsed:.3f}s on 1 MiB blob"
527
528 def test_snapshot_1000_files_under_5s(self, plugin, tmp_path):
529 for i in range(1000):
530 (tmp_path / f"mist_{i:04d}.py").write_bytes(f"x = {i}".encode())
531 start = time.perf_counter()
532 snap = plugin.snapshot(tmp_path)
533 elapsed = time.perf_counter() - start
534 assert len(snap["files"]) == 1000
535 assert elapsed < 5.0, f"snapshot of 1000 files took {elapsed:.3f}s"
536
537
538 # ---------------------------------------------------------------------------
539 # Tier 8 — Docstring completeness
540 # ---------------------------------------------------------------------------
541
542
543 class TestMistPluginDocstrings:
544 """Every public symbol in plugin.py must carry a non-empty docstring."""
545
546 PUBLIC_FUNCTIONS = (
547 "compute_mist_id",
548 "detect_artifact_type",
549 "_validate_mist_filename",
550 "extract_mist_symbol_anchors",
551 )
552
553 PLUGIN_METHODS = (
554 "snapshot",
555 "diff",
556 "merge",
557 "drift",
558 "apply",
559 "schema",
560 )
561
562 def test_module_docstring(self):
563 import muse.plugins.mist.plugin as mod
564
565 assert mod.__doc__ and len(mod.__doc__.strip()) > 0
566
567 def test_mist_plugin_class_docstring(self):
568 from muse.plugins.mist.plugin import MistPlugin
569
570 assert MistPlugin.__doc__ and len(MistPlugin.__doc__.strip()) > 0
571
572 @pytest.mark.parametrize("func_name", PUBLIC_FUNCTIONS)
573 def test_function_has_docstring(self, func_name):
574 import muse.plugins.mist.plugin as mod
575
576 fn = getattr(mod, func_name)
577 assert fn.__doc__ and len(fn.__doc__.strip()) > 0, (
578 f"{func_name} is missing a docstring"
579 )
580
581 @pytest.mark.parametrize("method_name", PLUGIN_METHODS)
582 def test_plugin_method_has_docstring(self, method_name):
583 from muse.plugins.mist.plugin import MistPlugin
584
585 method = getattr(MistPlugin, method_name)
586 assert method.__doc__ and len(method.__doc__.strip()) > 0, (
587 f"MistPlugin.{method_name} is missing a docstring"
588 )
File History 2 commits
sha256:88ac91129873e6a496e9189515aa690eb893ae25d69c8f72af141a2be5068eb3 docs: docstring sprint contract→find-symbol — idiomatic run… Sonnet 4.6 patch 140 days ago
sha256:a09b1b4f6838754495547f200aa0ce88e2f56ffc5b20b900f6f0cff2c3cdede9 fix(cursorignore): remove git-ism (.git/worktrees) Human minor 143 days ago