-
Notifications
You must be signed in to change notification settings - Fork 7.7k
Expand file tree
/
Copy pathtest_presets.py
More file actions
2763 lines (2234 loc) · 111 KB
/
test_presets.py
File metadata and controls
2763 lines (2234 loc) · 111 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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Unit tests for the preset system.
Tests cover:
- Preset manifest validation
- Preset registry operations
- Preset manager installation/removal
- Template catalog search
- Template resolver priority stack
- Extension-provided templates
"""
import pytest
import json
import tempfile
import shutil
import zipfile
from pathlib import Path
from datetime import datetime, timezone
import yaml
from specify_cli.presets import (
PresetManifest,
PresetRegistry,
PresetManager,
PresetCatalog,
PresetCatalogEntry,
PresetResolver,
PresetError,
PresetValidationError,
PresetCompatibilityError,
VALID_PRESET_TEMPLATE_TYPES,
)
from specify_cli.extensions import ExtensionRegistry
# ===== Fixtures =====
@pytest.fixture
def temp_dir():
"""Create a temporary directory for tests."""
tmpdir = tempfile.mkdtemp()
yield Path(tmpdir)
shutil.rmtree(tmpdir)
@pytest.fixture
def valid_pack_data():
"""Valid preset manifest data."""
return {
"schema_version": "1.0",
"preset": {
"id": "test-pack",
"name": "Test Preset",
"version": "1.0.0",
"description": "A test preset",
"author": "Test Author",
"repository": "https://github.com/test/test-pack",
"license": "MIT",
},
"requires": {
"speckit_version": ">=0.1.0",
},
"provides": {
"templates": [
{
"type": "template",
"name": "spec-template",
"file": "templates/spec-template.md",
"description": "Custom spec template",
"replaces": "spec-template",
}
]
},
"tags": ["testing", "example"],
}
@pytest.fixture
def pack_dir(temp_dir, valid_pack_data):
"""Create a complete preset directory structure."""
p_dir = temp_dir / "test-pack"
p_dir.mkdir()
# Write manifest
manifest_path = p_dir / "preset.yml"
with open(manifest_path, 'w') as f:
yaml.dump(valid_pack_data, f)
# Create templates directory
templates_dir = p_dir / "templates"
templates_dir.mkdir()
# Write template file
tmpl_file = templates_dir / "spec-template.md"
tmpl_file.write_text("# Custom Spec Template\n\nThis is a custom template.\n")
return p_dir
@pytest.fixture
def project_dir(temp_dir):
"""Create a mock spec-kit project directory."""
proj_dir = temp_dir / "project"
proj_dir.mkdir()
# Create .specify directory
specify_dir = proj_dir / ".specify"
specify_dir.mkdir()
# Create templates directory with core templates
templates_dir = specify_dir / "templates"
templates_dir.mkdir()
# Create core spec-template
core_spec = templates_dir / "spec-template.md"
core_spec.write_text("# Core Spec Template\n")
# Create core plan-template
core_plan = templates_dir / "plan-template.md"
core_plan.write_text("# Core Plan Template\n")
# Create commands subdirectory
commands_dir = templates_dir / "commands"
commands_dir.mkdir()
return proj_dir
# ===== PresetManifest Tests =====
class TestPresetManifest:
"""Test PresetManifest validation and parsing."""
def test_valid_manifest(self, pack_dir):
"""Test loading a valid manifest."""
manifest = PresetManifest(pack_dir / "preset.yml")
assert manifest.id == "test-pack"
assert manifest.name == "Test Preset"
assert manifest.version == "1.0.0"
assert manifest.description == "A test preset"
assert manifest.author == "Test Author"
assert manifest.requires_speckit_version == ">=0.1.0"
assert len(manifest.templates) == 1
assert manifest.tags == ["testing", "example"]
def test_missing_manifest(self, temp_dir):
"""Test that missing manifest raises error."""
with pytest.raises(PresetValidationError, match="Manifest not found"):
PresetManifest(temp_dir / "nonexistent.yml")
def test_invalid_yaml(self, temp_dir):
"""Test that invalid YAML raises error."""
bad_file = temp_dir / "bad.yml"
bad_file.write_text(": invalid: yaml: {{{")
with pytest.raises(PresetValidationError, match="Invalid YAML"):
PresetManifest(bad_file)
def test_missing_schema_version(self, temp_dir, valid_pack_data):
"""Test missing schema_version field."""
del valid_pack_data["schema_version"]
manifest_path = temp_dir / "preset.yml"
with open(manifest_path, 'w') as f:
yaml.dump(valid_pack_data, f)
with pytest.raises(PresetValidationError, match="Missing required field: schema_version"):
PresetManifest(manifest_path)
def test_wrong_schema_version(self, temp_dir, valid_pack_data):
"""Test unsupported schema version."""
valid_pack_data["schema_version"] = "2.0"
manifest_path = temp_dir / "preset.yml"
with open(manifest_path, 'w') as f:
yaml.dump(valid_pack_data, f)
with pytest.raises(PresetValidationError, match="Unsupported schema version"):
PresetManifest(manifest_path)
def test_missing_pack_id(self, temp_dir, valid_pack_data):
"""Test missing preset.id field."""
del valid_pack_data["preset"]["id"]
manifest_path = temp_dir / "preset.yml"
with open(manifest_path, 'w') as f:
yaml.dump(valid_pack_data, f)
with pytest.raises(PresetValidationError, match="Missing preset.id"):
PresetManifest(manifest_path)
def test_invalid_pack_id_format(self, temp_dir, valid_pack_data):
"""Test invalid pack ID format."""
valid_pack_data["preset"]["id"] = "Invalid_ID"
manifest_path = temp_dir / "preset.yml"
with open(manifest_path, 'w') as f:
yaml.dump(valid_pack_data, f)
with pytest.raises(PresetValidationError, match="Invalid preset ID"):
PresetManifest(manifest_path)
def test_invalid_version(self, temp_dir, valid_pack_data):
"""Test invalid semantic version."""
valid_pack_data["preset"]["version"] = "not-a-version"
manifest_path = temp_dir / "preset.yml"
with open(manifest_path, 'w') as f:
yaml.dump(valid_pack_data, f)
with pytest.raises(PresetValidationError, match="Invalid version"):
PresetManifest(manifest_path)
def test_missing_speckit_version(self, temp_dir, valid_pack_data):
"""Test missing requires.speckit_version."""
del valid_pack_data["requires"]["speckit_version"]
manifest_path = temp_dir / "preset.yml"
with open(manifest_path, 'w') as f:
yaml.dump(valid_pack_data, f)
with pytest.raises(PresetValidationError, match="Missing requires.speckit_version"):
PresetManifest(manifest_path)
def test_no_templates_provided(self, temp_dir, valid_pack_data):
"""Test pack with no templates."""
valid_pack_data["provides"]["templates"] = []
manifest_path = temp_dir / "preset.yml"
with open(manifest_path, 'w') as f:
yaml.dump(valid_pack_data, f)
with pytest.raises(PresetValidationError, match="must provide at least one template"):
PresetManifest(manifest_path)
def test_invalid_template_type(self, temp_dir, valid_pack_data):
"""Test template with invalid type."""
valid_pack_data["provides"]["templates"][0]["type"] = "invalid"
manifest_path = temp_dir / "preset.yml"
with open(manifest_path, 'w') as f:
yaml.dump(valid_pack_data, f)
with pytest.raises(PresetValidationError, match="Invalid template type"):
PresetManifest(manifest_path)
def test_valid_template_types(self):
"""Test that all expected template types are valid."""
assert "template" in VALID_PRESET_TEMPLATE_TYPES
assert "command" in VALID_PRESET_TEMPLATE_TYPES
assert "script" in VALID_PRESET_TEMPLATE_TYPES
def test_template_missing_required_fields(self, temp_dir, valid_pack_data):
"""Test template missing required fields."""
valid_pack_data["provides"]["templates"] = [{"type": "template"}]
manifest_path = temp_dir / "preset.yml"
with open(manifest_path, 'w') as f:
yaml.dump(valid_pack_data, f)
with pytest.raises(PresetValidationError, match="missing 'type', 'name', or 'file'"):
PresetManifest(manifest_path)
def test_invalid_template_name_format(self, temp_dir, valid_pack_data):
"""Test template with invalid name format."""
valid_pack_data["provides"]["templates"][0]["name"] = "Invalid Name"
manifest_path = temp_dir / "preset.yml"
with open(manifest_path, 'w') as f:
yaml.dump(valid_pack_data, f)
with pytest.raises(PresetValidationError, match="Invalid template name"):
PresetManifest(manifest_path)
def test_get_hash(self, pack_dir):
"""Test manifest hash calculation."""
manifest = PresetManifest(pack_dir / "preset.yml")
hash_val = manifest.get_hash()
assert hash_val.startswith("sha256:")
assert len(hash_val) > 10
def test_multiple_templates(self, temp_dir, valid_pack_data):
"""Test pack with multiple templates of different types."""
valid_pack_data["provides"]["templates"] = [
{"type": "template", "name": "spec-template", "file": "templates/spec-template.md"},
{"type": "template", "name": "plan-template", "file": "templates/plan-template.md"},
{"type": "command", "name": "specify", "file": "commands/specify.md"},
{"type": "script", "name": "create-new-feature", "file": "scripts/create-new-feature.sh"},
]
manifest_path = temp_dir / "preset.yml"
with open(manifest_path, 'w') as f:
yaml.dump(valid_pack_data, f)
manifest = PresetManifest(manifest_path)
assert len(manifest.templates) == 4
# ===== PresetRegistry Tests =====
class TestPresetRegistry:
"""Test PresetRegistry operations."""
def test_empty_registry(self, temp_dir):
"""Test empty registry initialization."""
packs_dir = temp_dir / "packs"
packs_dir.mkdir()
registry = PresetRegistry(packs_dir)
assert registry.list() == {}
assert not registry.is_installed("test-pack")
def test_add_and_get(self, temp_dir):
"""Test adding and retrieving a pack."""
packs_dir = temp_dir / "packs"
packs_dir.mkdir()
registry = PresetRegistry(packs_dir)
registry.add("test-pack", {"version": "1.0.0", "source": "local"})
assert registry.is_installed("test-pack")
metadata = registry.get("test-pack")
assert metadata is not None
assert metadata["version"] == "1.0.0"
assert "installed_at" in metadata
def test_remove(self, temp_dir):
"""Test removing a pack."""
packs_dir = temp_dir / "packs"
packs_dir.mkdir()
registry = PresetRegistry(packs_dir)
registry.add("test-pack", {"version": "1.0.0"})
assert registry.is_installed("test-pack")
registry.remove("test-pack")
assert not registry.is_installed("test-pack")
def test_remove_nonexistent(self, temp_dir):
"""Test removing a pack that doesn't exist."""
packs_dir = temp_dir / "packs"
packs_dir.mkdir()
registry = PresetRegistry(packs_dir)
registry.remove("nonexistent") # Should not raise
def test_list(self, temp_dir):
"""Test listing all packs."""
packs_dir = temp_dir / "packs"
packs_dir.mkdir()
registry = PresetRegistry(packs_dir)
registry.add("pack-a", {"version": "1.0.0"})
registry.add("pack-b", {"version": "2.0.0"})
all_packs = registry.list()
assert len(all_packs) == 2
assert "pack-a" in all_packs
assert "pack-b" in all_packs
def test_persistence(self, temp_dir):
"""Test that registry data persists across instances."""
packs_dir = temp_dir / "packs"
packs_dir.mkdir()
# Add with first instance
registry1 = PresetRegistry(packs_dir)
registry1.add("test-pack", {"version": "1.0.0"})
# Load with second instance
registry2 = PresetRegistry(packs_dir)
assert registry2.is_installed("test-pack")
def test_corrupted_registry(self, temp_dir):
"""Test recovery from corrupted registry file."""
packs_dir = temp_dir / "packs"
packs_dir.mkdir()
registry_file = packs_dir / ".registry"
registry_file.write_text("not valid json{{{")
registry = PresetRegistry(packs_dir)
assert registry.list() == {}
def test_get_nonexistent(self, temp_dir):
"""Test getting a nonexistent pack."""
packs_dir = temp_dir / "packs"
packs_dir.mkdir()
registry = PresetRegistry(packs_dir)
assert registry.get("nonexistent") is None
def test_restore(self, temp_dir):
"""Test restore() preserves timestamps exactly."""
packs_dir = temp_dir / "packs"
packs_dir.mkdir()
registry = PresetRegistry(packs_dir)
# Create original entry with a specific timestamp
original_metadata = {
"version": "1.0.0",
"source": "local",
"installed_at": "2025-01-15T10:30:00+00:00",
"enabled": True,
}
registry.restore("test-pack", original_metadata)
# Verify exact restoration
restored = registry.get("test-pack")
assert restored["installed_at"] == "2025-01-15T10:30:00+00:00"
assert restored["version"] == "1.0.0"
assert restored["enabled"] is True
def test_restore_rejects_none_metadata(self, temp_dir):
"""Test restore() raises ValueError for None metadata."""
packs_dir = temp_dir / "packs"
packs_dir.mkdir()
registry = PresetRegistry(packs_dir)
with pytest.raises(ValueError, match="metadata must be a dict"):
registry.restore("test-pack", None)
def test_restore_rejects_non_dict_metadata(self, temp_dir):
"""Test restore() raises ValueError for non-dict metadata."""
packs_dir = temp_dir / "packs"
packs_dir.mkdir()
registry = PresetRegistry(packs_dir)
with pytest.raises(ValueError, match="metadata must be a dict"):
registry.restore("test-pack", "not-a-dict")
with pytest.raises(ValueError, match="metadata must be a dict"):
registry.restore("test-pack", ["list", "not", "dict"])
def test_restore_uses_deep_copy(self, temp_dir):
"""Test restore() deep copies metadata to prevent mutation."""
packs_dir = temp_dir / "packs"
packs_dir.mkdir()
registry = PresetRegistry(packs_dir)
original_metadata = {
"version": "1.0.0",
"nested": {"key": "original"},
}
registry.restore("test-pack", original_metadata)
# Mutate the original metadata after restore
original_metadata["version"] = "MUTATED"
original_metadata["nested"]["key"] = "MUTATED"
# Registry should have the original values
stored = registry.get("test-pack")
assert stored["version"] == "1.0.0"
assert stored["nested"]["key"] == "original"
def test_get_returns_deep_copy(self, temp_dir):
"""Test that get() returns a deep copy to prevent mutation."""
packs_dir = temp_dir / "packs"
packs_dir.mkdir()
registry = PresetRegistry(packs_dir)
registry.add("test-pack", {"version": "1.0.0", "nested": {"key": "original"}})
# Get and mutate the returned copy
metadata = registry.get("test-pack")
metadata["version"] = "MUTATED"
metadata["nested"]["key"] = "MUTATED"
# Original should be unchanged
fresh = registry.get("test-pack")
assert fresh["version"] == "1.0.0"
assert fresh["nested"]["key"] == "original"
def test_get_returns_none_for_corrupted_entry(self, temp_dir):
"""Test that get() returns None for corrupted (non-dict) entries."""
packs_dir = temp_dir / "packs"
packs_dir.mkdir()
registry = PresetRegistry(packs_dir)
# Directly corrupt the registry with non-dict entries
registry.data["presets"]["corrupted-string"] = "not a dict"
registry.data["presets"]["corrupted-list"] = ["not", "a", "dict"]
registry.data["presets"]["corrupted-int"] = 42
registry._save()
# All corrupted entries should return None
assert registry.get("corrupted-string") is None
assert registry.get("corrupted-list") is None
assert registry.get("corrupted-int") is None
# Non-existent should also return None
assert registry.get("nonexistent") is None
def test_list_returns_deep_copy(self, temp_dir):
"""Test that list() returns deep copies to prevent mutation."""
packs_dir = temp_dir / "packs"
packs_dir.mkdir()
registry = PresetRegistry(packs_dir)
registry.add("test-pack", {"version": "1.0.0", "nested": {"key": "original"}})
# Get list and mutate
all_packs = registry.list()
all_packs["test-pack"]["version"] = "MUTATED"
all_packs["test-pack"]["nested"]["key"] = "MUTATED"
# Original should be unchanged
fresh = registry.get("test-pack")
assert fresh["version"] == "1.0.0"
assert fresh["nested"]["key"] == "original"
def test_list_returns_empty_dict_for_corrupted_registry(self, temp_dir):
"""Test that list() returns empty dict when presets is not a dict."""
packs_dir = temp_dir / "packs"
packs_dir.mkdir()
registry = PresetRegistry(packs_dir)
# Corrupt the registry - presets is a list instead of dict
registry.data["presets"] = ["not", "a", "dict"]
registry._save()
# list() should return empty dict, not crash
result = registry.list()
assert result == {}
def test_list_by_priority_excludes_disabled(self, temp_dir):
"""Test that list_by_priority excludes disabled presets by default."""
packs_dir = temp_dir / "packs"
packs_dir.mkdir()
registry = PresetRegistry(packs_dir)
registry.add("pack-enabled", {"version": "1.0.0", "enabled": True, "priority": 5})
registry.add("pack-disabled", {"version": "1.0.0", "enabled": False, "priority": 1})
registry.add("pack-default", {"version": "1.0.0", "priority": 10}) # no enabled field = True
# Default: exclude disabled
by_priority = registry.list_by_priority()
pack_ids = [p[0] for p in by_priority]
assert "pack-enabled" in pack_ids
assert "pack-default" in pack_ids
assert "pack-disabled" not in pack_ids
def test_list_by_priority_includes_disabled_when_requested(self, temp_dir):
"""Test that list_by_priority includes disabled presets when requested."""
packs_dir = temp_dir / "packs"
packs_dir.mkdir()
registry = PresetRegistry(packs_dir)
registry.add("pack-enabled", {"version": "1.0.0", "enabled": True, "priority": 5})
registry.add("pack-disabled", {"version": "1.0.0", "enabled": False, "priority": 1})
# Include disabled
by_priority = registry.list_by_priority(include_disabled=True)
pack_ids = [p[0] for p in by_priority]
assert "pack-enabled" in pack_ids
assert "pack-disabled" in pack_ids
# Disabled pack has lower priority number, so it comes first when included
assert pack_ids[0] == "pack-disabled"
# ===== PresetManager Tests =====
class TestPresetManager:
"""Test PresetManager installation and removal."""
def test_install_from_directory(self, project_dir, pack_dir):
"""Test installing a preset from a directory."""
manager = PresetManager(project_dir)
manifest = manager.install_from_directory(pack_dir, "0.1.5")
assert manifest.id == "test-pack"
assert manager.registry.is_installed("test-pack")
# Verify files are copied
installed_dir = project_dir / ".specify" / "presets" / "test-pack"
assert installed_dir.exists()
assert (installed_dir / "preset.yml").exists()
assert (installed_dir / "templates" / "spec-template.md").exists()
def test_install_already_installed(self, project_dir, pack_dir):
"""Test installing an already-installed pack raises error."""
manager = PresetManager(project_dir)
manager.install_from_directory(pack_dir, "0.1.5")
with pytest.raises(PresetError, match="already installed"):
manager.install_from_directory(pack_dir, "0.1.5")
def test_install_incompatible(self, project_dir, temp_dir, valid_pack_data):
"""Test installing an incompatible pack raises error."""
valid_pack_data["requires"]["speckit_version"] = ">=99.0.0"
incompat_dir = temp_dir / "incompat-pack"
incompat_dir.mkdir()
manifest_path = incompat_dir / "preset.yml"
with open(manifest_path, 'w') as f:
yaml.dump(valid_pack_data, f)
(incompat_dir / "templates").mkdir()
(incompat_dir / "templates" / "spec-template.md").write_text("test")
manager = PresetManager(project_dir)
with pytest.raises(PresetCompatibilityError):
manager.install_from_directory(incompat_dir, "0.1.5")
def test_install_from_zip(self, project_dir, pack_dir, temp_dir):
"""Test installing from a ZIP file."""
zip_path = temp_dir / "test-pack.zip"
with zipfile.ZipFile(zip_path, 'w') as zf:
for file_path in pack_dir.rglob('*'):
if file_path.is_file():
arcname = file_path.relative_to(pack_dir)
zf.write(file_path, arcname)
manager = PresetManager(project_dir)
manifest = manager.install_from_zip(zip_path, "0.1.5")
assert manifest.id == "test-pack"
assert manager.registry.is_installed("test-pack")
def test_install_from_zip_nested(self, project_dir, pack_dir, temp_dir):
"""Test installing from ZIP with nested directory."""
zip_path = temp_dir / "test-pack.zip"
with zipfile.ZipFile(zip_path, 'w') as zf:
for file_path in pack_dir.rglob('*'):
if file_path.is_file():
arcname = Path("test-pack-v1.0.0") / file_path.relative_to(pack_dir)
zf.write(file_path, arcname)
manager = PresetManager(project_dir)
manifest = manager.install_from_zip(zip_path, "0.1.5")
assert manifest.id == "test-pack"
def test_install_from_zip_no_manifest(self, project_dir, temp_dir):
"""Test installing from ZIP without manifest raises error."""
zip_path = temp_dir / "bad.zip"
with zipfile.ZipFile(zip_path, 'w') as zf:
zf.writestr("readme.txt", "no manifest here")
manager = PresetManager(project_dir)
with pytest.raises(PresetValidationError, match="No preset.yml found"):
manager.install_from_zip(zip_path, "0.1.5")
def test_remove(self, project_dir, pack_dir):
"""Test removing a preset."""
manager = PresetManager(project_dir)
manager.install_from_directory(pack_dir, "0.1.5")
assert manager.registry.is_installed("test-pack")
result = manager.remove("test-pack")
assert result is True
assert not manager.registry.is_installed("test-pack")
installed_dir = project_dir / ".specify" / "presets" / "test-pack"
assert not installed_dir.exists()
def test_remove_nonexistent(self, project_dir):
"""Test removing a pack that doesn't exist."""
manager = PresetManager(project_dir)
result = manager.remove("nonexistent")
assert result is False
def test_list_installed(self, project_dir, pack_dir):
"""Test listing installed packs."""
manager = PresetManager(project_dir)
manager.install_from_directory(pack_dir, "0.1.5")
installed = manager.list_installed()
assert len(installed) == 1
assert installed[0]["id"] == "test-pack"
assert installed[0]["name"] == "Test Preset"
assert installed[0]["version"] == "1.0.0"
assert installed[0]["template_count"] == 1
def test_list_installed_empty(self, project_dir):
"""Test listing when no packs installed."""
manager = PresetManager(project_dir)
assert manager.list_installed() == []
def test_get_pack(self, project_dir, pack_dir):
"""Test getting a specific installed pack."""
manager = PresetManager(project_dir)
manager.install_from_directory(pack_dir, "0.1.5")
pack = manager.get_pack("test-pack")
assert pack is not None
assert pack.id == "test-pack"
def test_get_pack_not_installed(self, project_dir):
"""Test getting a non-installed pack returns None."""
manager = PresetManager(project_dir)
assert manager.get_pack("nonexistent") is None
def test_check_compatibility_valid(self, pack_dir, temp_dir):
"""Test compatibility check with valid version."""
manager = PresetManager(temp_dir)
manifest = PresetManifest(pack_dir / "preset.yml")
assert manager.check_compatibility(manifest, "0.1.5") is True
def test_check_compatibility_invalid(self, pack_dir, temp_dir):
"""Test compatibility check with invalid specifier."""
manager = PresetManager(temp_dir)
manifest = PresetManifest(pack_dir / "preset.yml")
manifest.data["requires"]["speckit_version"] = "not-a-specifier"
with pytest.raises(PresetCompatibilityError, match="Invalid version specifier"):
manager.check_compatibility(manifest, "0.1.5")
def test_install_with_priority(self, project_dir, pack_dir):
"""Test installing a pack with custom priority."""
manager = PresetManager(project_dir)
manager.install_from_directory(pack_dir, "0.1.5", priority=5)
metadata = manager.registry.get("test-pack")
assert metadata is not None
assert metadata["priority"] == 5
def test_install_default_priority(self, project_dir, pack_dir):
"""Test that default priority is 10."""
manager = PresetManager(project_dir)
manager.install_from_directory(pack_dir, "0.1.5")
metadata = manager.registry.get("test-pack")
assert metadata is not None
assert metadata["priority"] == 10
def test_list_installed_includes_priority(self, project_dir, pack_dir):
"""Test that list_installed includes priority."""
manager = PresetManager(project_dir)
manager.install_from_directory(pack_dir, "0.1.5", priority=3)
installed = manager.list_installed()
assert len(installed) == 1
assert installed[0]["priority"] == 3
class TestRegistryPriority:
"""Test registry priority sorting."""
def test_list_by_priority(self, temp_dir):
"""Test that list_by_priority sorts by priority number."""
packs_dir = temp_dir / "packs"
packs_dir.mkdir()
registry = PresetRegistry(packs_dir)
registry.add("pack-high", {"version": "1.0.0", "priority": 1})
registry.add("pack-low", {"version": "1.0.0", "priority": 20})
registry.add("pack-mid", {"version": "1.0.0", "priority": 10})
sorted_packs = registry.list_by_priority()
assert len(sorted_packs) == 3
assert sorted_packs[0][0] == "pack-high"
assert sorted_packs[1][0] == "pack-mid"
assert sorted_packs[2][0] == "pack-low"
def test_list_by_priority_default(self, temp_dir):
"""Test that packs without priority default to 10."""
packs_dir = temp_dir / "packs"
packs_dir.mkdir()
registry = PresetRegistry(packs_dir)
registry.add("pack-a", {"version": "1.0.0"}) # no priority, defaults to 10
registry.add("pack-b", {"version": "1.0.0", "priority": 5})
sorted_packs = registry.list_by_priority()
assert sorted_packs[0][0] == "pack-b"
assert sorted_packs[1][0] == "pack-a"
def test_list_by_priority_invalid_priority_defaults(self, temp_dir):
"""Malformed priority values fall back to the default priority."""
packs_dir = temp_dir / "packs"
packs_dir.mkdir()
registry = PresetRegistry(packs_dir)
registry.add("pack-high", {"version": "1.0.0", "priority": 1})
registry.data["presets"]["pack-invalid"] = {
"version": "1.0.0",
"priority": "high",
}
registry._save()
sorted_packs = registry.list_by_priority()
assert [item[0] for item in sorted_packs] == ["pack-high", "pack-invalid"]
assert sorted_packs[1][1]["priority"] == 10
# ===== PresetResolver Tests =====
class TestPresetResolver:
"""Test PresetResolver priority stack."""
def test_resolve_core_template(self, project_dir):
"""Test resolving a core template."""
resolver = PresetResolver(project_dir)
result = resolver.resolve("spec-template")
assert result is not None
assert result.name == "spec-template.md"
assert "Core Spec Template" in result.read_text()
def test_resolve_nonexistent(self, project_dir):
"""Test resolving a nonexistent template returns None."""
resolver = PresetResolver(project_dir)
result = resolver.resolve("nonexistent-template")
assert result is None
def test_resolve_higher_priority_pack_wins(self, project_dir, temp_dir, valid_pack_data):
"""Test that a pack with lower priority number wins over higher number."""
manager = PresetManager(project_dir)
# Create pack A (priority 10 — lower precedence)
pack_a_dir = temp_dir / "pack-a"
pack_a_dir.mkdir()
data_a = {**valid_pack_data}
data_a["preset"] = {**valid_pack_data["preset"], "id": "pack-a", "name": "Pack A"}
with open(pack_a_dir / "preset.yml", 'w') as f:
yaml.dump(data_a, f)
(pack_a_dir / "templates").mkdir()
(pack_a_dir / "templates" / "spec-template.md").write_text("# From Pack A\n")
# Create pack B (priority 1 — higher precedence)
pack_b_dir = temp_dir / "pack-b"
pack_b_dir.mkdir()
data_b = {**valid_pack_data}
data_b["preset"] = {**valid_pack_data["preset"], "id": "pack-b", "name": "Pack B"}
with open(pack_b_dir / "preset.yml", 'w') as f:
yaml.dump(data_b, f)
(pack_b_dir / "templates").mkdir()
(pack_b_dir / "templates" / "spec-template.md").write_text("# From Pack B\n")
# Install A first (priority 10), B second (priority 1)
manager.install_from_directory(pack_a_dir, "0.1.5", priority=10)
manager.install_from_directory(pack_b_dir, "0.1.5", priority=1)
# Pack B should win because lower priority number
resolver = PresetResolver(project_dir)
result = resolver.resolve("spec-template")
assert result is not None
assert "From Pack B" in result.read_text()
def test_resolve_override_takes_priority(self, project_dir):
"""Test that project overrides take priority over core."""
# Create override
overrides_dir = project_dir / ".specify" / "templates" / "overrides"
overrides_dir.mkdir(parents=True)
override = overrides_dir / "spec-template.md"
override.write_text("# Override Spec Template\n")
resolver = PresetResolver(project_dir)
result = resolver.resolve("spec-template")
assert result is not None
assert "Override Spec Template" in result.read_text()
def test_resolve_pack_takes_priority_over_core(self, project_dir, pack_dir):
"""Test that installed packs take priority over core templates."""
# Install the pack
manager = PresetManager(project_dir)
manager.install_from_directory(pack_dir, "0.1.5")
resolver = PresetResolver(project_dir)
result = resolver.resolve("spec-template")
assert result is not None
assert "Custom Spec Template" in result.read_text()
def test_resolve_override_takes_priority_over_pack(self, project_dir, pack_dir):
"""Test that overrides take priority over installed packs."""
# Install the pack
manager = PresetManager(project_dir)
manager.install_from_directory(pack_dir, "0.1.5")
# Create override
overrides_dir = project_dir / ".specify" / "templates" / "overrides"
overrides_dir.mkdir(parents=True)
override = overrides_dir / "spec-template.md"
override.write_text("# Override Spec Template\n")
resolver = PresetResolver(project_dir)
result = resolver.resolve("spec-template")
assert result is not None
assert "Override Spec Template" in result.read_text()
def test_resolve_extension_provided_templates(self, project_dir):
"""Test resolving templates provided by extensions."""
# Create extension with templates
ext_dir = project_dir / ".specify" / "extensions" / "my-ext"
ext_templates_dir = ext_dir / "templates"
ext_templates_dir.mkdir(parents=True)
ext_template = ext_templates_dir / "custom-template.md"
ext_template.write_text("# Extension Custom Template\n")
# Register extension in registry
extensions_dir = project_dir / ".specify" / "extensions"
ext_registry = ExtensionRegistry(extensions_dir)
ext_registry.add("my-ext", {"version": "1.0.0", "priority": 10})
resolver = PresetResolver(project_dir)
result = resolver.resolve("custom-template")
assert result is not None
assert "Extension Custom Template" in result.read_text()
def test_resolve_disabled_extension_templates_skipped(self, project_dir):
"""Test that disabled extension templates are not resolved."""
# Create extension with templates
ext_dir = project_dir / ".specify" / "extensions" / "disabled-ext"
ext_templates_dir = ext_dir / "templates"
ext_templates_dir.mkdir(parents=True)
ext_template = ext_templates_dir / "disabled-template.md"
ext_template.write_text("# Disabled Extension Template\n")
# Register extension as disabled
extensions_dir = project_dir / ".specify" / "extensions"
ext_registry = ExtensionRegistry(extensions_dir)
ext_registry.add("disabled-ext", {"version": "1.0.0", "priority": 1, "enabled": False})
# Template should NOT be resolved because extension is disabled
resolver = PresetResolver(project_dir)
result = resolver.resolve("disabled-template")
assert result is None, "Disabled extension template should not be resolved"
def test_resolve_disabled_extension_not_picked_up_as_unregistered(self, project_dir):
"""Test that disabled extensions are not picked up via unregistered dir scan."""
# Create extension directory with templates
ext_dir = project_dir / ".specify" / "extensions" / "test-disabled-ext"
ext_templates_dir = ext_dir / "templates"
ext_templates_dir.mkdir(parents=True)
ext_template = ext_templates_dir / "unique-disabled-template.md"
ext_template.write_text("# Should Not Resolve\n")
# Register the extension but disable it
extensions_dir = project_dir / ".specify" / "extensions"
ext_registry = ExtensionRegistry(extensions_dir)
ext_registry.add("test-disabled-ext", {"version": "1.0.0", "enabled": False})
# Verify the template is NOT resolved (even though the directory exists)
resolver = PresetResolver(project_dir)
result = resolver.resolve("unique-disabled-template")
assert result is None, "Disabled extension should not be picked up as unregistered"
def test_resolve_pack_over_extension(self, project_dir, pack_dir, temp_dir, valid_pack_data):
"""Test that pack templates take priority over extension templates."""
# Create extension with templates
ext_dir = project_dir / ".specify" / "extensions" / "my-ext"
ext_templates_dir = ext_dir / "templates"
ext_templates_dir.mkdir(parents=True)
ext_template = ext_templates_dir / "spec-template.md"
ext_template.write_text("# Extension Spec Template\n")
# Install a pack with the same template
manager = PresetManager(project_dir)
manager.install_from_directory(pack_dir, "0.1.5")
resolver = PresetResolver(project_dir)
result = resolver.resolve("spec-template")
assert result is not None
# Pack should win over extension
assert "Custom Spec Template" in result.read_text()
def test_resolve_with_source_core(self, project_dir):
"""Test resolve_with_source for core template."""
resolver = PresetResolver(project_dir)
result = resolver.resolve_with_source("spec-template")
assert result is not None
assert result["source"] == "core"
assert "spec-template.md" in result["path"]
def test_resolve_with_source_override(self, project_dir):
"""Test resolve_with_source for override template."""
overrides_dir = project_dir / ".specify" / "templates" / "overrides"
overrides_dir.mkdir(parents=True)
override = overrides_dir / "spec-template.md"
override.write_text("# Override\n")
resolver = PresetResolver(project_dir)
result = resolver.resolve_with_source("spec-template")
assert result is not None
assert result["source"] == "project override"
def test_resolve_with_source_pack(self, project_dir, pack_dir):
"""Test resolve_with_source for pack template."""
manager = PresetManager(project_dir)
manager.install_from_directory(pack_dir, "0.1.5")
resolver = PresetResolver(project_dir)
result = resolver.resolve_with_source("spec-template")
assert result is not None
assert "test-pack" in result["source"]
assert "v1.0.0" in result["source"]
def test_resolve_with_source_extension(self, project_dir):
"""Test resolve_with_source for extension-provided template."""
ext_dir = project_dir / ".specify" / "extensions" / "my-ext"
ext_templates_dir = ext_dir / "templates"
ext_templates_dir.mkdir(parents=True)
ext_template = ext_templates_dir / "unique-template.md"
ext_template.write_text("# Unique\n")
# Register extension in registry
extensions_dir = project_dir / ".specify" / "extensions"
ext_registry = ExtensionRegistry(extensions_dir)
ext_registry.add("my-ext", {"version": "1.0.0", "priority": 10})
resolver = PresetResolver(project_dir)
result = resolver.resolve_with_source("unique-template")
assert result is not None
assert result["source"] == "extension:my-ext v1.0.0"
def test_resolve_with_source_not_found(self, project_dir):
"""Test resolve_with_source for nonexistent template."""
resolver = PresetResolver(project_dir)
result = resolver.resolve_with_source("nonexistent")
assert result is None
def test_resolve_skips_hidden_extension_dirs(self, project_dir):
"""Test that hidden directories in extensions are skipped."""
ext_dir = project_dir / ".specify" / "extensions" / ".backup"
ext_templates_dir = ext_dir / "templates"
ext_templates_dir.mkdir(parents=True)
ext_template = ext_templates_dir / "hidden-template.md"
ext_template.write_text("# Hidden\n")
resolver = PresetResolver(project_dir)
result = resolver.resolve("hidden-template")
assert result is None