-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathChecklistServiceBuildChecklistDataTests.cs
More file actions
1557 lines (1427 loc) · 63.3 KB
/
Copy pathChecklistServiceBuildChecklistDataTests.cs
File metadata and controls
1557 lines (1427 loc) · 63.3 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using Paranext.DataProvider.Checklists;
using Paranext.DataProvider.Checklists.Markers;
using Paranext.DataProvider.Projects;
using Paratext.Data;
using SIL.Scripture;
using ScriptureRange = Paranext.DataProvider.Checklists.ScriptureRange;
namespace TestParanextDataProvider.Checklists;
/// <summary>
/// RED-phase contract and outer-acceptance tests for CAP-006
/// (<c>ChecklistService.BuildChecklistData</c> — end-to-end orchestration).
///
/// <para>
/// These tests will NOT compile until the implementer adds
/// <c>Paranext.DataProvider.Checklists.ChecklistService.BuildChecklistData(
/// ChecklistRequest, CancellationToken)</c>. The
/// compile error is the first layer of the RED signal; the test assertion
/// failures (after a stub body lands) are the second. Matches the
/// CAP-003 / CAP-004 / CAP-005 RED precedents.
/// </para>
///
/// <para>
/// Per strategic-plan-backend.md §CAP-006, this capability uses
/// <b>Outside-In TDD</b>: the outer golden-master replays (gm-001,
/// gm-004) drive pipeline composition; focused unit tests pin
/// the specific invariants (INV-002, INV-010, INV-012, VAL-003,
/// VAL-004, INV-C15) and the edge-case scenarios (TS-053, TS-054,
/// TS-062, TS-070).
/// </para>
///
/// <para>
/// <b>Scope note — gm-014 / gm-019 not replayed here.</b> Those golden
/// masters were captured with <c>checklistType=Verses</c> (see their
/// respective <c>input.json</c>), but per data-contracts.md §4.1
/// "Checklist type is implicitly 'Markers' for this feature" CAP-006 only
/// implements the Markers path. TS-068 (duplicate verses) stays covered
/// through CAP-005's row-alignment unit tests.
/// </para>
///
/// <para>
/// <b>Scope note — EditLinkItem.</b> CAP-012 owns the inline edit-link
/// gate. These CAP-006 tests therefore do NOT assert on the presence or
/// absence of <see cref="EditLinkItem"/> content items. They assert only
/// on the outer shape (<see cref="ChecklistResult.Rows"/>,
/// <see cref="ChecklistRow.Cells"/>, <see cref="ChecklistRow.IsMatch"/>,
/// <see cref="ChecklistResult.ExcludedCount"/>,
/// <see cref="ChecklistResult.Truncated"/>,
/// <see cref="ChecklistResult.ColumnHeaders"/>,
/// <see cref="ChecklistResult.ColumnProjectIds"/>,
/// <see cref="ChecklistResult.EmptyResultMessage"/>).
/// </para>
///
/// <para>
/// <b>Signature note.</b> data-contracts.md §4.1 and strategic-plan-backend.md
/// differ on the method signature: the former lists
/// <c>Task<ChecklistResult> BuildChecklistDataAsync(ChecklistRequest,
/// CancellationToken)</c>; the latter lists the sync
/// <c>ChecklistResult BuildChecklistData(ChecklistRequest,
/// CancellationToken)</c>. These tests follow the
/// strategic-plan signature; if GREEN adopts the async shape, the tests
/// will be touched up to <c>await</c> the result. The compile-fail RED
/// signal is robust to either choice.
/// </para>
///
/// Traceability:
/// - Capability: CAP-006
/// - Behaviors: BHV-100 (factory — transitive), BHV-101 (main),
/// BHV-118 (First/Last VerseRef — transitive), BHV-121
/// (HasSameParagraphStructure — transitive)
/// - Extractions: EXT-001 (CreateDataSource), EXT-002 (BuildChecklistData),
/// EXT-015 (GetChecklistData wrapper with maxRows)
/// - Invariants: INV-002 (single-column IsMatch=true), INV-010
/// (hideMatches tracking), INV-012 (max rows 5000),
/// VAL-003 (start 1:1 -> 1:0), VAL-004 (unknown ChecklistType),
/// INV-C15 (ColumnProjectIds parallel to ColumnHeaders)
/// - Scenarios: TS-001, TS-004, TS-005, TS-006, TS-049, TS-053, TS-054,
/// TS-062, TS-070, and (related / emergent) TS-002, TS-003, TS-032, TS-033
/// - Golden Masters: gm-001 (primary outer acceptance), gm-004 (secondary)
/// - Contract: data-contracts.md §4.1 (BuildChecklistData),
/// §3.1 (ChecklistResult), §3.2 (ChecklistRow), §3.3 (ChecklistCell)
/// - PT9 source: Paratext/Checklists/CLDataSource.cs:97-185 (BuildRows)
/// </summary>
[TestFixture]
internal class ChecklistServiceBuildChecklistDataTests : PapiTestBase
{
// ---------------------------------------------------------------------
// Shared helpers — reuse DummyScrText + LocalParatextProjects pattern
// ---------------------------------------------------------------------
/// <summary>
/// The canonical EXO USFM captured in gm-001's <c>input-EXO.usfm</c>.
/// Single project, two verses, three paragraph markers (\p, \q, \q2).
/// </summary>
private const string Gm001ExoUsfm =
@"\id EXO \c 20 \p \v 1 one. \v 2 two, \q poetry \q2 indented poetry";
/// <summary>gm-004's text1 EXO USFM (matches text1 captured input).</summary>
private const string Gm004Text1ExoUsfm =
@"\id EXO \c 20 \p \v 1 one. \v 2 two, \q poetry \q2 indented poetry \p \v 3 three";
/// <summary>gm-004's text2 EXO USFM (matches text2 captured input).</summary>
private const string Gm004Text2ExoUsfm =
@"\id EXO \c 20 \p \v 1 uno. \v 2 dos, \p more text \q prose \q2 \v 3 indented prose";
/// <summary>
/// Registers a <see cref="DummyScrText"/> as a discoverable project so
/// <see cref="LocalParatextProjects.GetParatextProject"/> resolves its
/// HexId. Mirrors the pattern used across the existing Projects tests
/// (see <c>c-sharp-tests/Projects/ParatextDataProviderTests.cs:24</c>).
/// </summary>
private DummyScrText RegisterDummyProject(string usfmPerBook, int bookNum = 2)
{
var scrText = new DummyScrText();
// gm-001 / gm-004 use the poetry-style paragraph markers (\q, \q1, \q2)
// which DummyScrStylesheet defines only as scCharacterStyle. We must
// upgrade them to scParagraphStyle via reflection — same approach as
// CAP-003's ChecklistServiceTokenExtractionTests.PoetryStylesheet.
UpgradePoetryMarkersToParagraphStyle(scrText);
scrText.PutText(bookNum, 0, false, usfmPerBook, null);
ParatextProjects.FakeAddProject(CreateProjectDetails(scrText), scrText);
return scrText;
}
/// <summary>
/// Replaces the existing character-style <c>q / q1 / q2 / b</c> tags on
/// the DummyScrStylesheet with paragraph-style tags. gm-001 / gm-004 use
/// these as paragraph markers. Mirrors the approach in CAP-003's test
/// file; this helper additionally <i>replaces</i> the existing tag so the
/// stylesheet's <c>scCharacterStyle</c> entry (from DummyScrStylesheet)
/// is overridden.
/// </summary>
private static void UpgradePoetryMarkersToParagraphStyle(DummyScrText scrText)
{
// DummyScrStylesheet defines \v with a huge OccursUnder including
// q/q1/q2 as allowable parents of \v — so we just need to ADD
// paragraph-style tags for the Markers checklist's ParagraphMarkers
// query (BHV-102: scParagraphStyle filter).
var stylesheet = scrText.DefaultStylesheet;
foreach (var marker in new[] { "q", "q1", "q2", "b" })
{
AddPoetryTag(stylesheet, marker);
}
}
private static void AddPoetryTag(ScrStylesheet stylesheet, string marker)
{
var tag = new ScrTag
{
Marker = marker,
TextProperties =
TextProperties.scParagraph
| TextProperties.scPublishable
| TextProperties.scVernacular
| TextProperties.scPoetic,
TextType = ScrTextType.scVerseText,
StyleType = ScrStyleType.scParagraphStyle,
OccursUnder = "c",
};
var addTagInternal = typeof(ScrStylesheet).GetMethod(
"AddTagInternal",
BindingFlags.Instance | BindingFlags.NonPublic
);
if (addTagInternal == null)
{
throw new InvalidOperationException(
"ScrStylesheet.AddTagInternal not found via reflection; "
+ "API has changed and this test helper must be updated."
);
}
addTagInternal.Invoke(stylesheet, new object[] { tag });
}
/// <summary>
/// Builds a default request for a single-project Markers checklist over
/// EXO 20:1..EXO 20:20. Callers override individual fields via
/// <c>with</c>-expressions.
/// </summary>
private static ChecklistRequest BuildRequest(
string activeProjectId,
IReadOnlyList<string>? comparativeTextIds = null,
ScriptureRange? verseRange = null,
bool hideMatches = false,
bool showVerseText = false,
string equivalentMarkers = "",
string markerFilter = ""
)
{
verseRange ??= new ScriptureRange(
new VerseRef("EXO", "20", "1", ScrVers.English),
new VerseRef("EXO", "20", "20", ScrVers.English)
);
return new ChecklistRequest(
ProjectId: activeProjectId,
ComparativeTextIds: comparativeTextIds ?? Array.Empty<string>(),
MarkerSettings: new MarkerSettings(equivalentMarkers, markerFilter),
VerseRange: verseRange,
HideMatches: hideMatches,
ShowVerseText: showVerseText
);
}
// =====================================================================
// Group A — Happy path & single column (TS-001, TS-005, INV-002)
// =====================================================================
[Test]
[Category("Contract")]
[Property("CapabilityId", "CAP-006")]
[Property("Contract", "BuildChecklistData")]
[Property("ScenarioId", "TS-001")]
[Property("BehaviorId", "BHV-101")]
public void BuildChecklistData_SingleProjectMarkers_ReturnsRowsWithMarkerParagraphs()
{
// TS-001: Single ScrText with EXO containing \p, \q, \q2 produces rows
// whose cells carry paragraphs with those markers.
var scrText = RegisterDummyProject(Gm001ExoUsfm);
var request = BuildRequest(activeProjectId: scrText.Guid.ToString());
ChecklistResult result = ChecklistService.BuildChecklistData(
request,
CancellationToken.None
);
Assert.That(result, Is.Not.Null);
Assert.That(result.Rows, Is.Not.Null);
Assert.That(result.Rows, Is.Not.Empty, "at least one row expected for \\p + \\q + \\q2");
// Collect every paragraph marker across every cell of every row.
var markers = result
.Rows.SelectMany(r => r.Cells)
.SelectMany(c => c.Paragraphs)
.Select(p => p.Marker)
.ToList();
Assert.That(markers, Does.Contain("p"), "\\p paragraph marker must appear");
Assert.That(markers, Does.Contain("q"), "\\q paragraph marker must appear");
Assert.That(markers, Does.Contain("q2"), "\\q2 paragraph marker must appear");
}
[Test]
[Category("Contract")]
[Property("CapabilityId", "CAP-006")]
[Property("Contract", "BuildChecklistData")]
[Property("ScenarioId", "TS-031")]
[Property("BehaviorId", "BHV-604")]
[Property("GoldenMaster", "gm-016")]
public void BuildChecklistData_ShowVerseTextWithCharacterStyle_PreservesCharacterStyleAttribution()
{
// T-B-6 / Rolf commitment #3124021961 — BHV-604 / gm-016 integration
// test. When showVerseText=true and USFM contains a character style
// (\em...\em*) inside a paragraph, the resulting TextItem items must
// include the character-style attribution on a distinct sub-item
// (TextItem.CharacterStyle == "em") for the styled run while the
// surrounding text carries CharacterStyle == null. Pins the behaviour
// end-to-end through the orchestrator (not just at the
// CAP-003 leaf level) so a regression that drops the CharacterStyle
// field on the wire cannot hide behind a passing golden master.
const string usfm =
@"\id EXO \c 20 \p \v 1 one. \v 2 two, \q poetry \q2 indented \em poetry\em* ";
var scrText = RegisterDummyProject(usfm);
var request = BuildRequest(activeProjectId: scrText.Guid.ToString(), showVerseText: true);
ChecklistResult result = ChecklistService.BuildChecklistData(
request,
CancellationToken.None
);
// Collect all TextItems across all paragraphs so we can inspect the
// character-style attribution directly.
var textItems = result
.Rows.SelectMany(r => r.Cells)
.SelectMany(c => c.Paragraphs)
.SelectMany(p => p.Items)
.OfType<TextItem>()
.ToList();
Assert.That(
textItems,
Is.Not.Empty,
"showVerseText=true must emit TextItems alongside the marker attribution"
);
// Partition by CharacterStyle field — null for plain text, non-null
// for character-style runs. Both flavours must be present.
var styledItems = textItems.Where(t => t.CharacterStyle != null).ToList();
var plainItems = textItems.Where(t => t.CharacterStyle == null).ToList();
Assert.That(
plainItems,
Is.Not.Empty,
"plain (non-styled) TextItems must be present (marker + surrounding text)"
);
Assert.That(
styledItems,
Is.Not.Empty,
"BHV-604 / gm-016 — \\em character-style run must surface as a TextItem "
+ "with CharacterStyle=\"em\""
);
Assert.That(
styledItems.Select(t => t.CharacterStyle).Distinct(),
Is.EqualTo(new[] { "em" }),
"BHV-604 — the only character style emitted here is \\em"
);
Assert.That(
styledItems.Any(t => t.Text.Contains("poetry")),
Is.True,
"BHV-604 — the \\em-styled text \"poetry\" must carry CharacterStyle=\"em\""
);
}
[Test]
[Category("Contract")]
[Property("CapabilityId", "CAP-006")]
[Property("Contract", "BuildChecklistData")]
[Property("ScenarioId", "TS-005")]
[Property("BehaviorId", "BHV-101")]
[Property("Invariant", "INV-002")]
public void BuildChecklistData_SingleColumn_AllRowsIsMatch_True()
{
// TS-005 / INV-002: Single-column checklists mark every row IsMatch=true
// (no difference highlighting is meaningful with only one column).
var scrText = RegisterDummyProject(Gm001ExoUsfm);
var request = BuildRequest(activeProjectId: scrText.Guid.ToString());
ChecklistResult result = ChecklistService.BuildChecklistData(
request,
CancellationToken.None
);
Assume.That(result.Rows, Is.Not.Empty, "precondition — rows produced");
foreach (var row in result.Rows)
{
Assert.That(
row.IsMatch,
Is.True,
$"INV-002 — single-column row must be IsMatch=true (row FirstRef={row.FirstRef})"
);
}
}
[Test]
[Category("Contract")]
[Property("CapabilityId", "CAP-006")]
[Property("Contract", "BuildChecklistData")]
[Property("BehaviorId", "BHV-101")]
[Property("Invariant", "INV-010")]
public void BuildChecklistData_SingleColumn_ExcludedCountIsZero()
{
// INV-010 edge: single-column checklists never hide anything, so
// ExcludedCount must be 0 regardless of the hideMatches flag.
var scrText = RegisterDummyProject(Gm001ExoUsfm);
var request = BuildRequest(activeProjectId: scrText.Guid.ToString(), hideMatches: true);
ChecklistResult result = ChecklistService.BuildChecklistData(
request,
CancellationToken.None
);
Assert.That(
result.ExcludedCount,
Is.EqualTo(0),
"single-column checklist has nothing to hide; ExcludedCount stays 0"
);
}
// =====================================================================
// Group B — HideMatches filter (TS-004, INV-010)
// =====================================================================
[Test]
[Category("Contract")]
[Property("CapabilityId", "CAP-006")]
[Property("Contract", "BuildChecklistData")]
[Property("ScenarioId", "TS-004")]
[Property("BehaviorId", "BHV-101")]
[Property("Invariant", "INV-010")]
public void BuildChecklistData_TwoColumnsHideMatches_RemovesMatchingRows()
{
// TS-004 / INV-010: With one matching verse (v1 \p in both) and two
// non-matching verses (v2 + v3 — per gm-004 capture), hideMatches=true
// yields only the 2 non-matching rows with ExcludedCount=1.
var active = RegisterDummyProject(Gm004Text1ExoUsfm);
var compare = RegisterDummyProject(Gm004Text2ExoUsfm);
var request = BuildRequest(
activeProjectId: active.Guid.ToString(),
comparativeTextIds: new[] { compare.Guid.ToString() },
hideMatches: true
);
ChecklistResult result = ChecklistService.BuildChecklistData(
request,
CancellationToken.None
);
Assert.That(
result.Rows.Count,
Is.EqualTo(2),
"two non-matching rows expected after hideMatches filtering"
);
Assert.That(
result.ExcludedCount,
Is.EqualTo(1),
"one matching row removed -> ExcludedCount=1 (INV-010)"
);
foreach (var row in result.Rows)
{
Assert.That(
row.IsMatch,
Is.False,
"every remaining row must be non-matching after hideMatches"
);
}
}
[Test]
[Category("Contract")]
[Property("CapabilityId", "CAP-006")]
[Property("Contract", "BuildChecklistData")]
[Property("ScenarioId", "TS-004")]
[Property("BehaviorId", "BHV-101")]
[Property("Invariant", "INV-010")]
public void BuildChecklistData_HideMatchesFalse_RetainsAllRows()
{
// TS-004 inverse: hideMatches=false keeps all rows (including matches)
// and ExcludedCount stays 0.
var active = RegisterDummyProject(Gm004Text1ExoUsfm);
var compare = RegisterDummyProject(Gm004Text2ExoUsfm);
var request = BuildRequest(
activeProjectId: active.Guid.ToString(),
comparativeTextIds: new[] { compare.Guid.ToString() },
hideMatches: false
);
ChecklistResult result = ChecklistService.BuildChecklistData(
request,
CancellationToken.None
);
Assert.That(
result.Rows.Count,
Is.EqualTo(3),
"all 3 rows retained -> 1 match (EXO 20:1) + 2 non-match (EXO 20:2, 20:3)"
);
Assert.That(
result.ExcludedCount,
Is.EqualTo(0),
"nothing hidden when hideMatches=false -> ExcludedCount=0"
);
}
// =====================================================================
// Group C — Verse-range start adjustment (TS-006, VAL-003)
// =====================================================================
[Test]
[Category("Contract")]
[Property("CapabilityId", "CAP-006")]
[Property("Contract", "BuildChecklistData")]
[Property("ScenarioId", "TS-006")]
[Property("BehaviorId", "BHV-101")]
[Property("ValidationRule", "VAL-003")]
public void BuildChecklistData_VerseRangeStartAtChapter1Verse1_AdjustsToVerse0()
{
// VAL-003: When request.VerseRange.start == (GEN 1:1), it is silently
// adjusted to (GEN 1:0) so introductory material (\ip at verse 0) is
// included. We seed \ip at position before \v 1 and assert it comes
// through in the result.
const string usfm = @"\id GEN \c 1 \ip An introduction. \p \v 1 In the beginning.";
var scrText = RegisterDummyProject(usfm, bookNum: 1);
var request = BuildRequest(
activeProjectId: scrText.Guid.ToString(),
verseRange: new ScriptureRange(
new VerseRef("GEN", "1", "1", ScrVers.English),
new VerseRef("GEN", "1", "20", ScrVers.English)
)
);
ChecklistResult result = ChecklistService.BuildChecklistData(
request,
CancellationToken.None
);
var markers = result
.Rows.SelectMany(r => r.Cells)
.SelectMany(c => c.Paragraphs)
.Select(p => p.Marker)
.ToList();
Assert.That(
markers,
Does.Contain("ip"),
"VAL-003 — start ref 1:1 must be adjusted to 1:0 so \\ip at verse 0 is included"
);
}
[Test]
[Category("Contract")]
[Property("CapabilityId", "CAP-006")]
[Property("Contract", "BuildChecklistData")]
[Property("BehaviorId", "BHV-101")]
[Property("ValidationRule", "VAL-003")]
public void BuildChecklistData_VerseRangeStartAtChapter1Verse2_DoesNotAdjust()
{
// VAL-003 inverse boundary: starts other than 1:1 are NOT adjusted.
// When start=1:2, any \ip at verse 0 must be excluded.
const string usfm =
@"\id GEN \c 1 \ip An introduction. \p \v 1 In the beginning. \v 2 continuing.";
var scrText = RegisterDummyProject(usfm, bookNum: 1);
var request = BuildRequest(
activeProjectId: scrText.Guid.ToString(),
verseRange: new ScriptureRange(
new VerseRef("GEN", "1", "2", ScrVers.English),
new VerseRef("GEN", "1", "20", ScrVers.English)
)
);
ChecklistResult result = ChecklistService.BuildChecklistData(
request,
CancellationToken.None
);
var markers = result
.Rows.SelectMany(r => r.Cells)
.SelectMany(c => c.Paragraphs)
.Select(p => p.Marker)
.ToList();
Assert.That(
markers,
Does.Not.Contain("ip"),
"VAL-003 is 1:1-specific — start=1:2 must not pull in the \\ip at verse 0"
);
}
[Test]
[Category("Contract")]
[Property("CapabilityId", "CAP-006")]
[Property("Contract", "BuildChecklistData")]
public void BuildChecklistData_VerseRangeEndOmitted_ScansSingleVerseAtStart()
{
// Platform ScriptureRange contract (lib/papi-dts):
// "If not provided, then only the verse indicated by start is included."
// Verify the checklist honors that contract — passing { Start, End: null }
// must narrow to a single-verse range, NOT fall back to the project bounds.
const string usfm = @"\id GEN \c 1 \v 1 alpha \p \v 2 bravo \p \v 3 charlie \p \v 4 delta";
var scrText = RegisterDummyProject(usfm, bookNum: 1);
var request = BuildRequest(
activeProjectId: scrText.Guid.ToString(),
verseRange: new ScriptureRange(
Start: new VerseRef("GEN", "1", "2", ScrVers.English),
End: null
),
showVerseText: true
);
ChecklistResult result = ChecklistService.BuildChecklistData(
request,
CancellationToken.None
);
var verseTexts = result
.Rows.SelectMany(r => r.Cells)
.SelectMany(c => c.Paragraphs)
.SelectMany(p => p.Items)
.OfType<TextItem>()
.Select(t => t.Text.Trim())
.Where(t => !string.IsNullOrEmpty(t))
.ToList();
// Only verse 2 should appear; verses 1, 3, 4 must be excluded.
Assert.That(
verseTexts,
Has.Some.Contains("bravo"),
"End == null must include the verse at Start (GEN 1:2)"
);
Assert.That(
verseTexts,
Has.None.Contains("alpha"),
"End == null must NOT scan the whole project (verse 1 should be excluded)"
);
Assert.That(
verseTexts,
Has.None.Contains("charlie"),
"End == null must NOT scan past the Start verse (verse 3 should be excluded)"
);
Assert.That(
verseTexts,
Has.None.Contains("delta"),
"End == null must NOT scan past the Start verse (verse 4 should be excluded)"
);
}
// =====================================================================
// Group D — Max rows truncation (TS-049, INV-012)
// =====================================================================
[Test]
[Category("Contract")]
[Property("CapabilityId", "CAP-006")]
[Property("Contract", "BuildChecklistData")]
[Property("BehaviorId", "BHV-101")]
[Property("Invariant", "INV-012")]
public void BuildChecklistData_ResultUnder5000Rows_TruncatedFalse()
{
// INV-012 negative direction: a small result (well under 5000) must
// have Truncated=false.
var scrText = RegisterDummyProject(Gm001ExoUsfm);
var request = BuildRequest(activeProjectId: scrText.Guid.ToString());
ChecklistResult result = ChecklistService.BuildChecklistData(
request,
CancellationToken.None
);
Assert.That(
result.Truncated,
Is.False,
"small result (<5000 rows) must not be marked Truncated"
);
Assert.That(
result.Rows.Count,
Is.LessThanOrEqualTo(5000),
"INV-012 upper bound — row count must never exceed 5000"
);
}
[Test]
[Category("GoldenMaster")]
[Property("CapabilityId", "CAP-006")]
[Property("Contract", "BuildChecklistData")]
[Property("ScenarioId", "TS-049")]
[Property("BehaviorId", "BHV-101")]
[Property("Invariant", "INV-012")]
public void BuildChecklistData_ResultExceeds5000Rows_TruncatedFlagSet()
{
// INV-012 positive direction: if the pipeline would produce >5000
// rows, the result must be truncated at 5000 and Truncated=true.
//
// Seed the project with enough \p paragraphs to cross the threshold.
// Strategy: many chapters, many verses-per-chapter with \p per verse.
// We target ~5500 paragraphs in a single book across many chapters.
var usfm = new System.Text.StringBuilder(@"\id GEN");
// 110 chapters * 50 paragraphs/chapter = 5500 paragraphs
for (int chapter = 1; chapter <= 110; chapter++)
{
usfm.Append($" \\c {chapter}");
for (int verse = 1; verse <= 50; verse++)
{
usfm.Append($" \\p \\v {verse} content.");
}
}
var scrText = RegisterDummyProject(usfm.ToString(), bookNum: 1);
var request = BuildRequest(
activeProjectId: scrText.Guid.ToString(),
verseRange: new ScriptureRange(
new VerseRef("GEN", "1", "1", ScrVers.English),
new VerseRef("GEN", "110", "50", ScrVers.English)
)
);
ChecklistResult result = ChecklistService.BuildChecklistData(
request,
CancellationToken.None
);
Assert.That(
result.Truncated,
Is.True,
"INV-012 — producing >5000 rows must set Truncated=true"
);
Assert.That(
result.Rows.Count,
Is.EqualTo(5000),
"INV-012 — truncated result must have exactly 5000 rows"
);
}
// =====================================================================
// Group E — CancellationToken (TS-062)
// =====================================================================
[Test]
[Category("Contract")]
[Property("CapabilityId", "CAP-006")]
[Property("Contract", "BuildChecklistData")]
[Property("ScenarioId", "TS-062")]
[Property("BehaviorId", "BHV-101")]
public void BuildChecklistData_CancellationRequested_Throws()
{
// TS-062: PT10 replaces PT9's Progress.Mgr.EndProgressIfCancelled with
// CancellationToken. A cancelled token passed to BuildChecklistData
// must surface via OperationCanceledException (standard .NET pattern
// for ct.ThrowIfCancellationRequested / ct.IsCancellationRequested).
//
// NOTE: GREEN may instead choose to return a structured error result
// (ChecklistResultError with code "CANCELLED" per data-contracts.md
// §4.1 error table). In that case this test will be adjusted to
// match the chosen contract — RED compile-fail is robust to either.
var scrText = RegisterDummyProject(Gm001ExoUsfm);
var request = BuildRequest(activeProjectId: scrText.Guid.ToString());
using var cts = new CancellationTokenSource();
cts.Cancel();
Assert.That(
() => ChecklistService.BuildChecklistData(request, cts.Token),
Throws.InstanceOf<OperationCanceledException>(),
"TS-062 — cancelled token must surface as OperationCanceledException"
);
}
// =====================================================================
// Group F — Factory & unknown checklist type (TS-053, TS-054, BHV-100, VAL-004)
// =====================================================================
[Test]
[Category("Contract")]
[Property("CapabilityId", "CAP-006")]
[Property("Contract", "BuildChecklistData")]
[Property("ScenarioId", "TS-053")]
[Property("BehaviorId", "BHV-100")]
public void BuildChecklistData_ChecklistTypeMarkers_ComposesMarkersPipeline()
{
// TS-053 (revised post-UX-2 finding #13): the Markers pipeline is
// composed under the hood. We observe BHV-103 indirectly: with
// showVerseText=true, the original verse-text Items (verse markers
// and text fragments produced by the cell builder) flow through
// MarkersDataSource.PostProcessParagraph unchanged — they are NOT
// dropped, and they are NOT prefixed with a redundant `\marker`
// TextItem (the UI renders the marker from paragraph.Marker).
//
// If the service did NOT route through MarkersDataSource, the
// showVerseText flag would have no effect; the paragraph items
// would always be present. With showVerseText=true that's
// indistinguishable, so instead we assert the new INV-004 contract:
// paragraph.Marker is set and Items contain only content items
// (verse markers / text), never the prepended `\marker` TextItem.
var scrText = RegisterDummyProject(Gm001ExoUsfm);
var request = BuildRequest(activeProjectId: scrText.Guid.ToString(), showVerseText: true);
ChecklistResult result = ChecklistService.BuildChecklistData(
request,
CancellationToken.None
);
Assume.That(result.Rows, Is.Not.Empty, "precondition — rows produced");
foreach (var row in result.Rows)
foreach (var cell in row.Cells)
foreach (var paragraph in cell.Paragraphs)
{
Assert.That(
paragraph.Marker,
Is.Not.Null.And.Not.Empty,
"INV-004 — paragraph.Marker carries the marker name (UI renders the backslash prefix)"
);
// INV-004 (revised): the redundant "\\" + Marker TextItem is no
// longer prepended. Verify no item in the list starts with the
// backslash-prefix marker as its sole text payload.
var backslashMarker = "\\" + paragraph.Marker;
foreach (var item in paragraph.Items)
{
if (item is TextItem text)
{
Assert.That(
text.Text,
Is.Not.EqualTo(backslashMarker),
$"INV-004 (revised) — Items must not contain the prepended marker TextItem '{backslashMarker}'"
);
}
}
}
}
[Test]
[Category("Contract")]
[Property("CapabilityId", "CAP-006")]
[Property("Contract", "BuildChecklistData")]
[Property("ScenarioId", "TS-054")]
[Property("BehaviorId", "BHV-100")]
[Property("ValidationRule", "VAL-004")]
[Ignore(
"VAL-004 tracks invalid ChecklistType handling. ChecklistRequest (data-contracts §2.1) has no ChecklistType field — the current API is implicitly Markers-only. Kept as a placeholder so traceability matrix records VAL-004; remove Ignore if GREEN exposes a ChecklistType surface that can be stress-tested."
)]
public void BuildChecklistData_UnknownChecklistType_ThrowsInvalidOperationException()
{
// VAL-004 placeholder. See [Ignore] rationale above — the test is
// always skipped via [Ignore] so this body is never executed.
Assert.Pass("placeholder — see [Ignore] rationale");
}
// =====================================================================
// Group G — Empty / edge inputs (TS-070)
// =====================================================================
[Test]
[Category("Contract")]
[Property("CapabilityId", "CAP-006")]
[Property("Contract", "BuildChecklistData")]
[Property("ScenarioId", "TS-070")]
[Property("BehaviorId", "BHV-101")]
public void BuildChecklistData_ProjectIdNotRegistered_SurfacesResolutionError()
{
// TS-070 analog: unresolvable projectId. The strategic plan
// documents PROJECT_NOT_FOUND as a structured error code, but the
// PT10 resolver (ScrTextCollection.GetById) throws on unknown IDs.
// Either the service catches and wraps (structured error) OR the
// exception bubbles out. We assert that the thrown exception is
// NOT a NotImplementedException (which would mean the implementation
// hasn't landed yet — we reject that false-green path), AND is not
// null (something must indicate the error).
//
// GREEN note: if the implementer wraps the resolver exception into a
// structured result (ChecklistResultError with code "PROJECT_NOT_FOUND"),
// this test will be adjusted to inspect the structured error instead
// of asserting Throws.
const string missingProjectId = "0123456789abcdef0123456789abcdef01234567";
var request = BuildRequest(
activeProjectId: missingProjectId // not registered
);
Exception? caught = null;
try
{
ChecklistService.BuildChecklistData(request, CancellationToken.None);
}
catch (Exception ex)
{
caught = ex;
}
Assert.That(
caught,
Is.Not.Null,
"TS-070 / PROJECT_NOT_FOUND — unresolvable projectId must surface as an error"
);
Assert.That(
caught,
Is.Not.InstanceOf<NotImplementedException>(),
"TS-070 — NotImplementedException is a RED-stub artifact, not the expected resolution error. "
+ "GREEN implementer must actively reject unknown projectIds (either throw a PT9-style "
+ "resolver exception or return a structured PROJECT_NOT_FOUND error)."
);
Assert.That(
caught!.Message,
Does.Contain(missingProjectId),
"TS-070 — the exception message must reference the missing projectId so the "
+ "failure is self-diagnosing (not just a generic \"project not found\" opaque error)."
);
}
[Test]
[Category("Contract")]
[Property("CapabilityId", "CAP-006")]
[Property("Contract", "BuildChecklistData")]
[Property("BehaviorId", "BHV-101")]
[Property("Invariant", "INV-008")]
public void BuildChecklistData_VerseRangeOutsideBooksPresentSet_ProducesEmptyResultWithMessage()
{
// Edge: verse range does not intersect any book in BooksPresentSet, so
// no books are iterated and no rows are produced. INV-008 requires an
// EmptyResultMessage in that case.
var scrText = RegisterDummyProject(Gm001ExoUsfm); // registers EXO (book 2)
var request = BuildRequest(
activeProjectId: scrText.Guid.ToString(),
verseRange: new ScriptureRange(
new VerseRef("JHN", "1", "1", ScrVers.English),
new VerseRef("JHN", "1", "20", ScrVers.English)
)
);
ChecklistResult result = ChecklistService.BuildChecklistData(
request,
CancellationToken.None
);
Assert.That(result.Rows, Is.Empty, "range outside registered books -> no rows");
Assert.That(
result.EmptyResultMessage,
Is.Not.Null,
"INV-008 — empty results must carry an EmptyResultMessage"
);
}
// =====================================================================
// Group H — INV-C15 ColumnProjectIds parallel to ColumnHeaders
// =====================================================================
[Test]
[Category("Contract")]
[Property("CapabilityId", "CAP-006")]
[Property("Contract", "BuildChecklistData")]
[Property("BehaviorId", "BHV-101")]
[Property("Invariant", "INV-C15")]
public void BuildChecklistData_SingleProject_ColumnProjectIdsContainsOnlyRequestProjectId()
{
// INV-C15: With one active project, ColumnHeaders and ColumnProjectIds
// both have exactly one entry, and ColumnProjectIds[0] equals the
// request's ProjectId.
var scrText = RegisterDummyProject(Gm001ExoUsfm);
var request = BuildRequest(activeProjectId: scrText.Guid.ToString());
ChecklistResult result = ChecklistService.BuildChecklistData(
request,
CancellationToken.None
);
Assert.That(
result.ColumnHeaders.Count,
Is.EqualTo(1),
"single project -> one column header"
);
Assert.That(
result.ColumnProjectIds.Count,
Is.EqualTo(result.ColumnHeaders.Count),
"INV-C15 — ColumnProjectIds.Count must equal ColumnHeaders.Count"
);
Assert.That(
result.ColumnProjectIds[0],
Is.EqualTo(request.ProjectId),
"INV-C15 — ColumnProjectIds[0] must equal request.ProjectId"
);
}
[Test]
[Category("Contract")]
[Property("CapabilityId", "CAP-006")]
[Property("Contract", "BuildChecklistData")]
[Property("BehaviorId", "BHV-101")]
[Property("Invariant", "INV-C15")]
public void BuildChecklistData_ActiveProjectPlusComparative_ColumnProjectIdsOrderMatches()
{
// INV-C15 with 2 columns: active project at index 0, comparative at
// index 1 in request order.
var active = RegisterDummyProject(Gm004Text1ExoUsfm);
var compare = RegisterDummyProject(Gm004Text2ExoUsfm);
var request = BuildRequest(
activeProjectId: active.Guid.ToString(),
comparativeTextIds: new[] { compare.Guid.ToString() }
);
ChecklistResult result = ChecklistService.BuildChecklistData(
request,
CancellationToken.None
);
Assert.That(
result.ColumnHeaders.Count,
Is.EqualTo(2),
"active + 1 comparative -> 2 column headers"
);
Assert.That(
result.ColumnProjectIds.Count,
Is.EqualTo(result.ColumnHeaders.Count),
"INV-C15 — ColumnProjectIds.Count must equal ColumnHeaders.Count"
);
Assert.That(
result.ColumnProjectIds[0],
Is.EqualTo(active.Guid.ToString()),
"INV-C15 — active project must be at index 0"
);
Assert.That(
result.ColumnProjectIds[1],
Is.EqualTo(compare.Guid.ToString()),
"INV-C15 — comparative must follow the active project in request order"
);
}
// =====================================================================
// Group I — Outer acceptance gm-001 replay (primary TDD signal)
// =====================================================================
[Test]
[Category("GoldenMaster")]
[Property("CapabilityId", "CAP-006")]
[Property("Contract", "BuildChecklistData")]
[Property("ScenarioId", "TS-001")]
[Property("GoldenMaster", "gm-001")]
[Property("BehaviorId", "BHV-101")]
public void Gm001_SingleProjectMarkers_Replay_MatchesShape()
{
// gm-001 primary outer acceptance: single project, EXO 20:1..20:20,
// showVerseText=true, hideMatches=true (but single column so no-op),
// expected rowCount=2, excludedCount=0. Row 0 = EXO 20:1 cell with
// one paragraph marker="p". Row 1 = EXO 20:2 cell with two paragraphs
// marker="q" then marker="q2".
var scrText = RegisterDummyProject(Gm001ExoUsfm);
var request = BuildRequest(
activeProjectId: scrText.Guid.ToString(),