forked from hyphen-2025/cyber-pilot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_toc.py
More file actions
790 lines (674 loc) · 27.7 KB
/
test_toc.py
File metadata and controls
790 lines (674 loc) · 27.7 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
"""Tests for the cypilot toc command and unified TOC module."""
from __future__ import annotations
import json
import textwrap
from pathlib import Path
import pytest
from cypilot.commands.toc import cmd_toc
from cypilot.utils.toc import (
build_toc as _build_toc,
parse_headings as _parse_headings,
process_file as _process_file,
github_anchor as _slugify,
)
from cypilot.commands.validate_toc import cmd_validate_toc
from cypilot.utils.toc import (
build_toc,
github_anchor,
insert_toc_heading,
insert_toc_markers,
parse_headings,
validate_toc,
)
# ---------------------------------------------------------------------------
# _slugify
# ---------------------------------------------------------------------------
class TestSlugify:
def test_simple(self):
assert _slugify("Overview") == "overview"
def test_spaces_to_hyphens(self):
assert _slugify("Quick Reference") == "quick-reference"
def test_special_chars_stripped(self):
assert _slugify("Part I — Identifiers") == "part-i--identifiers"
def test_backticks_removed(self):
assert _slugify("`code` stuff") == "code-stuff"
def test_markdown_link(self):
assert _slugify("[WCAG 2.2](https://example.com)") == "wcag-22"
def test_bold_italic_removed(self):
assert _slugify("**Bold** and *italic*") == "bold-and-italic"
def test_ampersand_stripped(self):
assert _slugify("Scope & Boundaries") == "scope--boundaries"
# ---------------------------------------------------------------------------
# _parse_headings
# ---------------------------------------------------------------------------
class TestParseHeadings:
def test_basic(self):
lines = ["# Title", "## Section", "### Sub"]
result = _parse_headings(lines, min_level=2)
assert result == [(2, "Section"), (3, "Sub")]
def test_skips_fenced_code(self):
lines = [
"## Real",
"```",
"## Fake inside fence",
"```",
"## Also Real",
]
result = _parse_headings(lines, min_level=2)
assert len(result) == 2
assert result[0] == (2, "Real")
assert result[1] == (2, "Also Real")
def test_max_level(self):
lines = ["## L2", "### L3", "#### L4"]
result = _parse_headings(lines, min_level=2, max_level=3)
assert len(result) == 2
def test_empty(self):
assert _parse_headings([]) == []
def test_no_headings(self):
lines = ["Just text", "More text"]
assert _parse_headings(lines) == []
# ---------------------------------------------------------------------------
# _build_toc
# ---------------------------------------------------------------------------
class TestBuildToc:
def test_flat(self):
headings = [(2, "A"), (2, "B")]
toc = _build_toc(headings)
assert toc == "- [A](#a)\n- [B](#b)"
def test_nested(self):
headings = [(2, "Parent"), (3, "Child")]
toc = _build_toc(headings)
lines = toc.split("\n")
assert lines[0] == "- [Parent](#parent)"
assert lines[1] == " - [Child](#child)"
def test_duplicate_slugs(self):
headings = [(2, "Overview"), (2, "Overview")]
toc = _build_toc(headings)
assert "(#overview)" in toc
assert "(#overview-1)" in toc
def test_empty(self):
assert _build_toc([]) == ""
def test_custom_indent(self):
headings = [(2, "Parent"), (3, "Child")]
toc = _build_toc(headings, indent_size=4)
lines = toc.split("\n")
assert lines[1].startswith(" - ")
# ---------------------------------------------------------------------------
# _process_file
# ---------------------------------------------------------------------------
class TestProcessFile:
def test_file_not_found(self, tmp_path: Path):
result = _process_file(tmp_path / "nope.md")
assert result["status"] == "ERROR"
def test_no_headings(self, tmp_path: Path):
f = tmp_path / "empty.md"
f.write_text("Just text\n", encoding="utf-8")
result = _process_file(f)
assert result["status"] == "SKIP"
def test_inserts_toc_after_h1(self, tmp_path: Path):
f = tmp_path / "doc.md"
f.write_text("# Title\n\n## Section A\n\n## Section B\n", encoding="utf-8")
result = _process_file(f)
assert result["status"] == "UPDATED"
content = f.read_text(encoding="utf-8")
assert "<!-- toc -->" in content
assert "<!-- /toc -->" in content
assert "[Section A](#section-a)" in content
assert "[Section B](#section-b)" in content
def test_updates_existing_markers(self, tmp_path: Path):
f = tmp_path / "doc.md"
f.write_text(
"# Title\n\n<!-- toc -->\nold toc\n<!-- /toc -->\n\n## New\n",
encoding="utf-8",
)
result = _process_file(f)
assert result["status"] == "UPDATED"
content = f.read_text(encoding="utf-8")
assert "old toc" not in content
assert "[New](#new)" in content
def test_dry_run(self, tmp_path: Path):
f = tmp_path / "doc.md"
original = "# Title\n\n## Section\n"
f.write_text(original, encoding="utf-8")
result = _process_file(f, dry_run=True)
assert result["status"] == "WOULD_UPDATE"
assert f.read_text(encoding="utf-8") == original
def test_unchanged(self, tmp_path: Path):
f = tmp_path / "doc.md"
f.write_text("# Title\n\n## Section\n", encoding="utf-8")
# First run: insert
_process_file(f)
# Second run: should be unchanged
result = _process_file(f)
assert result["status"] == "UNCHANGED"
def test_max_level(self, tmp_path: Path):
f = tmp_path / "doc.md"
f.write_text("# T\n\n## L2\n\n### L3\n\n#### L4\n", encoding="utf-8")
_process_file(f, max_level=3)
content = f.read_text(encoding="utf-8")
assert "[L2]" in content
assert "[L3]" in content
assert "[L4]" not in content
# ---------------------------------------------------------------------------
# cmd_toc (integration)
# ---------------------------------------------------------------------------
class TestCmdToc:
def test_basic(self, tmp_path: Path, capsys):
f = tmp_path / "test.md"
f.write_text("# Doc\n\n## A\n\n## B\n", encoding="utf-8")
rc = cmd_toc([str(f)])
assert rc == 0
out = json.loads(capsys.readouterr().out)
assert out["status"] == "OK"
assert out["results"][0]["status"] == "UPDATED"
def test_multiple_files(self, tmp_path: Path, capsys):
f1 = tmp_path / "a.md"
f2 = tmp_path / "b.md"
f1.write_text("# A\n\n## X\n", encoding="utf-8")
f2.write_text("# B\n\n## Y\n", encoding="utf-8")
rc = cmd_toc([str(f1), str(f2)])
assert rc == 0
out = json.loads(capsys.readouterr().out)
assert out["files_processed"] == 2
def test_dry_run_flag(self, tmp_path: Path, capsys):
f = tmp_path / "test.md"
original = "# Doc\n\n## A\n"
f.write_text(original, encoding="utf-8")
rc = cmd_toc(["--dry-run", str(f)])
assert rc == 0
assert f.read_text(encoding="utf-8") == original
def test_missing_file(self, tmp_path: Path, capsys):
rc = cmd_toc([str(tmp_path / "nope.md")])
assert rc == 1
out = json.loads(capsys.readouterr().out)
assert out["status"] == "ERROR"
# ---------------------------------------------------------------------------
# Unified module: github_anchor
# ---------------------------------------------------------------------------
class TestGithubAnchor:
def test_strikethrough_removed(self):
assert github_anchor("~~deleted~~ text") == "deleted-text"
def test_double_star_removed(self):
assert github_anchor("**Bold** title") == "bold-title"
def test_link_text_kept(self):
assert github_anchor("[Link](http://example.com) here") == "link-here"
def test_consecutive_hyphens_preserved(self):
assert github_anchor("A — B") == "a--b"
def test_unicode_preserved(self):
assert github_anchor("Привет мир") == "привет-мир"
# ---------------------------------------------------------------------------
# Unified module: parse_headings (skip_first, skip_toc_heading)
# ---------------------------------------------------------------------------
class TestParseHeadingsUnified:
def test_skip_first(self):
lines = ["# Title", "## A", "## B"]
result = parse_headings(lines, skip_first=True)
assert result == [(2, "A"), (2, "B")]
def test_skip_toc_heading(self):
lines = ["## Table of Contents", "## Real Section"]
result = parse_headings(lines, skip_toc_heading=True)
assert result == [(2, "Real Section")]
def test_skip_toc_heading_case_insensitive(self):
lines = ["## TOC", "## Section"]
result = parse_headings(lines, skip_toc_heading=True)
assert result == [(2, "Section")]
def test_skip_first_and_toc(self):
lines = ["# Doc Title", "## Table of Contents", "## Overview"]
result = parse_headings(lines, skip_first=True, skip_toc_heading=True)
assert result == [(2, "Overview")]
def test_tilde_fences_skipped(self):
lines = ["## Real", "~~~", "## Fake", "~~~", "## Also Real"]
result = parse_headings(lines)
assert result == [(2, "Real"), (2, "Also Real")]
def test_four_backtick_fence(self):
lines = ["## Before", "````", "## Inside", "````", "## After"]
result = parse_headings(lines)
assert result == [(2, "Before"), (2, "After")]
def test_fence_with_info_string_not_a_closer(self):
"""A line like '```python' inside a fence must NOT close it (CommonMark §4.5)."""
lines = [
"## Before",
"```python",
"## Inside code",
"```python", # NOT a closer — has info string
"## Still inside",
"```", # real closer
"## After",
]
result = parse_headings(lines)
assert result == [(2, "Before"), (2, "After")]
def test_fence_closer_with_trailing_spaces_ok(self):
"""Closing fence with trailing whitespace is valid."""
lines = [
"## Before",
"```",
"## Inside",
"``` ", # valid closer — only whitespace after
"## After",
]
result = parse_headings(lines)
assert result == [(2, "Before"), (2, "After")]
def test_indented_4_spaces_not_a_fence(self):
"""4+ leading spaces is an indented code block, not a fence (CommonMark §4.5)."""
lines = [
"## Before",
" ```python", # 4 spaces — NOT a fence opener
"## Middle",
" ```", # 4 spaces — NOT a fence closer
"## After",
]
result = parse_headings(lines)
assert result == [(2, "Before"), (2, "Middle"), (2, "After")]
def test_indented_3_spaces_is_a_fence(self):
"""Up to 3 leading spaces is still a valid fence opener."""
lines = [
"## Before",
" ```", # 3 spaces — valid fence
"## Inside",
" ```", # 3 spaces — valid closer
"## After",
]
result = parse_headings(lines)
assert result == [(2, "Before"), (2, "After")]
# ---------------------------------------------------------------------------
# Unified module: build_toc (numbered mode)
# ---------------------------------------------------------------------------
class TestBuildTocNumbered:
def test_numbered_top_level(self):
headings = [(2, "First"), (2, "Second"), (2, "Third")]
toc = build_toc(headings, numbered=True)
lines = toc.split("\n")
assert lines[0] == "1. [First](#first)"
assert lines[1] == "2. [Second](#second)"
assert lines[2] == "3. [Third](#third)"
def test_numbered_with_children(self):
headings = [(2, "Parent"), (3, "Child A"), (3, "Child B"), (2, "Next")]
toc = build_toc(headings, numbered=True, indent_size=3)
lines = toc.split("\n")
assert lines[0] == "1. [Parent](#parent)"
assert lines[1] == " - [Child A](#child-a)"
assert lines[2] == " - [Child B](#child-b)"
assert lines[3] == "2. [Next](#next)"
def test_numbered_deep_nesting(self):
headings = [(2, "L2"), (3, "L3"), (4, "L4")]
toc = build_toc(headings, numbered=True, indent_size=3)
lines = toc.split("\n")
assert lines[0] == "1. [L2](#l2)"
assert lines[1] == " - [L3](#l3)"
assert lines[2] == " - [L4](#l4)"
def test_numbered_duplicate_slugs(self):
headings = [(2, "Intro"), (2, "Intro")]
toc = build_toc(headings, numbered=True)
assert "1. [Intro](#intro)" in toc
assert "2. [Intro](#intro-1)" in toc
# ---------------------------------------------------------------------------
# Unified module: insert_toc_markers
# ---------------------------------------------------------------------------
class TestInsertTocMarkers:
def test_inserts_after_h1(self):
content = "# Title\n\n## A\n\n## B\n"
result = insert_toc_markers(content)
assert "<!-- toc -->" in result
assert "<!-- /toc -->" in result
assert "[A](#a)" in result
def test_replaces_between_markers(self):
content = "# Title\n\n<!-- toc -->\nold\n<!-- /toc -->\n\n## New\n"
result = insert_toc_markers(content)
assert "old" not in result
assert "[New](#new)" in result
def test_no_headings_returns_unchanged(self):
content = "# Only title\n\nSome text.\n"
assert insert_toc_markers(content) == content
def test_respects_max_level(self):
content = "# T\n\n## L2\n\n### L3\n\n#### L4\n"
result = insert_toc_markers(content, max_level=2)
assert "[L2]" in result
assert "[L3]" not in result
# ---------------------------------------------------------------------------
# Unified module: insert_toc_heading (blueprint-style)
# ---------------------------------------------------------------------------
class TestInsertTocHeading:
def test_inserts_heading_section(self):
content = "# Blueprint\n\n---\n\n## Rules\n\n## Checks\n"
result = insert_toc_heading(content)
assert "## Table of Contents" in result
assert "[Rules](#rules)" in result
assert "[Checks](#checks)" in result
def test_replaces_existing_toc_heading(self):
content = (
"# Blueprint\n\n"
"## Table of Contents\n\nold toc\n\n"
"## Rules\n\n## Checks\n"
)
result = insert_toc_heading(content)
assert "old toc" not in result
assert "[Rules](#rules)" in result
def test_skips_first_heading(self):
content = "# Title\n\n## Section\n"
result = insert_toc_heading(content)
# Title should not appear in TOC
assert "[Title]" not in result
assert "[Section](#section)" in result
def test_numbered_by_default(self):
content = "# Title\n\n## A\n\n## B\n"
result = insert_toc_heading(content)
assert "1. [A](#a)" in result
assert "2. [B](#b)" in result
def test_max_heading_level(self):
content = "# T\n\n## L2\n\n### L3\n"
result = insert_toc_heading(content, max_heading_level=2)
assert "[L2]" in result
assert "[L3]" not in result
def test_no_headings_returns_unchanged(self):
content = "# Only Title\n"
assert insert_toc_heading(content) == content
def test_frontmatter_handling(self):
content = "---\ntitle: Test\n---\n\n# Title\n\n---\n\n## Section\n"
result = insert_toc_heading(content)
assert "## Table of Contents" in result
assert "[Section](#section)" in result
# ---------------------------------------------------------------------------
# Unified module: validate_toc
# ---------------------------------------------------------------------------
class TestValidateToc:
def test_no_headings_no_errors(self):
content = "# Only Title\n\nSome text.\n"
result = validate_toc(content)
assert result["errors"] == []
assert result["warnings"] == []
def test_missing_toc(self):
content = "# Title\n\n## Section A\n\n## Section B\n"
result = validate_toc(content)
assert len(result["errors"]) == 1
assert result["errors"][0]["code"] == "toc-missing"
def test_valid_heading_based_toc(self):
content = (
"# Title\n\n"
"## Table of Contents\n\n"
"1. [Section A](#section-a)\n"
"2. [Section B](#section-b)\n\n"
"---\n\n"
"## Section A\n\n"
"## Section B\n"
)
result = validate_toc(content, max_heading_level=2)
assert result["errors"] == []
def test_valid_marker_based_toc(self):
content = (
"# Title\n\n"
"<!-- toc -->\n\n"
"- [Section A](#section-a)\n"
"- [Section B](#section-b)\n\n"
"<!-- /toc -->\n\n"
"## Section A\n\n"
"## Section B\n"
)
result = validate_toc(content)
assert result["errors"] == []
def test_valid_marker_based_toc_with_secondary_h1_sections(self):
content = (
"# Title\n\n"
"<!-- toc -->\n\n"
"- [Section A](#section-a)\n"
"- [Section B](#section-b)\n\n"
"<!-- /toc -->\n\n"
"# MUST HAVE\n"
"## Section A\n\n"
"# MUST NOT HAVE\n"
"## Section B\n"
)
result = validate_toc(content, max_heading_level=2)
assert result["errors"] == []
assert result["warnings"] == []
def test_broken_anchor(self):
content = (
"# Title\n\n"
"## Table of Contents\n\n"
"1. [Old Name](#old-name)\n\n"
"---\n\n"
"## New Name\n"
)
result = validate_toc(content, max_heading_level=2)
errors = result["errors"]
codes = [e["code"] for e in errors]
assert "toc-anchor-broken" in codes
assert "toc-heading-not-in-toc" in codes
def test_heading_not_in_toc(self):
content = (
"# Title\n\n"
"## Table of Contents\n\n"
"1. [Section A](#section-a)\n\n"
"---\n\n"
"## Section A\n\n"
"## Section B\n"
)
result = validate_toc(content, max_heading_level=2)
errors = result["errors"]
assert any(e["code"] == "toc-heading-not-in-toc" for e in errors)
missing = [e for e in errors if e["code"] == "toc-heading-not-in-toc"]
assert missing[0]["heading_text"] == "Section B"
def test_stale_toc_warning(self):
# Valid TOC but with wrong ordering/numbering
content = (
"# Title\n\n"
"## Table of Contents\n\n"
"1. [Section B](#section-b)\n"
"2. [Section A](#section-a)\n\n"
"---\n\n"
"## Section A\n\n"
"## Section B\n"
)
result = validate_toc(content, max_heading_level=2)
# No hard errors (all anchors are valid), but staleness warning
assert result["errors"] == []
assert any(w["code"] == "toc-stale" for w in result["warnings"])
def test_duplicate_headings_handled(self):
content = (
"# Title\n\n"
"## Table of Contents\n\n"
"1. [Intro](#intro)\n"
"2. [Intro](#intro-1)\n\n"
"---\n\n"
"## Intro\n\n"
"## Intro\n"
)
result = validate_toc(content, max_heading_level=2)
assert result["errors"] == []
def test_error_has_line_number(self):
content = "# Title\n\n## Section A\n\n## Section B\n"
result = validate_toc(content)
assert result["errors"][0]["line"] == 1
def test_broken_anchor_has_line_number(self):
content = (
"# Title\n\n"
"## Table of Contents\n\n"
"1. [Gone](#gone)\n\n"
"---\n\n"
"## Actual\n"
)
result = validate_toc(content, max_heading_level=2)
broken = [e for e in result["errors"] if e["code"] == "toc-anchor-broken"]
assert broken[0]["line"] == 5 # line of the broken TOC entry
def test_toml_comments_in_code_fence_ignored(self):
"""TOML comments (# ...) inside code fences must not be treated as headings."""
content = (
"# Title\n\n"
"## Table of Contents\n\n"
"1. [Section A](#section-a)\n"
"2. [Section B](#section-b)\n\n"
"---\n\n"
"## Section A\n\n"
"```toml\n"
"# This is a TOML comment, not a heading\n"
"[some_table]\n"
"key = \"value\"\n"
"```\n\n"
"## Section B\n"
)
result = validate_toc(content, max_heading_level=2)
assert result["errors"] == [], f"Unexpected errors: {result['errors']}"
assert result["warnings"] == [], f"Unexpected warnings: {result['warnings']}"
def test_toml_comments_in_fence_between_toc_and_heading(self):
"""Code fence with TOML comments between TOC and first heading."""
content = (
"# Title\n\n"
"## Table of Contents\n\n"
"1. [Overview](#overview)\n\n"
"```toml\n"
"# Artifact kind comment\n"
"artifact = \"TEST\"\n"
"```\n\n"
"---\n\n"
"## Overview\n\n"
"Content here.\n"
)
result = validate_toc(content, max_heading_level=2)
assert result["errors"] == [], f"Unexpected errors: {result['errors']}"
# ---------------------------------------------------------------------------
# cmd_validate_toc (integration)
# ---------------------------------------------------------------------------
class TestCmdValidateToc:
def test_pass(self, tmp_path: Path, capsys):
f = tmp_path / "good.md"
f.write_text(
"# Title\n\n"
"## Table of Contents\n\n"
"1. [A](#a)\n\n"
"---\n\n"
"## A\n",
encoding="utf-8",
)
rc = cmd_validate_toc([str(f), "--max-level", "2"])
assert rc == 0
out = json.loads(capsys.readouterr().out)
assert out["status"] == "PASS"
def test_fail_missing_toc(self, tmp_path: Path, capsys):
f = tmp_path / "bad.md"
f.write_text("# Title\n\n## Section\n", encoding="utf-8")
rc = cmd_validate_toc([str(f)])
assert rc == 2
out = json.loads(capsys.readouterr().out)
assert out["status"] == "FAIL"
assert out["error_count"] == 1
def test_missing_file(self, tmp_path: Path, capsys):
rc = cmd_validate_toc([str(tmp_path / "nope.md")])
assert rc == 2
out = json.loads(capsys.readouterr().out)
assert out["results"][0]["status"] == "ERROR"
def test_multiple_files(self, tmp_path: Path, capsys):
good = tmp_path / "good.md"
good.write_text(
"# T\n\n## Table of Contents\n\n1. [A](#a)\n\n---\n\n## A\n",
encoding="utf-8",
)
bad = tmp_path / "bad.md"
bad.write_text("# T\n\n## Section\n", encoding="utf-8")
rc = cmd_validate_toc([str(good), str(bad)])
assert rc == 2
out = json.loads(capsys.readouterr().out)
assert out["files_validated"] == 2
assert out["error_count"] == 1
def test_verbose_flag(self, tmp_path: Path, capsys):
f = tmp_path / "doc.md"
f.write_text(
"# T\n\n## Table of Contents\n\n1. [A](#a)\n\n---\n\n## A\n",
encoding="utf-8",
)
rc = cmd_validate_toc(["--verbose", "--max-level", "2", str(f)])
assert rc == 0
out = json.loads(capsys.readouterr().out)
assert "errors" in out["results"][0]
assert "warnings" in out["results"][0]
def test_warn_stale_toc(self, tmp_path: Path, capsys):
f = tmp_path / "stale.md"
f.write_text(
"# T\n\n"
"## Table of Contents\n\n"
"1. [B](#b)\n"
"2. [A](#a)\n\n"
"---\n\n"
"## A\n\n"
"## B\n",
encoding="utf-8",
)
rc = cmd_validate_toc(["--max-level", "2", str(f)])
assert rc == 0 # warnings don't cause failure
out = json.loads(capsys.readouterr().out)
assert out["status"] == "WARN"
assert out["warning_count"] >= 1
class TestCmdTocValidation:
"""cmd_toc post-validation and error-status paths."""
def test_validation_errors_set_status_and_return_2(self, tmp_path):
"""When _validate_toc returns errors, cmd_toc reports VALIDATION_FAIL and rc=2."""
md = tmp_path / "doc.md"
md.write_text("# Title\n\n## Sub\n\nText.\n", encoding="utf-8")
from unittest.mock import patch as _p
fake = {"errors": ["bad toc entry"], "warnings": []}
with _p("cypilot.commands.toc._validate_toc", return_value=fake):
import io, json
buf = io.StringIO()
from contextlib import redirect_stdout
with redirect_stdout(buf):
rc = cmd_toc([str(md)])
assert rc == 2
out = json.loads(buf.getvalue())
assert out["status"] == "VALIDATION_FAIL"
r = out["results"][0]
assert r["validation"]["status"] == "FAIL"
assert r["validation"]["errors"] == 1
def test_validation_warnings_only(self, tmp_path):
"""Warnings without errors ⇒ WARN validation, overall OK, rc=0."""
md = tmp_path / "doc.md"
md.write_text("# Title\n\n## Sub\n\nText.\n", encoding="utf-8")
from unittest.mock import patch as _p
fake = {"errors": [], "warnings": ["minor issue"]}
with _p("cypilot.commands.toc._validate_toc", return_value=fake):
import io, json
buf = io.StringIO()
from contextlib import redirect_stdout
with redirect_stdout(buf):
rc = cmd_toc([str(md)])
assert rc == 0
out = json.loads(buf.getvalue())
r = out["results"][0]
assert r["validation"]["status"] == "WARN"
def test_error_on_missing_file(self, tmp_path):
"""Processing a non-existent file produces ERROR status."""
import io, json
from contextlib import redirect_stdout
buf = io.StringIO()
with redirect_stdout(buf):
rc = cmd_toc([str(tmp_path / "nope.md")])
out = json.loads(buf.getvalue())
assert out["results"][0]["status"] == "ERROR"
# Single file error ⇒ overall ERROR, rc=1
assert out["status"] == "ERROR"
assert rc == 1
class TestArtifactKindConstraintsToc:
def test_toc_default_true(self):
from cypilot.utils.constraints import ArtifactKindConstraints
c = ArtifactKindConstraints(name=None, description=None, defined_id=[])
assert c.toc is True
def test_parse_toc_false(self):
from cypilot.utils.constraints import parse_kit_constraints
data = {
"TEST": {
"toc": False,
"identifiers": {},
}
}
kc, errs = parse_kit_constraints(data)
assert not errs
assert kc is not None
assert kc.by_kind["TEST"].toc is False
def test_parse_toc_absent_defaults_true(self):
from cypilot.utils.constraints import parse_kit_constraints
data = {
"TEST": {
"identifiers": {},
}
}
kc, errs = parse_kit_constraints(data)
assert not errs
assert kc is not None
assert kc.by_kind["TEST"].toc is True