forked from hyphen-2025/cyber-pilot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_cli_py_coverage.py
More file actions
3500 lines (2951 loc) · 149 KB
/
test_cli_py_coverage.py
File metadata and controls
3500 lines (2951 loc) · 149 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
import io
import json
import os
import sys
import types
import unittest
from contextlib import redirect_stdout
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).parent.parent / "skills" / "cypilot" / "scripts"))
def setUpModule():
from cypilot.utils.ui import set_json_mode
set_json_mode(True)
def tearDownModule():
from cypilot.utils.ui import set_json_mode
set_json_mode(False)
def _write_json(path: Path, data: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
def _bootstrap_project_root(root: Path, adapter_rel: str = "adapter") -> Path:
(root / ".git").mkdir()
(root / "AGENTS.md").write_text(
f'<!-- @cpt:root-agents -->\n```toml\ncypilot_path = "{adapter_rel}"\n```\n',
encoding="utf-8",
)
adapter = root / adapter_rel
adapter.mkdir(parents=True, exist_ok=True)
(adapter / "config").mkdir(exist_ok=True)
(adapter / "config" / "AGENTS.md").write_text("# Test adapter\n", encoding="utf-8")
return adapter
def _setup_list_ids_project(root, *, codebase=None, ignore=None, content=None,
art_path="docs/reqs.md", system_name="Test", system_slug="test"):
"""Bootstrap a project with a single REQ artifact for list-ids tests."""
adapter = _bootstrap_project_root(root)
art = root / art_path
art.parent.mkdir(parents=True, exist_ok=True)
art.write_text(content or "- [x] `p1` - **ID**: `cpt-test-req-1`\n", encoding="utf-8")
from cypilot.utils import toml_utils
system = {
"name": system_name, "slug": system_slug,
"artifacts": [{"path": art_path, "kind": "req"}],
}
if codebase:
system["codebase"] = codebase
data = {"version": "1.0", "project_root": "..", "kits": {}, "systems": [system]}
if ignore:
data["ignore"] = ignore
toml_utils.dump(data, adapter / "config" / "artifacts.toml")
return adapter
def _bootstrap_self_check_kits(root: Path, adapter: Path, *, with_example: bool = True, bad_example: bool = False) -> None:
# Minimal artifacts registry that passes `load_artifacts_meta` and contains kits.
from cypilot.utils import toml_utils
toml_utils.dump(
{
"project_root": "..",
"systems": [],
"kits": {
"cypilot-sdlc": {"format": "Cypilot", "path": "kits/cypilot-sdlc"},
},
},
adapter / "config" / "artifacts.toml",
)
kit_root = root / "kits" / "cypilot-sdlc"
kit_root.mkdir(parents=True, exist_ok=True)
(kit_root / "artifacts" / "REQ").mkdir(parents=True, exist_ok=True)
(kit_root / "artifacts" / "REQ" / "template.md").write_text(
"---\ncypilot-template:\n version:\n major: 1\n minor: 0\n kind: REQ\n---\n\n"
"- [x] `p1` - **ID**: `cpt-{system}-req-{slug}`\n",
encoding="utf-8",
)
from _test_helpers import write_constraints_toml
write_constraints_toml(kit_root, {"REQ": {"identifiers": {"req": {"required": True, "template": "cpt-{system}-req-{slug}"}}}})
if with_example:
ex_dir = kit_root / "artifacts" / "REQ" / "examples"
ex_dir.mkdir(parents=True, exist_ok=True)
example = ex_dir / "example.md"
if bad_example:
example.write_text("# Example\n\n(no IDs)\n", encoding="utf-8")
else:
example.write_text(
"- [x] `p1` - **ID**: `cpt-myapp-req-login`\n",
encoding="utf-8",
)
# ── Shared fake classes for validate tests ────────────────────────────────────
# Extracted to module level to avoid SonarCloud duplication flags (S1144).
class _FakeKitPkg:
def is_cypilot_format(self):
return True
def get_template_path(self, _kind: str) -> str:
return "kits/x/artifacts/REQ/template.md"
class _FakeSystemNode:
kit = "x"
artifacts = []
codebase = []
children = []
class _FakeArtifactMeta:
def __init__(self, path: str, kind: str = "REQ", traceability: str = "FULL"):
self.path = path
self.kind = kind
self.traceability = traceability
class _FakeKit:
path = "kits/x"
# ── Compact fake classes for validate/workspace coverage tests ─────────────────
# These replace repeated local _KP/_SN/_AM/_Meta/_LK/_Prim/_Ctx definitions.
class _CompactKitPkg:
"""Fake kit package (compact one-liner style used in coverage tests)."""
def is_cypilot_format(self): return True
def get_template_path(self, _k): return "kits/x/artifacts/REQ/template.md"
class _CompactSystemNode:
"""Fake system node with optional codebase."""
def __init__(self, *, codebase=None):
self.kit = "x"
self.artifacts = []
self.codebase = codebase or []
self.children = []
class _CompactArtifactMeta:
"""Fake artifact meta with configurable fields."""
def __init__(self, path, kind="REQ", traceability="FULL", source=None):
self.path = path
self.kind = kind
self.traceability = traceability
self.source = source
class _CompactMeta:
"""Fake artifacts meta that yields configurable artifacts."""
def __init__(self, artifacts, *, systems=None, system_node=None):
# artifacts: str (single path) or list of (path, kind) tuples
if isinstance(artifacts, str):
self._arts = [(artifacts, "REQ")]
else:
self._arts = artifacts
self._sn = system_node or _CompactSystemNode()
self.systems = systems if systems is not None else []
def iter_all_artifacts(self):
for p, k in self._arts:
yield _CompactArtifactMeta(p, k), self._sn
def get_kit(self, _k): return _CompactKitPkg()
def is_ignored(self, _r): return False
class _CompactLoadedKit:
"""Fake loaded kit with optional constraints."""
def __init__(self, constraints=None):
self.kit = types.SimpleNamespace(path="kits/x")
self.constraints = constraints
class _CompactCtx:
"""Fake context for validate tests."""
def __init__(self, root, artifacts, *, kits=None, errors=None,
meta_systems=None, registered_systems=None, system_node=None):
self.meta = _CompactMeta(artifacts, systems=meta_systems, system_node=system_node)
self.project_root = root
self.registered_systems = registered_systems if registered_systems is not None else {"sys"}
self.kits = kits if kits is not None else {}
self._errors = errors or []
def get_known_id_kinds(self): return set()
class _CompactPrim:
"""Fake primary context for workspace tests (has adapter_dir)."""
def __init__(self, root, artifacts, *, kits=None, errors=None,
meta_systems=None, registered_systems=None, system_node=None):
self.meta = _CompactMeta(artifacts, systems=meta_systems, system_node=system_node)
self.project_root = root
self.adapter_dir = root / "adapter"
self.registered_systems = registered_systems if registered_systems is not None else {"sys"}
self.kits = kits if kits is not None else {}
self._errors = errors or []
def get_known_id_kinds(self): return set()
class _EmptyFakeMeta:
"""Fake meta with no artifacts (for --source tests)."""
systems = []
def iter_all_artifacts(self): return iter([])
def is_ignored(self, _rel): return False
class _EmptyFakePrimary:
"""Fake primary context with no artifacts (for --source tests)."""
meta = _EmptyFakeMeta()
project_root = Path("/fake")
adapter_dir = Path("/fake/adapter")
registered_systems = set()
kits = {}
_errors = []
def get_known_id_kinds(self): return set()
class _CollectMeta:
"""Fake meta for collect_artifacts_to_scan tests (no get_kit needed)."""
def __init__(self, ar):
self._ar = ar
def iter_all_artifacts(self):
yield _CompactArtifactMeta(self._ar, source=None), types.SimpleNamespace(kit="x")
def is_ignored(self, _r): return False
class _CollectPrim:
"""Fake primary for collect_artifacts_to_scan tests."""
def __init__(self, r, ar):
self.meta = _CollectMeta(ar)
self.project_root = r
self.adapter_dir = r / "adapter"
self.registered_systems = {"sys"}
self.kits = {}
self._errors = []
def _scaffold_validate_project(td):
"""Create minimal validate project structure. Returns (root, art_rel)."""
root = Path(td)
(root / "kits" / "x" / "artifacts" / "REQ").mkdir(parents=True, exist_ok=True)
(root / "kits" / "x" / "artifacts" / "REQ" / "template.md").write_text("# T\n", encoding="utf-8")
(root / "artifacts").mkdir(parents=True, exist_ok=True)
ar = "artifacts/REQ.md"
(root / ar).write_text("# R\n", encoding="utf-8")
return root, ar
def _build_ws_validate_ctx(td):
"""Build WorkspaceContext + validate project for workspace validate tests.
Returns (ws, art_resolved, WorkspaceContext_cls).
"""
from cypilot.utils.context import WorkspaceContext
root, ar = _scaffold_validate_project(td)
(root / "src").mkdir(parents=True, exist_ok=True)
(root / "src" / "code.py").write_text("print('ok')\n", encoding="utf-8")
codebase_sn = _CompactSystemNode(
codebase=[types.SimpleNamespace(path="src", extensions=[".py"])])
lk = _CompactLoadedKit(
constraints=types.SimpleNamespace(by_kind={"REQ": types.SimpleNamespace(defined_id=[])}))
p = _CompactPrim(root, ar, kits={"x": lk},
meta_systems=[codebase_sn],
system_node=types.SimpleNamespace(kit="x"))
ws = WorkspaceContext(primary=p, sources={})
art_resolved = (root / ar).resolve()
return ws, art_resolved, WorkspaceContext
def _run_ws_validate(args):
"""Run cmd_validate with a workspace context patched for get_all_artifact_ids.
Returns (rc, mock_get_all_ids, buf).
"""
from cypilot.commands import validate as validate_cmd
with TemporaryDirectory() as td:
ws, art_resolved, WC = _build_ws_validate_ctx(td)
buf = io.StringIO()
with patch("cypilot.utils.context.get_context", return_value=ws):
with patch.object(WC, "resolve_artifact_path", return_value=art_resolved):
with patch.object(WC, "get_all_artifact_ids", return_value={"cpt-remote-1"}) as mi:
with patch("cypilot.commands.validate.validate_artifact_file", return_value={"errors": [], "warnings": []}):
with patch("cypilot.commands.validate.cross_validate_artifacts", return_value={"errors": [], "warnings": []}):
with patch("cypilot.commands.validate.scan_cpt_ids", return_value=[]):
with redirect_stdout(buf):
rc = validate_cmd.cmd_validate(args)
return rc, mi, buf
def _make_cross_repo_dirs(td):
"""Create primary + remote directory pair for cross-repo tests. Returns (root, remote)."""
root = Path(td) / "primary"
root.mkdir()
remote = Path(td) / "remote"
remote.mkdir()
(root / "artifacts").mkdir()
(remote / "artifacts").mkdir()
return root, remote
def _patch_collect_artifacts(root, remote, remote_file="REMOTE.md"):
"""Return a patch for collect_artifacts_to_scan with standard cross-repo layout."""
return patch("cypilot.utils.context.collect_artifacts_to_scan", return_value=(
[
((root / "artifacts" / "REQ.md").resolve(), "REQ"),
((remote / "artifacts" / remote_file).resolve(), "REQ"),
],
{str((remote / "artifacts" / remote_file).resolve()): "backend"},
))
def _run_cli_dispatch(test_case, args):
"""Run CLI main() in a temp dir, assert exit code in [0, 1, 2]."""
from cypilot.cli import main
from cypilot.utils.ui import is_json_mode, set_json_mode
with TemporaryDirectory() as td:
cwd = os.getcwd()
saved_json_mode = is_json_mode()
try:
os.chdir(td)
buf = io.StringIO()
with redirect_stdout(buf):
rc = main(args)
test_case.assertIn(rc, [0, 1, 2])
finally:
set_json_mode(saved_json_mode)
os.chdir(cwd)
class TestCLIPyCoverageSelfCheck(unittest.TestCase):
def test_self_check_pass(self):
from cypilot.cli import main
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
adapter = _bootstrap_project_root(root)
_bootstrap_self_check_kits(root, adapter, with_example=True, bad_example=False)
cwd = os.getcwd()
try:
os.chdir(root)
stdout = io.StringIO()
with redirect_stdout(stdout):
exit_code = main(["self-check"])
self.assertEqual(exit_code, 0)
out = json.loads(stdout.getvalue())
self.assertEqual(out.get("status"), "PASS")
self.assertEqual(out.get("kits_validated"), 1)
self.assertEqual(out.get("templates_checked"), 1)
self.assertEqual(out["self_check_results"][0]["status"], "PASS")
finally:
os.chdir(cwd)
class TestCLIPyCoverageSelfCheckMoreBranches(unittest.TestCase):
def _bootstrap_kit(
self,
root: Path,
*,
kind: str = "REQ",
with_constraints: bool = True,
constraints_payload: dict | None = None,
template_content: str | None = None,
) -> "cypilot.utils.artifacts_meta.ArtifactsMeta":
from cypilot.utils.artifacts_meta import ArtifactsMeta
kit_root = root / "kits" / "k"
(kit_root / "artifacts" / kind / "examples").mkdir(parents=True, exist_ok=True)
tmpl = template_content if template_content is not None else "# T\n"
(kit_root / "artifacts" / kind / "template.md").write_text(tmpl, encoding="utf-8")
(kit_root / "artifacts" / kind / "examples" / "example.md").write_text(
"- [x] `p1` - **ID**: `cpt-myapp-req-login`\n",
encoding="utf-8",
)
if with_constraints:
payload = constraints_payload
if payload is None:
payload = {
kind: {
"identifiers": {
"req": {"required": False, "template": "cpt-{system}-req-{slug}"}
}
}
}
from _test_helpers import write_constraints_toml
write_constraints_toml(kit_root, payload)
reg = {
"version": "1.1",
"project_root": "..",
"systems": [],
"kits": {
"k": {
"format": "Cypilot",
"path": "kits/k",
"artifacts": {
kind: {
"template": "{project_root}/kits/k/artifacts/%s/template.md" % kind,
"examples": "{project_root}/kits/k/artifacts/%s/examples" % kind,
}
},
}
},
}
return ArtifactsMeta.from_dict(reg)
def test_run_self_check_passes_when_constraints_missing(self):
from cypilot.commands.self_check import run_self_check_from_meta
with TemporaryDirectory() as td:
root = Path(td)
meta = self._bootstrap_kit(root, with_constraints=False)
rc, out = run_self_check_from_meta(project_root=root, adapter_dir=(root / "adapter"), artifacts_meta=meta)
self.assertEqual(rc, 0)
self.assertEqual(out.get("status"), "PASS")
self.assertGreaterEqual(int(out.get("kits_checked", 0)), 1)
def test_run_self_check_fails_on_invalid_constraints(self):
from cypilot.commands.self_check import run_self_check_from_meta
with TemporaryDirectory() as td:
root = Path(td)
meta = self._bootstrap_kit(root, with_constraints=True, constraints_payload={"REQ": {}})
rc, out = run_self_check_from_meta(project_root=root, adapter_dir=(root / "adapter"), artifacts_meta=meta)
self.assertEqual(rc, 2)
self.assertEqual(out.get("status"), "FAIL")
self.assertGreaterEqual(int(out.get("kits_checked", 0)), 1)
def test_run_self_check_passes_when_kind_not_in_constraints(self):
from cypilot.commands.self_check import run_self_check_from_meta
with TemporaryDirectory() as td:
root = Path(td)
meta = self._bootstrap_kit(root, with_constraints=True, constraints_payload={"OTHER": {"identifiers": {}}})
rc, out = run_self_check_from_meta(project_root=root, adapter_dir=(root / "adapter"), artifacts_meta=meta)
self.assertEqual(rc, 0)
self.assertEqual(out.get("status"), "PASS")
def test_template_checks_phase_gate_on_heading_errors(self):
from cypilot.commands.self_check import run_self_check_from_meta
with TemporaryDirectory() as td:
root = Path(td)
meta = self._bootstrap_kit(root, with_constraints=True)
with patch(
"cypilot.commands.self_check.validate_headings_contract",
return_value={"errors": [{"type": "x", "message": "boom", "path": "p", "line": 1}], "warnings": []},
):
rc, out = run_self_check_from_meta(project_root=root, adapter_dir=(root / "adapter"), artifacts_meta=meta, verbose=True)
self.assertEqual(rc, 2)
self.assertEqual(out.get("status"), "FAIL")
def test_template_checks_template_unreadable_branch(self):
from cypilot.commands.self_check import run_self_check_from_meta
with TemporaryDirectory() as td:
root = Path(td)
meta = self._bootstrap_kit(root, with_constraints=True)
with patch("cypilot.commands.self_check.read_text_safe", return_value=None):
rc, out = run_self_check_from_meta(project_root=root, adapter_dir=(root / "adapter"), artifacts_meta=meta)
self.assertEqual(rc, 2)
self.assertEqual(out.get("status"), "FAIL")
def test_template_checks_fails_on_identifier_without_template(self):
from cypilot.commands.self_check import run_self_check_from_meta
with TemporaryDirectory() as td:
root = Path(td)
# identifiers.req has no template -> error branch
meta = self._bootstrap_kit(
root,
with_constraints=True,
constraints_payload={
"REQ": {
"identifiers": {
"req": {"required": False}
}
}
},
)
rc, out = run_self_check_from_meta(project_root=root, adapter_dir=(root / "adapter"), artifacts_meta=meta, verbose=True)
self.assertEqual(rc, 2)
self.assertEqual(out.get("status"), "FAIL")
self.assertIn("errors", out["results"][0])
def test_template_checks_fail_when_required_id_placeholder_missing(self):
from cypilot.commands.self_check import run_self_check_from_meta
with TemporaryDirectory() as td:
root = Path(td)
meta = self._bootstrap_kit(
root,
with_constraints=True,
constraints_payload={
"REQ": {
"identifiers": {
"req": {"required": True, "template": "cpt-{system}-req-{slug}"}
}
}
},
)
rc, out = run_self_check_from_meta(project_root=root, adapter_dir=(root / "adapter"), artifacts_meta=meta)
self.assertEqual(rc, 2)
self.assertEqual(out.get("status"), "FAIL")
def test_template_checks_id_placeholder_wrong_heading(self):
from cypilot.commands.self_check import run_self_check_from_meta
with TemporaryDirectory() as td:
root = Path(td)
meta = self._bootstrap_kit(
root,
with_constraints=True,
template_content="# T\n\n- [ ] **ID**: `cpt-{system}-req-{slug}`\n",
constraints_payload={
"REQ": {
"headings": [{"level": 1, "pattern": "^T$"}],
"identifiers": {
"req": {
"required": True,
"template": "cpt-{system}-req-{slug}",
"headings": ["allowed"],
}
},
}
},
)
fake_headings_at = [[] for _ in range(10)]
fake_headings_at[3] = ["not-allowed"]
with patch("cypilot.commands.self_check.heading_constraint_ids_by_line", return_value=fake_headings_at):
rc, out = run_self_check_from_meta(project_root=root, adapter_dir=(root / "adapter"), artifacts_meta=meta)
self.assertEqual(rc, 2)
self.assertEqual(out.get("status"), "FAIL")
def test_template_checks_required_reference_missing(self):
from cypilot.commands.self_check import run_self_check_from_meta
with TemporaryDirectory() as td:
root = Path(td)
meta = self._bootstrap_kit(
root,
with_constraints=True,
constraints_payload={
"SRC": {
"identifiers": {
"x": {
"required": False,
"template": "cpt-{system}-x-{slug}",
"references": {"REQ": {"coverage": True}},
}
}
},
"REQ": {"identifiers": {"req": {"required": False, "template": "cpt-{system}-req-{slug}"}}},
},
)
rc, out = run_self_check_from_meta(project_root=root, adapter_dir=(root / "adapter"), artifacts_meta=meta)
self.assertEqual(rc, 2)
self.assertEqual(out.get("status"), "FAIL")
def test_template_checks_required_reference_wrong_heading(self):
from cypilot.commands.self_check import run_self_check_from_meta
with TemporaryDirectory() as td:
root = Path(td)
meta = self._bootstrap_kit(
root,
with_constraints=True,
template_content="# T\n\nRef `cpt-{system}-x-{slug}`\n",
constraints_payload={
"SRC": {
"identifiers": {
"x": {
"required": False,
"template": "cpt-{system}-x-{slug}",
"references": {"REQ": {"coverage": True, "headings": ["allowed"]}},
}
}
},
"REQ": {
"headings": [{"level": 1, "pattern": "^T$"}],
"identifiers": {
"req": {"required": False, "template": "cpt-{system}-req-{slug}"}
},
},
},
)
fake_headings_at = [[] for _ in range(10)]
fake_headings_at[3] = ["not-allowed"]
with patch("cypilot.commands.self_check.heading_constraint_ids_by_line", return_value=fake_headings_at):
rc, out = run_self_check_from_meta(project_root=root, adapter_dir=(root / "adapter"), artifacts_meta=meta)
self.assertEqual(rc, 2)
self.assertEqual(out.get("status"), "FAIL")
def test_run_self_check_fallback_when_kit_paths_raise(self):
from cypilot.commands.self_check import run_self_check_from_meta
with TemporaryDirectory() as td:
root = Path(td)
meta = self._bootstrap_kit(root, with_constraints=True)
kit = meta.kits["k"]
def _boom(_kind: str) -> str:
raise ValueError("boom")
kit.get_template_path = _boom
kit.get_examples_path = _boom
# Legacy fallback layout already exists from _bootstrap_kit.
# Verify fallback picks up the files even when get_*_path raises.
rc, out = run_self_check_from_meta(project_root=root, adapter_dir=(root / "adapter"), artifacts_meta=meta, verbose=True)
self.assertEqual(rc, 0)
self.assertEqual(out.get("status"), "PASS")
class TestCLIPyCoverageSelfCheckReverseAndOptional(unittest.TestCase):
"""Tests for self-check reverse checks and optional missing warnings."""
def _bootstrap_kit(self, root, *, kind="REQ", constraints_payload=None, template_content=None):
from cypilot.utils.artifacts_meta import ArtifactsMeta
kit_root = root / "kits" / "k"
(kit_root / "artifacts" / kind / "examples").mkdir(parents=True, exist_ok=True)
tmpl = template_content or "# T\n"
(kit_root / "artifacts" / kind / "template.md").write_text(tmpl, encoding="utf-8")
(kit_root / "artifacts" / kind / "examples" / "example.md").write_text(
"- [x] `p1` - **ID**: `cpt-myapp-req-login`\n", encoding="utf-8",
)
if constraints_payload is not None:
from _test_helpers import write_constraints_toml
write_constraints_toml(kit_root, constraints_payload)
reg = {
"version": "1.1", "project_root": "..", "systems": [],
"kits": {"k": {"format": "Cypilot", "path": "kits/k", "artifacts": {
kind: {
"template": "{project_root}/kits/k/artifacts/%s/template.md" % kind,
"examples": "{project_root}/kits/k/artifacts/%s/examples" % kind,
},
}}},
}
return ArtifactsMeta.from_dict(reg)
def test_template_def_kind_not_in_constraints(self):
"""Template has definition pattern not in constraints → error."""
from cypilot.commands.self_check import run_self_check_from_meta
with TemporaryDirectory() as td:
root = Path(td)
tmpl = (
"---\ncypilot-template:\n version:\n major: 1\n minor: 0\n kind: REQ\n---\n"
"- [ ] `p1` - **ID**: `cpt-{system}-unknown-{slug}`\n"
)
meta = self._bootstrap_kit(root, constraints_payload={
"REQ": {"identifiers": {"req": {"required": False, "template": "cpt-{system}-req-{slug}"}}}
}, template_content=tmpl)
rc, out = run_self_check_from_meta(project_root=root, adapter_dir=(root / "adapter"), artifacts_meta=meta, verbose=True)
self.assertEqual(rc, 2)
errs = out["results"][0].get("errors", [])
codes = [e.get("code") for e in errs]
self.assertIn("template-def-kind-not-in-constraints", codes)
def test_template_ref_kind_not_in_constraints(self):
"""Template has reference pattern not in constraints → error."""
from cypilot.commands.self_check import run_self_check_from_meta
with TemporaryDirectory() as td:
root = Path(td)
tmpl = (
"---\ncypilot-template:\n version:\n major: 1\n minor: 0\n kind: REQ\n---\n"
"- [ ] `p1` - **ID**: `cpt-{system}-req-{slug}`\n"
"**Refs**: `cpt-{system}-bogus-{slug}`\n"
)
meta = self._bootstrap_kit(root, constraints_payload={
"REQ": {"identifiers": {"req": {"required": False, "template": "cpt-{system}-req-{slug}"}}}
}, template_content=tmpl)
rc, out = run_self_check_from_meta(project_root=root, adapter_dir=(root / "adapter"), artifacts_meta=meta, verbose=True)
self.assertEqual(rc, 2)
errs = out["results"][0].get("errors", [])
codes = [e.get("code") for e in errs]
self.assertIn("template-ref-kind-not-in-constraints", codes)
def test_optional_def_missing_from_template_warns(self):
"""Optional definition kind in constraints but missing from template → warning."""
from cypilot.commands.self_check import run_self_check_from_meta
with TemporaryDirectory() as td:
root = Path(td)
# Template has no ID definitions at all — optional kind 'req' missing
tmpl = "---\ncypilot-template:\n version:\n major: 1\n minor: 0\n kind: REQ\n---\n# T\n"
meta = self._bootstrap_kit(root, constraints_payload={
"REQ": {"identifiers": {"req": {"required": False, "template": "cpt-{system}-req-{slug}"}}}
}, template_content=tmpl)
rc, out = run_self_check_from_meta(project_root=root, adapter_dir=(root / "adapter"), artifacts_meta=meta, verbose=True)
# Should pass (optional), but with a warning
warns = out["results"][0].get("warnings", [])
msgs = [w.get("message", "") for w in warns]
self.assertTrue(any("optional ID placeholder" in m for m in msgs), f"Expected optional warning, got: {msgs}")
def test_optional_ref_missing_from_template_warns(self):
"""Optional reference in constraints but missing from template → warning."""
from cypilot.commands.self_check import run_self_check_from_meta
with TemporaryDirectory() as td:
root = Path(td)
# PRD defines 'fr', DESIGN references 'fr' as optional — but DESIGN template doesn't have the reference placeholder
tmpl = "---\ncypilot-template:\n version:\n major: 1\n minor: 0\n kind: DESIGN\n---\n# T\n"
constraints = {
"PRD": {"identifiers": {"fr": {"required": False, "template": "cpt-{system}-fr-{slug}", "references": {
"DESIGN": {}
}}}},
"DESIGN": {"identifiers": {"design": {"required": False, "template": "cpt-{system}-design-{slug}"}}},
}
meta = self._bootstrap_kit(root, kind="DESIGN", constraints_payload=constraints, template_content=tmpl)
rc, out = run_self_check_from_meta(project_root=root, adapter_dir=(root / "adapter"), artifacts_meta=meta, verbose=True)
warns = out["results"][0].get("warnings", [])
msgs = [w.get("message", "") for w in warns]
self.assertTrue(any("optional reference placeholder" in m for m in msgs), f"Expected optional ref warning, got: {warns}")
class TestCLIPyCoverageValidateBranches(unittest.TestCase):
def test_validate_artifact_outside_project_root_hits_relative_to_error(self):
from cypilot.commands import validate as validate_cmd
class _FakeMeta:
systems = []
def get_artifact_by_path(self, _rel: str):
return None
def get_kit(self, _kit_id: str):
return _FakeKitPkg()
def iter_all_artifacts(self):
return iter([])
def is_ignored(self, _rel: str) -> bool:
return False
class _FakeLoadedKit:
kit = _FakeKit()
constraints = None
class _FakeCtx:
meta = _FakeMeta()
project_root = Path("/fake/nonexistent-root")
registered_systems = {"sys"}
kits = {"x": _FakeLoadedKit()}
def get_known_id_kinds(self):
return set()
with TemporaryDirectory() as td:
tmp = Path(td)
outside = tmp / "outside"
outside.mkdir(parents=True, exist_ok=True)
art = outside / "A.md"
art.write_text("# X\n", encoding="utf-8")
# Force context to claim a different project root so Path.relative_to() raises ValueError.
fake_ctx = _FakeCtx()
fake_ctx.project_root = tmp / "project"
buf = io.StringIO()
with patch("cypilot.utils.context.CypilotContext.load", return_value=fake_ctx):
with patch("cypilot.utils.context.get_context", return_value=fake_ctx):
with redirect_stdout(buf):
rc = validate_cmd.cmd_validate(["--artifact", str(art)])
self.assertEqual(rc, 1)
out = json.loads(buf.getvalue())
self.assertEqual(out.get("status"), "ERROR")
def test_validate_early_stop_writes_output_file(self):
from cypilot.commands import validate as validate_cmd
class _FakeMeta:
def __init__(self, root: Path, art_rel: str):
self._root = root
self._art_rel = art_rel
self.systems = []
def iter_all_artifacts(self):
yield _FakeArtifactMeta(self._art_rel, "REQ", "FULL"), _FakeSystemNode()
def get_kit(self, _kit_id: str):
return _FakeKitPkg()
def is_ignored(self, _rel: str) -> bool:
return False
class _FakeLoadedKit:
kit = _FakeKit()
constraints = types.SimpleNamespace(by_kind={"REQ": types.SimpleNamespace(defined_id=[])})
class _FakeCtx:
def __init__(self, root: Path, art_rel: str):
self.meta = _FakeMeta(root, art_rel)
self.project_root = root
self.registered_systems = {"sys"}
self.kits = {"x": _FakeLoadedKit()}
self._errors = []
def get_known_id_kinds(self):
return set()
with TemporaryDirectory() as td:
root = Path(td)
(root / "kits" / "x" / "artifacts" / "REQ").mkdir(parents=True, exist_ok=True)
(root / "kits" / "x" / "artifacts" / "REQ" / "template.md").write_text("# T\n", encoding="utf-8")
art_rel = "artifacts/REQ.md"
(root / "artifacts").mkdir(parents=True, exist_ok=True)
(root / art_rel).write_text("# R\n", encoding="utf-8")
ctx = _FakeCtx(root, art_rel)
out_path = root / "out.json"
with patch("cypilot.utils.context.get_context", return_value=ctx):
# Force per-artifact validation to fail so cmd_validate returns early and writes output.
with patch("cypilot.commands.validate.validate_artifact_file", return_value={"errors": [{"type": "x", "message": "boom", "path": str(root / art_rel), "line": 1}], "warnings": []}):
rc = validate_cmd.cmd_validate(["--output", str(out_path)])
self.assertEqual(rc, 2)
self.assertTrue(out_path.is_file())
def test_validate_skips_non_cypilot_artifacts_in_registry(self):
from cypilot.commands import validate as validate_cmd
class _FakePkg:
def is_cypilot_format(self):
return False
class _FakeArtifactMeta:
path = "a.md"
kind = "REQ"
traceability = "FULL"
class _FakeMeta:
systems = []
def iter_all_artifacts(self):
yield _FakeArtifactMeta(), _FakeSystemNode()
def get_kit(self, _kit_id: str):
return _FakePkg()
class _FakeCtx:
def __init__(self, root: Path):
self.meta = _FakeMeta()
self.project_root = root
self.registered_systems = set()
self.kits = {}
self._errors = []
def get_known_id_kinds(self):
return set()
with TemporaryDirectory() as td:
root = Path(td)
ctx = _FakeCtx(root)
buf = io.StringIO()
with patch("cypilot.utils.context.get_context", return_value=ctx):
with redirect_stdout(buf):
rc = validate_cmd.cmd_validate([])
# Validate succeeds with empty/non-Cypilot artifacts
self.assertIn(rc, [0, 1, 2])
out = json.loads(buf.getvalue())
self.assertIn("status", out)
def test_validate_ctx_errors_are_reported_and_trigger_early_fail(self):
from cypilot.commands import validate as validate_cmd
class _FakeMeta:
def __init__(self, art_rel: str):
self._art_rel = art_rel
self.systems = []
def iter_all_artifacts(self):
yield _FakeArtifactMeta(self._art_rel), _FakeSystemNode()
def get_kit(self, _kit_id: str):
return _FakeKitPkg()
class _FakeLoadedKit:
kit = _FakeKit()
constraints = types.SimpleNamespace(by_kind={"REQ": types.SimpleNamespace(defined_id=[types.SimpleNamespace(kind="req")])})
class _FakeCtx:
def __init__(self, root: Path, art_rel: str):
self.meta = _FakeMeta(art_rel)
self.project_root = root
self.registered_systems = {"sys"}
self.kits = {"x": _FakeLoadedKit()}
self._errors = [{"type": "constraints", "message": "ctx boom", "path": "<x>", "line": 1}]
def get_known_id_kinds(self):
return set()
with TemporaryDirectory() as td:
root = Path(td)
(root / "kits" / "x" / "artifacts" / "REQ").mkdir(parents=True, exist_ok=True)
(root / "kits" / "x" / "artifacts" / "REQ" / "template.md").write_text("# T\n", encoding="utf-8")
(root / "artifacts").mkdir(parents=True, exist_ok=True)
art_rel = "artifacts/REQ.md"
(root / art_rel).write_text("# R\n", encoding="utf-8")
ctx = _FakeCtx(root, art_rel)
buf = io.StringIO()
with patch("cypilot.utils.context.get_context", return_value=ctx):
with patch("cypilot.commands.validate.validate_artifact_file", return_value={"errors": [], "warnings": []}):
with redirect_stdout(buf):
rc = validate_cmd.cmd_validate([])
self.assertEqual(rc, 2)
out = json.loads(buf.getvalue())
self.assertEqual(out.get("status"), "FAIL")
self.assertGreater(out.get("error_count", 0), 0)
def test_validate_constraints_path_resolve_error_and_verbose_scan_exception(self):
from cypilot.commands import validate as validate_cmd
class _BadKit:
@property
def path(self):
raise OSError("boom")
class _FakeLoadedKit:
kit = _BadKit()
constraints = types.SimpleNamespace(by_kind={"REQ": types.SimpleNamespace(defined_id=[])})
class _FakeMeta:
def __init__(self, art_rel: str):
self._art_rel = art_rel
self.systems = []
def iter_all_artifacts(self):
yield _FakeArtifactMeta(self._art_rel), _FakeSystemNode()
def get_kit(self, _kit_id: str):
return _FakeKitPkg()
class _FakeCtx:
def __init__(self, root: Path, art_rel: str):
self.meta = _FakeMeta(art_rel)
self.project_root = root
self.registered_systems = {"sys"}
self.kits = {"x": _FakeLoadedKit()}
self._errors = []
def get_known_id_kinds(self):
return set()
with TemporaryDirectory() as td:
root = Path(td)
(root / "kits" / "x" / "artifacts" / "REQ").mkdir(parents=True, exist_ok=True)
(root / "kits" / "x" / "artifacts" / "REQ" / "template.md").write_text("# T\n", encoding="utf-8")
(root / "artifacts").mkdir(parents=True, exist_ok=True)
art_rel = "artifacts/REQ.md"
(root / art_rel).write_text("# R\n", encoding="utf-8")
ctx = _FakeCtx(root, art_rel)
buf = io.StringIO()
with patch("cypilot.utils.context.get_context", return_value=ctx):
with patch("cypilot.commands.validate.scan_cpt_ids", side_effect=ValueError("scan boom")):
with patch(
"cypilot.commands.validate.validate_artifact_file",
return_value={"errors": [{"type": "x", "message": "boom", "path": str(root / art_rel), "line": 1}], "warnings": []},
):
with redirect_stdout(buf):
rc = validate_cmd.cmd_validate(["--verbose"])
self.assertEqual(rc, 2)