-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_prep.py
More file actions
4297 lines (3543 loc) · 173 KB
/
test_prep.py
File metadata and controls
4297 lines (3543 loc) · 173 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
#!/usr/bin/env python3
"""Unit tests for prep.py"""
import argparse
import contextlib
import io
import os
import shutil
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import MagicMock, patch, PropertyMock
# Set up minimal env before importing prep
os.environ.setdefault("OPENAI_API_KEY", "sk-test-fake-key")
import prep
class _ProfileTestMixin:
"""Mixin that saves/restores all 13 dir constants + 7 config vars + episode counts."""
_PROFILE_DIR_ATTRS = [
'OUTPUTS', 'SYLLABUS_DIR', 'EPISODES_DIR', 'GEM_DIR', 'NLM_DIR',
'RAW_DIR', 'IN_AGENDAS', 'IN_EPISODES', 'IN_MISC',
]
_PROFILE_CFG_ATTRS = [
'ROLE', 'COMPANY', 'DOMAIN', 'AUDIENCE', 'MODEL', 'EFFORT', 'AS_OF',
]
_PROFILE_COUNT_ATTRS = [
'_CORE_COUNT', '_FRONTIER_COUNT', 'CORE_EPS', 'FRONTIER_EPS',
'ALL_EPS', 'SYLLABUS_RUNS',
]
def _save_profile_state(self):
self._profile_saved = {}
for attr in self._PROFILE_DIR_ATTRS + self._PROFILE_CFG_ATTRS + self._PROFILE_COUNT_ATTRS:
self._profile_saved[attr] = getattr(prep, attr)
self._saved_domain = prep._DOMAIN.copy()
def _restore_profile_state(self):
for attr, val in self._profile_saved.items():
setattr(prep, attr, val)
prep._DOMAIN = self._saved_domain
def _write_profile(self, name, content, base=None):
base = base or self.tmpdir
d = Path(base) / "profiles" / name
d.mkdir(parents=True, exist_ok=True)
(d / "profile.md").write_text(content, encoding="utf-8")
def _write_domain(self, name, domain_files, base=None):
"""Write domain/ files for a profile. domain_files: dict of fname->content."""
base = base or self.tmpdir
d = Path(base) / "profiles" / name / "domain"
d.mkdir(parents=True, exist_ok=True)
for fname, content in domain_files.items():
(d / fname).write_text(content, encoding="utf-8")
class TestGemSlot(unittest.TestCase):
def test_core_episodes_pair_into_slots_1_through_6(self):
self.assertEqual(prep.gem_slot(1), 1)
self.assertEqual(prep.gem_slot(2), 1)
self.assertEqual(prep.gem_slot(3), 2)
self.assertEqual(prep.gem_slot(4), 2)
self.assertEqual(prep.gem_slot(5), 3)
self.assertEqual(prep.gem_slot(6), 3)
self.assertEqual(prep.gem_slot(11), 6)
self.assertEqual(prep.gem_slot(12), 6)
def test_frontiers_go_to_slot_7(self):
self.assertEqual(prep.gem_slot(13), 7)
self.assertEqual(prep.gem_slot(14), 7)
self.assertEqual(prep.gem_slot(15), 7)
def test_misc_goes_to_slot_8(self):
self.assertEqual(prep.gem_slot(16), 8)
self.assertEqual(prep.gem_slot(99), 8)
class TestParseAgendas(unittest.TestCase):
def test_basic_episodes(self):
text = """## Episode 1: The Binding Problem
mTLS vs DPoP content here.
Some bullets and details.
## Episode 2: The Session Kill Switch
Revocation content here.
More details.
"""
result = prep.parse_agendas(text)
self.assertIn(1, result)
self.assertIn(2, result)
self.assertIn("Binding Problem", result[1])
self.assertIn("Session Kill Switch", result[2])
def test_frontier_digests(self):
text = """## Frontier Digest A: Binding, Revocation, Mobile OAuth
Some frontier content.
## Frontier Digest B: Zero Trust, Workload Identity
More frontier content.
"""
result = prep.parse_agendas(text)
self.assertIn(13, result) # A -> 13
self.assertIn(14, result) # B -> 14
def test_mixed_episodes_and_frontiers(self):
text = """## Episode 9: Detection Engineering
Detection content.
## Episode 10: Crypto Agility
Crypto content.
## Frontier Digest C: Detection, PQC, Encryption
Frontier C content.
"""
result = prep.parse_agendas(text)
self.assertIn(9, result)
self.assertIn(10, result)
self.assertIn(15, result) # C -> 15
def test_no_matches_returns_empty(self):
result = prep.parse_agendas("Just some random text with no episodes.")
self.assertEqual(result, {})
def test_single_hash_header(self):
text = "# Episode 5: BeyondCorp\nContent here."
result = prep.parse_agendas(text)
self.assertIn(5, result)
def test_no_hash_header(self):
text = "Episode 7: SSRF\nContent here."
result = prep.parse_agendas(text)
self.assertIn(7, result)
def test_bold_episode_header(self):
"""Real GPT-5.2-pro output uses **Episode N — Title**"""
text = """1) **The Title (Catchy and technical).**
**Episode 1 — The Binding Problem: mTLS vs DPoP**
2) **The Hook**
- Tokens are cash.
1) **The Title (Catchy and technical).**
**Episode 2 — The Session Kill Switch**
2) **The Hook**
- Long sessions vs fast kill.
"""
result = prep.parse_agendas(text)
self.assertIn(1, result)
self.assertIn(2, result)
self.assertIn("Binding Problem", result[1])
self.assertIn("Session Kill Switch", result[2])
def test_numbered_bold_episode(self):
"""Handle 1) **Episode 1:..."""
text = "1) **Episode 5: BeyondCorp**\nContent here."
result = prep.parse_agendas(text)
self.assertIn(5, result)
def test_bold_frontier_digest(self):
text = "**Frontier Digest A — Binding, Revocation (Feb 2026)**\nContent."
result = prep.parse_agendas(text)
self.assertIn(13, result)
def test_case_insensitive(self):
text = "## episode 3: Mobile Identity\nContent."
result = prep.parse_agendas(text)
self.assertIn(3, result)
def test_frontier_case_insensitive(self):
text = "## frontier digest a: stuff\nContent."
result = prep.parse_agendas(text)
self.assertIn(13, result)
def test_content_boundaries_correct(self):
text = """## Episode 1: First
Line A of episode 1.
Line B of episode 1.
## Episode 2: Second
Line A of episode 2.
"""
result = prep.parse_agendas(text)
self.assertNotIn("Second", result[1])
self.assertNotIn("Line A of episode 2", result[1])
self.assertIn("Line A of episode 1", result[1])
class TestEpFile(unittest.TestCase):
def test_zero_padded(self):
self.assertEqual(prep.ep_file(1, "agenda"), "episode-01-agenda.md")
self.assertEqual(prep.ep_file(12, "content"), "episode-12-content.md")
self.assertEqual(prep.ep_file(15, "agenda"), "episode-15-agenda.md")
class TestPromptTemplating(unittest.TestCase):
"""Test that prompt assembly doesn't crash on curly braces in content."""
def test_content_prompt_with_braces(self):
agenda = "Episode 1: JWT claims {sub, aud, jti} and mTLS {client_cert}"
result = prep.content_prompt(agenda)
self.assertIn("{sub, aud, jti}", result)
self.assertIn("{client_cert}", result)
self.assertIn(prep.AS_OF, result)
def test_content_prompt_with_json(self):
agenda = '{"iss": "https://accounts.google.com", "aud": "client_id"}'
result = prep.content_prompt(agenda)
self.assertIn('"iss"', result)
def test_content_prompt_defaults_extra_notes(self):
result = prep.content_prompt("Some agenda")
self.assertIn("No additional notes", result)
def test_content_prompt_custom_notes(self):
result = prep.content_prompt("Some agenda", notes="Focus on mTLS.")
self.assertIn("Focus on mTLS.", result)
def test_distill_prompt_with_braces(self):
raw = "Config: {\"key\": \"value\", \"nested\": {\"a\": 1}}"
result = prep.distill_prompt(raw)
self.assertIn('"key"', result)
def test_syllabus_prompt_format(self):
run = dict(mode="SCAFFOLD", core="", frontier="")
result = prep.syllabus_prompt(run)
self.assertIn("MODE: SCAFFOLD", result)
def test_syllabus_prompt_with_core_batch(self):
run = dict(mode="CORE_BATCH", core="1-4", frontier="")
result = prep.syllabus_prompt(run)
self.assertIn("CORE_EPISODES: 1-4", result)
def test_content_prompt_replacement_order_safe(self):
"""Agenda containing placeholder strings should NOT be double-replaced."""
agenda = "This agenda mentions {AS_OF_DATE} and {EXTRA_NOTES} literally"
result = prep.content_prompt(agenda)
# The literal strings in the agenda should survive
self.assertIn("{AS_OF_DATE}", result)
self.assertIn("{EXTRA_NOTES}", result)
class TestFileHelpers(_ProfileTestMixin, unittest.TestCase):
def setUp(self):
self.tmpdir = tempfile.mkdtemp()
self._save_profile_state()
prep.IN_AGENDAS = Path(self.tmpdir) / "in_agendas"
prep.IN_EPISODES = Path(self.tmpdir) / "in_episodes"
prep.SYLLABUS_DIR = Path(self.tmpdir) / "syllabus"
prep.EPISODES_DIR = Path(self.tmpdir) / "episodes"
for d in [prep.IN_AGENDAS, prep.IN_EPISODES, prep.SYLLABUS_DIR, prep.EPISODES_DIR]:
d.mkdir(parents=True)
def tearDown(self):
self._restore_profile_state()
shutil.rmtree(self.tmpdir)
def test_find_agenda_in_inputs(self):
p = prep.IN_AGENDAS / "episode-01-agenda.md"
p.write_text("agenda 1", encoding="utf-8")
self.assertEqual(prep.find_agenda(1), p)
def test_find_agenda_in_outputs(self):
p = prep.SYLLABUS_DIR / "episode-03-agenda.md"
p.write_text("agenda 3", encoding="utf-8")
self.assertEqual(prep.find_agenda(3), p)
def test_find_agenda_inputs_priority(self):
"""inputs/ should be checked before outputs/"""
p1 = prep.IN_AGENDAS / "episode-01-agenda.md"
p2 = prep.SYLLABUS_DIR / "episode-01-agenda.md"
p1.write_text("from inputs", encoding="utf-8")
p2.write_text("from outputs", encoding="utf-8")
result = prep.find_agenda(1)
self.assertEqual(result, p1)
self.assertEqual(result.read_text(encoding="utf-8"), "from inputs")
def test_find_agenda_missing(self):
self.assertIsNone(prep.find_agenda(99))
def test_find_content_in_inputs(self):
p = prep.IN_EPISODES / "episode-02-content.md"
p.write_text("content 2", encoding="utf-8")
self.assertEqual(prep.find_content(2), p)
def test_find_content_in_outputs(self):
p = prep.EPISODES_DIR / "episode-05-content.md"
p.write_text("content 5", encoding="utf-8")
self.assertEqual(prep.find_content(5), p)
def test_find_content_missing(self):
self.assertIsNone(prep.find_content(99))
def test_zero_byte_agenda_exists_but_empty(self):
"""A 0-byte file should still be 'found' — caller must handle."""
p = prep.IN_AGENDAS / "episode-05-agenda.md"
p.write_text("", encoding="utf-8")
result = prep.find_agenda(5)
self.assertEqual(result, p)
self.assertEqual(result.read_text(encoding="utf-8"), "")
class TestSkipLogic(_ProfileTestMixin, unittest.TestCase):
"""Test that cmd_syllabus and cmd_content correctly skip existing files."""
def setUp(self):
self.tmpdir = tempfile.mkdtemp()
self._save_profile_state()
for attr in ['IN_AGENDAS', 'IN_EPISODES', 'SYLLABUS_DIR', 'EPISODES_DIR',
'RAW_DIR', 'GEM_DIR', 'NLM_DIR']:
new_dir = Path(self.tmpdir) / attr.lower()
new_dir.mkdir(parents=True)
setattr(prep, attr, new_dir)
def tearDown(self):
self._restore_profile_state()
shutil.rmtree(self.tmpdir)
def test_content_skips_existing(self):
"""If content exists, cmd_content should not call LLM for that episode."""
# Create agenda + content for ep 1
(prep.SYLLABUS_DIR / "episode-01-agenda.md").write_text("agenda", encoding="utf-8")
(prep.EPISODES_DIR / "episode-01-content.md").write_text("x" * 1000, encoding="utf-8")
client = MagicMock()
# Run content for just ep 1 by temporarily limiting ALL_EPS
orig_all = prep.ALL_EPS
prep.ALL_EPS = [1]
try:
prep.cmd_content(client, force=False)
finally:
prep.ALL_EPS = orig_all
# LLM should NOT have been called
client.responses.create.assert_not_called()
def test_content_regenerates_truncated_file(self):
"""If content file is too small (<500 chars), regenerate it."""
(prep.SYLLABUS_DIR / "episode-01-agenda.md").write_text("Full agenda text " * 50, encoding="utf-8")
(prep.EPISODES_DIR / "episode-01-content.md").write_text("truncated", encoding="utf-8") # <500 chars
mock_resp = MagicMock()
mock_resp.status = "completed"
mock_resp.output_text = "Full regenerated content " * 100
mock_resp.usage = None
client = MagicMock()
client.responses.create.return_value = mock_resp
orig_all = prep.ALL_EPS
prep.ALL_EPS = [1]
try:
prep.cmd_content(client, force=False)
finally:
prep.ALL_EPS = orig_all
# LLM SHOULD have been called because file was too small
client.responses.create.assert_called_once()
def test_content_regenerates_empty_file(self):
"""0-byte content file should be regenerated."""
(prep.SYLLABUS_DIR / "episode-01-agenda.md").write_text("Full agenda text " * 50, encoding="utf-8")
(prep.EPISODES_DIR / "episode-01-content.md").write_text("", encoding="utf-8") # empty
mock_resp = MagicMock()
mock_resp.status = "completed"
mock_resp.output_text = "Regenerated content " * 100
mock_resp.usage = None
client = MagicMock()
client.responses.create.return_value = mock_resp
orig_all = prep.ALL_EPS
prep.ALL_EPS = [1]
try:
prep.cmd_content(client, force=False)
finally:
prep.ALL_EPS = orig_all
client.responses.create.assert_called_once()
def test_content_force_regenerates(self):
"""With --force, existing content should be regenerated."""
(prep.SYLLABUS_DIR / "episode-01-agenda.md").write_text("agenda text " * 50, encoding="utf-8")
(prep.EPISODES_DIR / "episode-01-content.md").write_text("old content " * 100, encoding="utf-8")
# Mock the LLM
mock_resp = MagicMock()
mock_resp.status = "completed"
mock_resp.output_text = "new content generated"
mock_resp.usage = None
client = MagicMock()
client.responses.create.return_value = mock_resp
orig_all = prep.ALL_EPS
prep.ALL_EPS = [1]
try:
prep.cmd_content(client, force=True)
finally:
prep.ALL_EPS = orig_all
client.responses.create.assert_called_once()
new_content = (prep.EPISODES_DIR / "episode-01-content.md").read_text(encoding="utf-8")
self.assertEqual(new_content, "new content generated")
def test_scaffold_skip(self):
"""Scaffold should be skipped if scaffold.md exists."""
(prep.SYLLABUS_DIR / "scaffold.md").write_text("existing scaffold", encoding="utf-8")
client = MagicMock()
# Only run SCAFFOLD
orig_runs = prep.SYLLABUS_RUNS
prep.SYLLABUS_RUNS = [dict(mode="SCAFFOLD", core="", frontier="")]
try:
prep.cmd_syllabus(client, force=False)
finally:
prep.SYLLABUS_RUNS = orig_runs
client.responses.create.assert_not_called()
def test_core_batch_skip(self):
"""CORE_BATCH should be skipped if all agendas in range exist."""
for n in range(1, 5):
(prep.SYLLABUS_DIR / f"episode-{n:02d}-agenda.md").write_text(f"agenda {n}", encoding="utf-8")
client = MagicMock()
orig_runs = prep.SYLLABUS_RUNS
prep.SYLLABUS_RUNS = [dict(mode="CORE_BATCH", core="1-4", frontier="")]
try:
prep.cmd_syllabus(client, force=False)
finally:
prep.SYLLABUS_RUNS = orig_runs
client.responses.create.assert_not_called()
def test_core_batch_partial_runs(self):
"""CORE_BATCH should NOT skip if only some agendas exist."""
(prep.SYLLABUS_DIR / "episode-01-agenda.md").write_text("agenda 1", encoding="utf-8")
# 2, 3, 4 missing
mock_resp = MagicMock()
mock_resp.status = "completed"
mock_resp.output_text = "## Episode 1: A\ncontent\n\n## Episode 2: B\ncontent\n\n## Episode 3: C\ncontent\n\n## Episode 4: D\ncontent"
mock_resp.usage = None
client = MagicMock()
client.responses.create.return_value = mock_resp
orig_runs = prep.SYLLABUS_RUNS
prep.SYLLABUS_RUNS = [dict(mode="CORE_BATCH", core="1-4", frontier="")]
try:
prep.cmd_syllabus(client, force=False)
finally:
prep.SYLLABUS_RUNS = orig_runs
client.responses.create.assert_called_once()
def test_content_returns_false_on_failure(self):
"""cmd_content should return False when episodes fail."""
(prep.SYLLABUS_DIR / "episode-01-agenda.md").write_text("agenda text " * 50, encoding="utf-8")
# LLM returns failure
mock_resp = MagicMock()
mock_resp.status = "failed"
mock_resp.error = "test failure"
client = MagicMock()
client.responses.create.return_value = mock_resp
orig_all = prep.ALL_EPS
prep.ALL_EPS = [1]
buf = io.StringIO()
try:
with contextlib.redirect_stdout(buf):
with patch('prep.time') as mock_time:
mock_time.sleep = MagicMock()
mock_time.time = MagicMock(return_value=0)
result = prep.cmd_content(client, force=True)
finally:
prep.ALL_EPS = orig_all
self.assertFalse(result)
self.assertIn("1 failed", buf.getvalue())
def test_content_returns_true_on_success(self):
"""cmd_content should return True when all episodes succeed."""
(prep.SYLLABUS_DIR / "episode-01-agenda.md").write_text("agenda text " * 50, encoding="utf-8")
mock_resp = MagicMock()
mock_resp.status = "completed"
mock_resp.output_text = "Generated content " * 100
mock_resp.usage = None
client = MagicMock()
client.responses.create.return_value = mock_resp
orig_all = prep.ALL_EPS
prep.ALL_EPS = [1]
buf = io.StringIO()
try:
with contextlib.redirect_stdout(buf):
result = prep.cmd_content(client, force=True)
finally:
prep.ALL_EPS = orig_all
self.assertTrue(result)
self.assertIn("0 failed", buf.getvalue())
class TestPackaging(_ProfileTestMixin, unittest.TestCase):
def setUp(self):
self.tmpdir = tempfile.mkdtemp()
self._save_profile_state()
for attr in ['IN_AGENDAS', 'IN_EPISODES', 'SYLLABUS_DIR', 'EPISODES_DIR',
'RAW_DIR', 'GEM_DIR', 'NLM_DIR']:
new_dir = Path(self.tmpdir) / attr.lower()
new_dir.mkdir(parents=True)
setattr(prep, attr, new_dir)
def tearDown(self):
self._restore_profile_state()
shutil.rmtree(self.tmpdir)
def test_package_creates_gem_files(self):
# Create content for eps 1 and 2 (should go to gem-1)
(prep.EPISODES_DIR / "episode-01-content.md").write_text("Content for ep 1", encoding="utf-8")
(prep.EPISODES_DIR / "episode-02-content.md").write_text("Content for ep 2", encoding="utf-8")
prep.cmd_package()
gem1 = prep.GEM_DIR / "gem-1.md"
self.assertTrue(gem1.exists())
text = gem1.read_text(encoding="utf-8")
self.assertIn("EPISODE 1", text)
self.assertIn("EPISODE 2", text)
self.assertIn("Content for ep 1", text)
self.assertIn("Content for ep 2", text)
def test_package_creates_notebooklm_files(self):
(prep.EPISODES_DIR / "episode-01-content.md").write_text("Content 1", encoding="utf-8")
prep.cmd_package()
nlm = prep.NLM_DIR / "episode-01-content.md"
self.assertTrue(nlm.exists())
self.assertEqual(nlm.read_text(encoding="utf-8"), "Content 1")
def test_package_misc_to_slot_8(self):
(prep.EPISODES_DIR / "misc-paper-content.md").write_text("Misc content", encoding="utf-8")
prep.cmd_package()
gem8 = prep.GEM_DIR / "gem-8.md"
self.assertTrue(gem8.exists())
self.assertIn("Misc content", gem8.read_text(encoding="utf-8"))
def test_package_no_content_returns_false(self):
result = prep.cmd_package()
self.assertFalse(result)
def test_frontiers_to_slot_7(self):
(prep.EPISODES_DIR / "episode-13-content.md").write_text("Frontier A", encoding="utf-8")
(prep.EPISODES_DIR / "episode-14-content.md").write_text("Frontier B", encoding="utf-8")
prep.cmd_package()
gem7 = prep.GEM_DIR / "gem-7.md"
self.assertTrue(gem7.exists())
self.assertIn("Frontier A", gem7.read_text(encoding="utf-8"))
self.assertIn("Frontier B", gem7.read_text(encoding="utf-8"))
class TestCallLLM(unittest.TestCase):
def test_successful_call(self):
mock_resp = MagicMock()
mock_resp.status = "completed"
mock_resp.output_text = "Generated content here"
mock_resp.usage = None
client = MagicMock()
client.responses.create.return_value = mock_resp
result = prep.call_llm(client, "instructions", "input", "test")
self.assertEqual(result, "Generated content here")
def test_polling_loop(self):
"""Test that polling works when initial status is queued."""
mock_initial = MagicMock()
mock_initial.status = "queued"
mock_initial.id = "resp_123"
mock_done = MagicMock()
mock_done.status = "completed"
mock_done.output_text = "Done!"
mock_done.usage = None
client = MagicMock()
client.responses.create.return_value = mock_initial
client.responses.retrieve.side_effect = [
MagicMock(status="in_progress"),
MagicMock(status="in_progress"),
mock_done,
]
with patch('prep.time') as mock_time:
mock_time.sleep = MagicMock()
mock_time.time = MagicMock(side_effect=[0, 1, 2, 3]) # well under timeout
result = prep.call_llm(client, "inst", "inp", "test")
self.assertEqual(result, "Done!")
self.assertEqual(client.responses.retrieve.call_count, 3)
def test_empty_output_retries(self):
mock_resp = MagicMock()
mock_resp.status = "completed"
mock_resp.output_text = ""
mock_resp2 = MagicMock()
mock_resp2.status = "completed"
mock_resp2.output_text = "Got it second time"
mock_resp2.usage = None
client = MagicMock()
client.responses.create.side_effect = [mock_resp, mock_resp2]
with patch('prep.time') as mock_time:
mock_time.sleep = MagicMock()
mock_time.time = MagicMock(return_value=0)
result = prep.call_llm(client, "inst", "inp", "test")
self.assertEqual(result, "Got it second time")
self.assertEqual(client.responses.create.call_count, 2)
def test_failed_status_retries(self):
mock_fail = MagicMock()
mock_fail.status = "failed"
mock_fail.error = "rate limited"
mock_ok = MagicMock()
mock_ok.status = "completed"
mock_ok.output_text = "Success"
mock_ok.usage = None
client = MagicMock()
client.responses.create.side_effect = [mock_fail, mock_ok]
with patch('prep.time') as mock_time:
mock_time.sleep = MagicMock()
mock_time.time = MagicMock(return_value=0)
result = prep.call_llm(client, "inst", "inp", "test")
self.assertEqual(result, "Success")
def test_all_retries_exhausted(self):
mock_fail = MagicMock()
mock_fail.status = "failed"
mock_fail.error = "server error"
client = MagicMock()
client.responses.create.return_value = mock_fail
with patch('prep.time') as mock_time:
mock_time.sleep = MagicMock()
mock_time.time = MagicMock(return_value=0)
result = prep.call_llm(client, "inst", "inp", "test", retries=2)
self.assertIsNone(result)
self.assertEqual(client.responses.create.call_count, 2)
def test_polling_timeout(self):
"""Test that polling raises after POLL_TIMEOUT seconds."""
mock_initial = MagicMock()
mock_initial.status = "in_progress"
mock_initial.id = "resp_stuck"
client = MagicMock()
client.responses.create.return_value = mock_initial
client.responses.retrieve.return_value = MagicMock(status="in_progress")
# Simulate time advancing past timeout
orig_timeout = prep.POLL_TIMEOUT
prep.POLL_TIMEOUT = 10 # 10 second timeout for test
times = iter([0, 5, 11]) # third call is past timeout
with patch('prep.time') as mock_time:
mock_time.sleep = MagicMock()
mock_time.time = MagicMock(side_effect=times)
result = prep.call_llm(client, "inst", "inp", "test", retries=1)
prep.POLL_TIMEOUT = orig_timeout
self.assertIsNone(result)
def test_unexpected_status(self):
"""Test that unexpected status (not failed, not completed) is handled."""
mock_resp = MagicMock()
mock_resp.status = "cancelled"
mock_resp.output_text = None
client = MagicMock()
client.responses.create.return_value = mock_resp
with patch('prep.time') as mock_time:
mock_time.sleep = MagicMock()
mock_time.time = MagicMock(return_value=0)
result = prep.call_llm(client, "inst", "inp", "test", retries=1)
# Should fail gracefully (output_text is None -> "Empty output" exception -> retry exhausted)
self.assertIsNone(result)
class TestParseAgendasWarning(_ProfileTestMixin, unittest.TestCase):
"""Test that empty parse results trigger warnings during syllabus."""
def setUp(self):
self.tmpdir = tempfile.mkdtemp()
self._save_profile_state()
for attr in ['IN_AGENDAS', 'IN_EPISODES', 'SYLLABUS_DIR', 'EPISODES_DIR',
'RAW_DIR', 'GEM_DIR', 'NLM_DIR']:
new_dir = Path(self.tmpdir) / attr.lower()
new_dir.mkdir(parents=True)
setattr(prep, attr, new_dir)
def tearDown(self):
self._restore_profile_state()
shutil.rmtree(self.tmpdir)
def test_warning_printed_on_empty_parse(self):
"""If model output has no parseable episodes, a warning should print."""
# Model returns garbage with no Episode headers
mock_resp = MagicMock()
mock_resp.status = "completed"
mock_resp.output_text = "Here is some content without any episode headers at all."
mock_resp.usage = None
client = MagicMock()
client.responses.create.return_value = mock_resp
orig_runs = prep.SYLLABUS_RUNS
prep.SYLLABUS_RUNS = [dict(mode="CORE_BATCH", core="1-4", frontier="")]
import io
from contextlib import redirect_stdout
f = io.StringIO()
try:
with redirect_stdout(f):
prep.cmd_syllabus(client, force=True)
finally:
prep.SYLLABUS_RUNS = orig_runs
output = f.getvalue()
self.assertIn("WARNING", output)
self.assertIn("parse_agendas found 0 episodes", output)
def test_no_warning_on_successful_parse(self):
"""Normal episode output should NOT trigger warning."""
mock_resp = MagicMock()
mock_resp.status = "completed"
mock_resp.output_text = "## Episode 1: Binding\nContent\n\n## Episode 2: Session\nContent\n\n## Episode 3: Mobile\nContent\n\n## Episode 4: Passkeys\nContent"
mock_resp.usage = None
client = MagicMock()
client.responses.create.return_value = mock_resp
orig_runs = prep.SYLLABUS_RUNS
prep.SYLLABUS_RUNS = [dict(mode="CORE_BATCH", core="1-4", frontier="")]
import io
from contextlib import redirect_stdout
f = io.StringIO()
try:
with redirect_stdout(f):
prep.cmd_syllabus(client, force=True)
finally:
prep.SYLLABUS_RUNS = orig_runs
output = f.getvalue()
self.assertNotIn("WARNING", output)
self.assertIn("saved episode-01-agenda.md", output)
class TestCmdAllFailureHandling(_ProfileTestMixin, unittest.TestCase):
"""Test that cmd_all warns on syllabus failure."""
def setUp(self):
self.tmpdir = tempfile.mkdtemp()
self._save_profile_state()
for attr in ['IN_AGENDAS', 'IN_EPISODES', 'SYLLABUS_DIR', 'EPISODES_DIR',
'RAW_DIR', 'GEM_DIR', 'NLM_DIR']:
new_dir = Path(self.tmpdir) / attr.lower()
new_dir.mkdir(parents=True)
setattr(prep, attr, new_dir)
def tearDown(self):
self._restore_profile_state()
shutil.rmtree(self.tmpdir)
def test_warns_on_syllabus_failure(self):
"""If syllabus fails, cmd_all should print error but continue."""
# Make syllabus fail by returning None from LLM
client = MagicMock()
client.responses.create.return_value = MagicMock(
status="failed", error="test failure"
)
orig_runs = prep.SYLLABUS_RUNS
prep.SYLLABUS_RUNS = [dict(mode="SCAFFOLD", core="", frontier="")]
import io
from contextlib import redirect_stdout
f = io.StringIO()
try:
with redirect_stdout(f):
with patch('prep.time') as mock_time:
mock_time.sleep = MagicMock()
mock_time.time = MagicMock(return_value=0)
prep.cmd_all(client, force=True)
finally:
prep.SYLLABUS_RUNS = orig_runs
output = f.getvalue()
self.assertIn("ERROR: Syllabus had failures", output)
class TestCmdAllAlreadyComplete(_ProfileTestMixin, unittest.TestCase):
"""Test that cmd_all short-circuits when pipeline is already complete."""
def setUp(self):
self.tmpdir = tempfile.mkdtemp()
self._save_profile_state()
for attr in ['IN_AGENDAS', 'IN_EPISODES', 'SYLLABUS_DIR', 'EPISODES_DIR',
'RAW_DIR', 'GEM_DIR', 'NLM_DIR']:
new_dir = Path(self.tmpdir) / attr.lower()
new_dir.mkdir(parents=True)
setattr(prep, attr, new_dir)
def tearDown(self):
self._restore_profile_state()
shutil.rmtree(self.tmpdir)
def test_skips_when_complete(self):
"""cmd_all should print message and return True when all outputs exist."""
for ep in prep.ALL_EPS:
(prep.SYLLABUS_DIR / prep.ep_file(ep, "agenda")).write_text("agenda", encoding="utf-8")
(prep.EPISODES_DIR / prep.ep_file(ep, "content")).write_text("x" * 500, encoding="utf-8")
client = MagicMock()
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
result = prep.cmd_all(client)
output = buf.getvalue()
self.assertIn("already complete", output)
self.assertIn("--force", output)
client.responses.create.assert_not_called()
self.assertIs(result, True)
def test_runs_when_incomplete(self):
"""cmd_all should proceed normally when outputs are missing."""
client = MagicMock()
client.responses.create.return_value = MagicMock(
status="failed", error="test"
)
orig_runs = prep.SYLLABUS_RUNS
prep.SYLLABUS_RUNS = [dict(mode="SCAFFOLD", core="", frontier="")]
buf = io.StringIO()
try:
with contextlib.redirect_stdout(buf):
with patch('prep.time') as mock_time:
mock_time.sleep = MagicMock()
mock_time.time = MagicMock(return_value=0)
prep.cmd_all(client)
finally:
prep.SYLLABUS_RUNS = orig_runs
output = buf.getvalue()
self.assertNotIn("already complete", output)
class TestRecoverFromRaw(_ProfileTestMixin, unittest.TestCase):
"""Test recovery of agendas from raw syllabus files."""
def setUp(self):
self.tmpdir = tempfile.mkdtemp()
self._save_profile_state()
for attr in ['IN_AGENDAS', 'IN_EPISODES', 'SYLLABUS_DIR', 'EPISODES_DIR',
'RAW_DIR', 'GEM_DIR', 'NLM_DIR']:
new_dir = Path(self.tmpdir) / attr.lower()
new_dir.mkdir(parents=True)
setattr(prep, attr, new_dir)
def tearDown(self):
self._restore_profile_state()
shutil.rmtree(self.tmpdir)
def test_recovers_agendas_from_raw_core_batch(self):
"""If raw file exists but agendas don't, recover them."""
raw_text = """**Episode 1 — The Binding Problem**
Content for ep 1.
**Episode 2 — The Session Kill Switch**
Content for ep 2.
"""
(prep.RAW_DIR / "syllabus-02-core_batch.md").write_text(raw_text, encoding="utf-8")
count = prep.recover_agendas_from_raw()
self.assertEqual(count, 2)
self.assertTrue((prep.SYLLABUS_DIR / "episode-01-agenda.md").exists())
self.assertTrue((prep.SYLLABUS_DIR / "episode-02-agenda.md").exists())
def test_no_double_recovery(self):
"""If agenda already exists, don't overwrite."""
raw_text = "**Episode 1 — New Version**\nNew content."
(prep.RAW_DIR / "syllabus-02-core_batch.md").write_text(raw_text, encoding="utf-8")
(prep.SYLLABUS_DIR / "episode-01-agenda.md").write_text("Original content", encoding="utf-8")
count = prep.recover_agendas_from_raw()
self.assertEqual(count, 0)
self.assertEqual(
(prep.SYLLABUS_DIR / "episode-01-agenda.md").read_text(encoding="utf-8"),
"Original content"
)
def test_respects_inputs_priority(self):
"""If agenda exists in inputs/, don't recover from raw."""
raw_text = "**Episode 1 — From Raw**\nRaw content."
(prep.RAW_DIR / "syllabus-02-core_batch.md").write_text(raw_text, encoding="utf-8")
(prep.IN_AGENDAS / "episode-01-agenda.md").write_text("From inputs", encoding="utf-8")
count = prep.recover_agendas_from_raw()
self.assertEqual(count, 0)
def test_recovers_frontier_digest(self):
raw_text = "**Frontier Digest A — Updates**\nFrontier content."
(prep.RAW_DIR / "syllabus-03-frontier_digest.md").write_text(raw_text, encoding="utf-8")
count = prep.recover_agendas_from_raw()
self.assertEqual(count, 1)
self.assertTrue((prep.SYLLABUS_DIR / "episode-13-agenda.md").exists())
def test_skips_empty_raw_file(self):
(prep.RAW_DIR / "syllabus-02-core_batch.md").write_text("", encoding="utf-8")
count = prep.recover_agendas_from_raw()
self.assertEqual(count, 0)
@unittest.skipUnless(
(Path(__file__).parent / "profiles" / "security-infra" / "outputs" / "raw" / "syllabus-02-core_batch.md").exists(),
"Real output file not available (run pipeline first)"
)
def test_recovers_from_real_raw_file(self):
"""Recovery works with actual GPT-5.2-pro output."""
real_text = (Path(__file__).parent / "profiles" / "security-infra" / "outputs" / "raw" / "syllabus-02-core_batch.md").read_text(encoding="utf-8")
(prep.RAW_DIR / "syllabus-02-core_batch.md").write_text(real_text, encoding="utf-8")
count = prep.recover_agendas_from_raw()
self.assertEqual(count, 4)
for ep in [1, 2, 3, 4]:
p = prep.SYLLABUS_DIR / f"episode-{ep:02d}-agenda.md"
self.assertTrue(p.exists(), f"Missing {p.name}")
self.assertGreater(len(p.read_text(encoding="utf-8")), 1000)
class TestSyllabusRuns(unittest.TestCase):
"""Verify the SYLLABUS_RUNS configuration is correct."""
def test_eight_runs(self):
self.assertEqual(len(prep.SYLLABUS_RUNS), 8)
def test_run_order(self):
modes = [r["mode"] for r in prep.SYLLABUS_RUNS]
self.assertEqual(modes, [
"SCAFFOLD",
"CORE_BATCH", "FRONTIER_DIGEST",
"CORE_BATCH", "FRONTIER_DIGEST",
"CORE_BATCH", "FRONTIER_DIGEST",
"FINAL_MERGE",
])
def test_core_batch_ranges(self):
cores = [r["core"] for r in prep.SYLLABUS_RUNS if r["mode"] == "CORE_BATCH"]
self.assertEqual(cores, ["1-4", "5-8", "9-12"])
def test_frontier_labels(self):
fronts = [r["frontier"] for r in prep.SYLLABUS_RUNS if r["mode"] == "FRONTIER_DIGEST"]
self.assertEqual(fronts, ["A", "B", "C"])
class TestConstants(unittest.TestCase):
def test_all_eps_is_1_through_15(self):
self.assertEqual(prep.ALL_EPS, list(range(1, 16)))
def test_core_eps(self):
self.assertEqual(prep.CORE_EPS, list(range(1, 13)))
def test_frontier_eps(self):
self.assertEqual(prep.FRONTIER_EPS, [13, 14, 15])