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