Repository navigation
Expand file tree
/
Copy pathtest_handoff.py
More file actions
executable file
·2574 lines (2275 loc) · 111 KB
/
Copy pathtest_handoff.py
File metadata and controls
executable file
·2574 lines (2275 loc) · 111 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Exercise handoff.py's chain model, refusals, and write ordering against a stubbed `gh`.
Every case here drives the real subcommands through a fake `gh` holding an in-memory repository,
because the properties under test are about what the script decides and in what order it writes,
not about GitHub. The one thing a stub cannot prove is that `gh` accepts these argument lists, so
each write case asserts the argv it produced rather than only its effect.
Two refusals earn cases of their own because the chain exists to fix them. An ambiguous track is
never resolved by picking, and a fleet repository missing the label refuses rather than reporting
an empty chain, which is the silent failure the `decision` label already demonstrated fleet-wide.
A repository outside the fleet warns instead, and its cases prove the warning path never writes
anything but the one label `new --create-label` asks for.
Run as `python3 tests/test_handoff.py`, or under
`python3 -m unittest discover -s tests`.
"""
import argparse
import contextlib
import copy
import io
import itertools
import json
import re
import shutil
import subprocess
import sys
import tempfile
import unittest
import unittest.mock
from pathlib import Path
SCRIPTS = Path(__file__).resolve().parent.parent / "scripts"
sys.path.insert(0, str(SCRIPTS))
import handoff
REAL_REGISTRY = handoff.registry
def setUpModule() -> None:
"""Read `o/r` as a fleet repository unless a case says otherwise.
The write scope reads the registry before every write, and the real one lists no `o`, so
without this every write case would test the scope refusal instead of what it names.
"""
patcher = unittest.mock.patch.object(handoff, "registry", lambda: ("o", {"r"}))
patcher.start()
unittest.addModuleCleanup(patcher.stop)
def marked(body: str, track: str, round_: int, previous: int | None) -> str:
return handoff.with_marker(body, track, round_, previous)
def read_marker(body: str, number: int) -> dict[str, str]:
"""The metadata block a case expects to be there, asserted rather than assumed."""
marker = handoff.parse_marker(body, number)
assert marker is not None, f"#{number} carries no handoff metadata block"
return marker
def subcommands() -> dict[str, argparse.ArgumentParser]:
"""The declared subcommands, read off the parser rather than restated here."""
for action in handoff.build_parser()._actions:
if isinstance(action, argparse._SubParsersAction):
return dict(action.choices)
raise AssertionError("handoff.build_parser declares no subcommands")
def projected(row: dict, argv: list[str]) -> dict:
"""`row` cut down to the fields `--json` asked for, the way real `gh` answers.
A fake returning every field regardless is a fake that models a superset of the tool, and a
caller reading a field it never asked for then passes here and raises against `gh`. That is
exactly what happened: `open_handoffs` did not request `state`, `cmd_new` read it, and 65
green cases said nothing because this stub handed the field over anyway.
"""
if "--json" not in argv:
return dict(row)
wanted = argv[argv.index("--json") + 1].split(",")
return {field: row[field] for field in wanted if field in row}
def fields(argv: list[str]) -> dict[str, list[str]]:
"""Every `-f`/`-F` field of a `gh api` call, keyed by name, each value a list in call order."""
out: dict[str, list[str]] = {}
for flag, pair in itertools.pairwise(argv):
if flag in ("-f", "-F"):
key, _, value = pair.partition("=")
out.setdefault(key.removesuffix("[]"), []).append(value)
return out
def connection(
rows: list, more: bool = False, cursor: str | None = None, *, enabled: bool = True
) -> str:
"""`rows` as one page of the issue connection `handoff.LIST_QUERY` reads."""
page = {"hasNextPage": more, "endCursor": cursor}
issues = {"pageInfo": page, "nodes": rows}
return json.dumps({"data": {"repository": {"hasIssuesEnabled": enabled, "issues": issues}}})
class FakeGh:
"""An in-memory repository `handoff.gh` reads and writes, recording every argv it is given.
It honors `--json`, `--state`, `--label`, and `--limit`, and the GraphQL list's labels,
states, page size, cursor, and node selection. A stub looser than the tool it stands in for is
a stub that green-lights a crash.
It also refuses any call carrying no `--repo`, apart from `repo view`, which names its
repository positionally and is refused instead where that name is no OWNER/NAME. Real `gh`
would answer a call missing its repository by resolving it from the working directory's
remote. That is the failure this whole script is built against. Without this the argument
could be dropped from any call site with every case still green. The GraphQL list names its
repository as `owner` and `name` instead, and is refused alike.
"""
def __init__(
self,
issues: dict[int, dict] | None = None,
*,
label: bool = True,
issues_on: bool = True,
fork: bool = True,
) -> None:
self.issues = issues or {}
self.label = label
self.issues_on = issues_on
self.fork = fork
self.refuse_label = False
self.calls: list[list[str]] = []
self.next_number = 1001
# A close that reports success and leaves the issue open.
# That is the state the read-back after every close exists to catch.
self.refuse_close = False
def __call__(self, argv: list[str]) -> str:
self.calls.append(list(argv))
if argv[:2] == ["repo", "view"]:
if "/" not in argv[2]:
raise AssertionError(f"{' '.join(argv)} names no OWNER/NAME repository")
flags = {"hasIssuesEnabled": self.issues_on, "isFork": self.fork}
return json.dumps(projected(flags, argv))
if argv[:2] == ["api", "graphql"]:
return self._graphql(argv)
if "--repo" not in argv:
raise AssertionError(
f"{' '.join(argv)} carries no --repo, so real gh would resolve the repository "
"from the working directory instead of the one named"
)
head = (argv[0], argv[1])
if head == ("label", "list"):
return json.dumps([{"name": handoff.LABEL}] if self.label else [{"name": "bug"}])
if head == ("label", "create"):
if not self.refuse_label:
self.label = argv[2] == handoff.LABEL
return ""
if head == ("issue", "list"):
return json.dumps([projected(row, argv) for row in self._list(argv)])
if head == ("issue", "view"):
# An issue this repository does not hold is what `gh` exits non-zero on.
# `run_gh` turns that into an Execution, so the fake stands in for the same thing.
# Raising a KeyError instead would model a failure no caller has a reader for.
if int(argv[2]) not in self.issues:
raise handoff.Execution(f"gh issue view failed rc=1 for #{argv[2]}")
return json.dumps(projected(self.issues[int(argv[2])], argv))
if head == ("issue", "create"):
return self._create(argv)
if head == ("issue", "comment"):
return f"https://github.com/o/r/issues/{argv[2]}#issuecomment-1\n"
if head == ("issue", "close"):
if not self.refuse_close:
self.issues[int(argv[2])]["state"] = "CLOSED"
return f"Closed issue #{argv[2]}\n"
if head == ("issue", "edit"):
return self._edit(argv)
raise AssertionError(f"the fake was given an unmodeled call: {argv}")
def _list(self, argv: list[str]) -> list[dict]:
state = argv[argv.index("--state") + 1].upper()
rows = [
row
for row in self.issues.values()
if row["state"] == state
and ("--label" not in argv or self._labeled(row, argv[argv.index("--label") + 1]))
]
limit = int(argv[argv.index("--limit") + 1]) if "--limit" in argv else len(rows)
return rows[:limit]
def _graphql(self, argv: list[str]) -> str:
"""One page of `handoff.LIST_QUERY`, newest first, its cursor the offset of the next row.
The owner and name stand in for `--repo`, so a call naming no repository is refused here too.
"""
f = fields(argv)
if (
len(f.get("owner", [])) != 1
or len(f.get("name", [])) != 1
or not all((*f["owner"], *f["name"]))
):
raise AssertionError(f"{' '.join(argv)} names no OWNER/NAME repository")
rows = sorted(
(
row
for row in self.issues.values()
if row["state"] in f["states"]
and all(self._labeled(row, name) for name in f["labels"])
),
key=lambda row: row["number"],
reverse=True,
)
query = f["query"][0]
declared = dict(re.findall(r"\$(\w+):\s*([\w\[\]!]+)", query))
passed = set(f) - {"query"}
required = {k for k, kind in declared.items() if kind.endswith("!")}
if not passed <= set(declared) or not required <= passed:
raise AssertionError(f"passed {sorted(passed)} against declared {sorted(declared)}")
if not any(a == "-F" and b.startswith("first=") for a, b in itertools.pairwise(argv)):
raise AssertionError("first must go through -F, or GitHub reads it as a string")
first = int(f["first"][0])
if not 1 <= first <= 100:
raise AssertionError(f"first={first} is outside GitHub's 1 to 100")
selected = re.search(r"nodes\s*\{([^}]*)\}", query)
if selected is None:
raise AssertionError("the query selects no nodes")
node = selected.group(1).split()
nested = "labels(" in selected.group(1)
start = int(f.get("after", ["0"])[0])
end = start + first
nodes = [{k: row[k] for k in node if k in row} for row in rows[start:end]]
if nested:
for shaped, row in zip(nodes, rows[start:end], strict=True):
shaped["labels"] = {"nodes": list(row.get("labels") or [])}
return connection(nodes, end < len(rows), str(end), enabled=self.issues_on)
@staticmethod
def _labeled(row: dict, name: str) -> bool:
return any(label["name"] == name for label in row.get("labels") or [])
def _create(self, argv: list[str]) -> str:
number = self.next_number
self.next_number += 1
body = Path(argv[argv.index("--body-file") + 1]).read_text(encoding="utf-8")
# The labels come from argv rather than from a constant.
# That is `projected`'s reason applied to a write.
# A fake labeling an issue the call never asked to label proves nothing.
# An unlabeled handoff is invisible to every read the script makes.
labels = [{"name": argv[i + 1]} for i, arg in enumerate(argv) if arg == "--label"]
self.issues[number] = {
"number": number,
"title": argv[argv.index("--title") + 1],
"body": body,
"state": "OPEN",
"createdAt": "2026-09-09T00:00:00Z",
"updatedAt": "2026-09-09T00:00:00Z",
"closedAt": None,
"url": f"https://github.com/o/r/issues/{number}",
"labels": labels,
}
return f"https://github.com/o/r/issues/{number}\n"
def _edit(self, argv: list[str]) -> str:
row = self.issues[int(argv[2])]
if "--body-file" in argv:
row["body"] = Path(argv[argv.index("--body-file") + 1]).read_text(encoding="utf-8")
return f"https://github.com/o/r/issues/{argv[2]}\n"
def doubled(track: str) -> str:
"""A body carrying two metadata blocks, which is the shape a hand edit produces."""
return f"{handoff.render_marker(track, 1, None)}\n{handoff.render_marker(track, 2, None)}\n"
def link(number: int, track: str, round_: int, previous: int | None, **over) -> dict:
"""One handoff issue as `gh` renders it, marked unless a case overrides the body."""
row = {
"number": number,
"title": handoff.TITLE.format(track=track, subject=f"round {round_}"),
"body": marked(f"body of round {round_}", track, round_, previous),
"state": "OPEN",
"createdAt": "2026-09-01T00:00:00Z",
"updatedAt": "2026-09-01T00:00:00Z",
"closedAt": None,
"url": f"https://github.com/o/r/issues/{number}",
"labels": [{"name": handoff.LABEL}],
}
row.update(over)
return row
def body_file(case: unittest.TestCase, text: str) -> str:
"""A handoff body on disk, removed when the case that asked for it finishes."""
directory = tempfile.mkdtemp()
path = Path(directory) / "handoff.md"
path.write_text(text, encoding="utf-8")
case.addCleanup(shutil.rmtree, directory)
return str(path)
def run(fake: FakeGh, *argv: str) -> tuple[int, str, str]:
"""One `main` call against the fake, returning its code and both streams."""
return run_with(fake, *argv)
def run_with(transport, *argv: str) -> tuple[int, str, str]:
"""One `main` call against any `run_gh` stand-in, so a case can wrap the fake."""
out, err = io.StringIO(), io.StringIO()
with (
unittest.mock.patch.object(handoff, "run_gh", transport),
contextlib.redirect_stdout(out),
contextlib.redirect_stderr(err),
):
code = handoff.main(list(argv))
return code, out.getvalue(), err.getvalue()
class MarkerCase(unittest.TestCase):
"""The chain is read from the metadata block, so a body edit never breaks it."""
def test_the_block_is_the_last_line(self) -> None:
body = marked("first\n\nsecond", "default", 3, 12)
self.assertTrue(body.rstrip().endswith("previous=12 -->"))
self.assertIn("second", body)
def test_rewriting_replaces_rather_than_appends(self) -> None:
once = marked("text", "lane", 1, None)
twice = marked(once, "lane", 2, 9)
self.assertEqual(len(handoff.MARKER.findall(twice)), 1)
self.assertEqual(
handoff.parse_marker(twice, 1),
{
"track": "lane",
"round": "2",
"previous": "9",
},
)
def test_a_body_with_no_block_reads_as_none(self) -> None:
self.assertIsNone(handoff.parse_marker("nothing here", 1))
def test_a_crlf_body_still_chains(self) -> None:
"""GitHub returns CRLF for anything typed in its web UI, and one Edit must not unchain."""
body = "notes\r\n\r\n<!-- handoff: v1 track=default round=2 previous=11 -->\r\n"
self.assertEqual(
read_marker(body, 12), {"track": "default", "round": "2", "previous": "11"}
)
def test_a_track_outside_the_slug_grammar_reads_as_no_block(self) -> None:
"""A lane no command can address must refuse rather than list as current."""
for track in ("Lane", "lane_two", "lane.two", "-lane"):
with self.subTest(track=track):
body = f"<!-- handoff: v1 track={track} round=1 previous=none -->\n"
self.assertIsNone(handoff.parse_marker(body, 1))
def test_two_blocks_refuse_rather_than_pick(self) -> None:
body = f"{handoff.render_marker('a', 1, None)}\n{handoff.render_marker('b', 2, None)}\n"
with self.assertRaises(handoff.Refusal) as caught:
handoff.parse_marker(body, 7)
self.assertIn("#7", str(caught.exception))
def test_a_retitled_issue_still_chains(self) -> None:
"""Nothing parses the title, which is what lets it carry a human subject."""
row = link(20, "default", 2, 19, title="Something a maintainer renamed it to")
self.assertEqual(read_marker(row["body"], 20)["track"], "default")
def fleet(case: unittest.TestCase, member: bool = True) -> None:
"""Pin a registry owned by `o` that lists `o/r` or not, for the rest of the case."""
names = {"r"} if member else set()
patcher = unittest.mock.patch.object(handoff, "registry", lambda: ("o", names))
patcher.start()
case.addCleanup(patcher.stop)
class LabelCase(unittest.TestCase):
"""A fleet repository missing the label refuses rather than reporting an empty chain."""
def setUp(self) -> None:
fleet(self)
def test_a_missing_label_refuses_and_names_the_fix(self) -> None:
code, _, err = run(FakeGh(label=False), "current", "--repo", "o/r")
self.assertEqual(code, 1)
self.assertIn("configure.sh apply", err)
self.assertIn(handoff.LABEL, err)
def test_create_label_is_refused_on_a_fleet_repository(self) -> None:
"""There the fleet label set is the fix, and one label alone would hide the drift."""
fake = FakeGh(label=False)
code, _, err = run(
fake,
"new",
"--repo",
"o/r",
"--title",
"T",
"--body-file",
body_file(self, "w"),
"--create-label",
)
self.assertEqual(code, 1)
self.assertIn("unregistered fork", err)
self.assertIn("configure.sh apply", err)
self.assertEqual([c[:2] for c in fake.calls], [["label", "list"]])
def test_a_full_label_window_refuses_rather_than_reporting_the_label_absent(self) -> None:
"""Otherwise the caller is sent to re-apply a set that may already be applied."""
def crowded(argv):
if argv[:2] == ["label", "list"]:
return json.dumps([{"name": f"l{n}"} for n in range(handoff.WINDOW)])
raise AssertionError("should not get past the label read")
err = io.StringIO()
with (
unittest.mock.patch.object(handoff, "run_gh", crowded),
contextlib.redirect_stdout(io.StringIO()),
contextlib.redirect_stderr(err),
):
code = handoff.main(["current", "--repo", "o/r"])
self.assertEqual(code, 1)
self.assertIn("fills the read window", err.getvalue())
def test_the_label_is_checked_before_every_subcommand(self) -> None:
"""Every one of them, read off the parser, rather than the two that are easy to drive."""
extra = {
"resume": [],
"chain": [],
"new": ["--title", "T", "--body-file", body_file(self, "w")],
"link": ["--new", "2", "--previous", "1"],
}
names = set(subcommands())
self.assertGreaterEqual(len(names), 6)
for cmd in sorted(names):
with self.subTest(cmd=cmd):
fake = FakeGh(label=False)
argv = [cmd, *extra.get(cmd, [])]
self.assertEqual(run(fake, *argv, "--repo", "o/r")[0], 1)
self.assertEqual(fake.calls[0][:2], ["label", "list"])
class OutsideFleetLabelCase(unittest.TestCase):
"""An unregistered fork with no label warns, and writes only the label it is asked to."""
def setUp(self) -> None:
fleet(self, member=False)
def new(self, fake: FakeGh, *extra: str) -> tuple[int, str, str]:
return run(
fake,
"new",
"--repo",
"o/r",
"--title",
"T",
"--body-file",
body_file(self, "w"),
*extra,
)
def test_a_read_warns_and_answers_as_an_empty_chain(self) -> None:
for cmd in ("current", "resume", "chain"):
with self.subTest(cmd=cmd):
fake = FakeGh(label=False)
code, _, err = run(fake, cmd, "--repo", "o/r")
self.assertEqual(code, 1)
self.assertIn("warning:", err)
self.assertIn(f"gh label create {handoff.LABEL} --repo o/r", err)
self.assertIn("no handoff on track", err)
self.assertNotIn("configure.sh", err)
self.assertEqual([c[:2] for c in fake.calls], [["label", "list"], ["repo", "view"]])
def test_json_on_a_fork_without_the_label_is_an_empty_array(self) -> None:
code, out, err = run(FakeGh(label=False), "tracks", "--repo", "o/r", "--json")
self.assertEqual(code, 0)
self.assertEqual(json.loads(out), [])
self.assertIn("warning:", err)
def test_tracks_warns_and_lists_nothing(self) -> None:
code, out, err = run(FakeGh(label=False), "tracks", "--repo", "o/r")
self.assertEqual(code, 0)
self.assertIn("(no open", out)
self.assertIn("warning:", err)
def test_new_without_the_flag_refuses_and_names_it(self) -> None:
fake = FakeGh(label=False)
code, _, err = self.new(fake)
self.assertEqual(code, 1)
self.assertIn("--create-label", err)
self.assertNotIn("configure.sh", err)
self.assertFalse(any(c[:2] == ["label", "create"] for c in fake.calls))
self.assertFalse(any(c[:2] == ["issue", "create"] for c in fake.calls))
def test_new_with_the_flag_creates_the_label_then_the_first_link(self) -> None:
"""The label is confirmed before the issue that needs it, and no chain read is made."""
fake = FakeGh(label=False)
code, out, _ = self.new(fake, "--create-label")
self.assertEqual(code, 0, out)
self.assertEqual(
[c[:2] for c in fake.calls],
[
["repo", "view"],
["label", "list"],
["label", "create"],
["label", "list"],
["issue", "create"],
],
)
self.assertEqual(fake.calls[2][2], handoff.LABEL)
filed = fake.issues[1001]
self.assertEqual([label["name"] for label in filed["labels"]], [handoff.LABEL])
marker = read_marker(filed["body"], 1001)
self.assertEqual((marker["round"], marker["previous"]), ("1", "none"))
def test_a_dry_run_with_the_flag_writes_nothing(self) -> None:
fake = FakeGh(label=False)
code, out, _ = self.new(fake, "--create-label", "--dry-run")
self.assertEqual(code, 0, out)
self.assertIn(f"would run: gh label create {handoff.LABEL}", out)
self.assertIn("would run: gh issue create", out)
self.assertEqual([c[:2] for c in fake.calls], [["repo", "view"], ["label", "list"]])
self.assertFalse(fake.label)
def test_a_body_new_would_refuse_creates_no_label(self) -> None:
"""Otherwise the refusal comes after a write, which leaves the fork half-changed."""
fake = FakeGh(label=False)
missing = str(Path(tempfile.mkdtemp()) / "absent.md")
self.addCleanup(shutil.rmtree, Path(missing).parent)
code, _, err = run(
fake,
"new",
"--repo",
"o/r",
"--title",
"T",
"--body-file",
missing,
"--create-label",
)
self.assertEqual(code, 1)
self.assertIn("could not read the body file", err)
self.assertFalse(any(c[:2] == ["label", "create"] for c in fake.calls))
def test_the_body_is_read_once_and_that_read_is_filed(self) -> None:
"""A second read could see a changed file after the label exists, and warns twice."""
fake = FakeGh(label=False)
path = body_file(self, "x" * (handoff.WARN_BYTES + 1))
reads: list[Path] = []
real = handoff.body_from
def counted(p: Path) -> str:
reads.append(p)
return real(p)
with unittest.mock.patch.object(handoff, "body_from", counted):
code, out, err = run(
fake,
"new",
"--repo",
"o/r",
"--title",
"T",
"--body-file",
path,
"--create-label",
)
self.assertEqual(code, 0, out + err)
self.assertEqual(len(reads), 1)
def test_an_unconfirmed_label_create_fails_before_filing(self) -> None:
fake = FakeGh(label=False)
fake.refuse_label = True
code, _, err = self.new(fake, "--create-label")
self.assertEqual(code, 2)
self.assertIn("not confirmed", err)
self.assertFalse(any(c[:2] == ["issue", "create"] for c in fake.calls))
def test_issues_turned_off_are_named_and_stop_the_label_create(self) -> None:
code, _, err = run(FakeGh(label=False, issues_on=False), "current", "--repo", "o/r")
self.assertEqual(code, 1)
self.assertIn("gh repo edit o/r --enable-issues", err)
fake = FakeGh(label=False, issues_on=False)
code, _, err = self.new(fake, "--create-label")
self.assertEqual(code, 1)
self.assertIn("--enable-issues", err)
self.assertFalse(any(c[:2] == ["label", "create"] for c in fake.calls))
def test_a_repository_under_another_owner_refuses_before_any_other_call(self) -> None:
"""A mistyped owner would otherwise put a label on a stranger's repository, then an issue."""
for argv in (("current",), ("tracks",)):
with self.subTest(argv=argv):
fake = FakeGh(label=False)
code, _, err = run(fake, *argv, "--repo", "stranger/r")
self.assertEqual(code, 1)
self.assertIn("not under o", err)
self.assertEqual([c[:2] for c in fake.calls], [["label", "list"]])
fake = FakeGh(label=False)
code, _, _ = run(
fake,
"new",
"--repo",
"stranger/r",
"--title",
"T",
"--body-file",
body_file(self, "w"),
"--create-label",
)
self.assertEqual(code, 1)
self.assertEqual([c[:2] for c in fake.calls], [])
def test_an_unregistered_repository_that_is_not_a_fork_is_drift(self) -> None:
"""It belongs in the registry, so it refuses as drift rather than taking a lone label."""
fake = FakeGh(label=False, fork=False)
code, _, err = run(fake, "tracks", "--repo", "o/r")
self.assertEqual(code, 1)
self.assertIn("registry drift", err)
self.assertIn("configure.sh apply", err)
fake = FakeGh(label=False, fork=False)
code, _, _ = self.new(fake, "--create-label")
self.assertEqual(code, 1)
self.assertEqual([c[:2] for c in fake.calls], [["repo", "view"]])
def test_the_label_created_is_the_fleet_set_s_own_definition(self) -> None:
rows = json.loads(handoff.LABELS.read_text(encoding="utf-8"))
want = next(row for row in rows if row["name"] == handoff.LABEL)
fake = FakeGh(label=False)
self.assertEqual(self.new(fake, "--create-label")[0], 0)
argv = next(c for c in fake.calls if c[:2] == ["label", "create"])
self.assertEqual(argv[argv.index("--color") + 1], want["color"])
self.assertEqual(argv[argv.index("--description") + 1], want["description"])
def test_link_refuses_without_the_label(self) -> None:
fake = FakeGh(label=False)
code, _, err = run(fake, "link", "--repo", "o/r", "--new", "2", "--previous", "1")
self.assertEqual(code, 1)
self.assertIn("--create-label", err)
self.assertEqual([c[:2] for c in fake.calls], [["repo", "view"], ["label", "list"]])
class WriteScopeCase(unittest.TestCase):
"""The writes are bounded whatever the label state, since a label opens no write by itself."""
def setUp(self) -> None:
fleet(self, member=False)
def new(self, fake: FakeGh, repo: str) -> tuple[int, str, str]:
return run(fake, "new", "--repo", repo, "--title", "T", "--body-file", body_file(self, "w"))
def test_a_labeled_repository_under_another_owner_takes_no_call_and_no_write(self) -> None:
fake = FakeGh()
code, _, err = self.new(fake, "stranger/r")
self.assertEqual(code, 1)
self.assertIn("writes nothing there", err)
self.assertEqual(fake.calls, [])
fake = FakeGh()
code, _, _ = run(fake, "link", "--repo", "stranger/r", "--new", "2", "--previous", "1")
self.assertEqual(code, 1)
self.assertEqual(fake.calls, [])
def test_a_labeled_unregistered_repository_that_is_not_a_fork_takes_no_write(self) -> None:
fake = FakeGh(fork=False)
code, _, err = self.new(fake, "o/r")
self.assertEqual(code, 1)
self.assertIn("registry drift", err)
self.assertEqual([c[:2] for c in fake.calls], [["repo", "view"]])
fake = FakeGh(fork=False)
code, _, _ = run(fake, "link", "--repo", "o/r", "--new", "2", "--previous", "1")
self.assertEqual(code, 1)
self.assertEqual([c[:2] for c in fake.calls], [["repo", "view"]])
def test_a_labeled_unregistered_fork_files_and_asks_once_whether_it_is_one(self) -> None:
fake = FakeGh()
code, out, err = self.new(fake, "o/r")
self.assertEqual(code, 0, out + err)
self.assertEqual(sum(c[:2] == ["repo", "view"] for c in fake.calls), 1)
self.assertTrue(any(c[:2] == ["issue", "create"] for c in fake.calls))
def test_a_read_of_a_labeled_repository_under_another_owner_stays_open(self) -> None:
fake = FakeGh()
code, out, _ = run(fake, "tracks", "--repo", "stranger/r")
self.assertEqual(code, 0)
self.assertIn("(no open", out)
def test_a_registered_repository_costs_no_extra_request(self) -> None:
fleet(self)
fake = FakeGh()
self.assertEqual(self.new(fake, "o/r")[0], 0)
self.assertFalse(any(c[:2] == ["repo", "view"] for c in fake.calls))
class FleetRegistryCase(unittest.TestCase):
"""Membership is read from the hub's registry, and an unreadable one is not an empty one."""
def test_the_registry_reads_lowercased_with_the_hub_in_it(self) -> None:
owner, names = REAL_REGISTRY()
self.assertEqual(owner, "ptr727")
self.assertIn("projecttemplate", names)
def test_membership_is_compared_case_insensitively_on_the_live_path(self) -> None:
"""A mixed-case registered repository is drift on the fleet path, never a fork's warning."""
fleet(self)
for repo in ("O/R", "o/R"):
with self.subTest(repo=repo):
fake = FakeGh(label=False)
code, _, err = run(fake, "tracks", "--repo", repo)
self.assertEqual(code, 1)
self.assertIn("configure.sh apply", err)
self.assertEqual([c[:2] for c in fake.calls], [["label", "list"]])
def test_an_unreadable_registry_fails_rather_than_reading_as_empty(self) -> None:
missing = Path(tempfile.mkdtemp()) / "repos.json"
self.addCleanup(shutil.rmtree, missing.parent)
with (
unittest.mock.patch.object(handoff, "REGISTRY", missing),
self.assertRaises(handoff.Execution),
):
REAL_REGISTRY()
def test_a_malformed_registry_fails_rather_than_reading_as_empty(self) -> None:
bad = Path(tempfile.mkdtemp()) / "repos.json"
self.addCleanup(shutil.rmtree, bad.parent)
for data in ({"owner": "o", "repos": [{"name": 7}]}, {"owner": 7, "repos": []}):
with self.subTest(data=data):
bad.write_text(json.dumps(data), encoding="utf-8")
with (
unittest.mock.patch.object(handoff, "REGISTRY", bad),
self.assertRaises(handoff.Execution) as caught,
):
REAL_REGISTRY()
self.assertIn("could not read the fleet registry", str(caught.exception))
class CurrentCase(unittest.TestCase):
"""Exactly one open handoff per track, and anything else is reported rather than resolved."""
def test_no_open_handoff_is_a_refusal_naming_the_track(self) -> None:
code, _, err = run(FakeGh(), "current", "--repo", "o/r", "--track", "lane")
self.assertEqual(code, 1)
self.assertIn("'lane'", err)
def test_two_on_one_track_refuses_and_names_both(self) -> None:
fake = FakeGh({4: link(4, "lane", 1, None), 5: link(5, "lane", 2, 4)})
code, _, err = run(fake, "current", "--repo", "o/r", "--track", "lane")
self.assertEqual(code, 1)
self.assertIn("#4", err)
self.assertIn("#5", err)
def test_an_unmarked_open_handoff_refuses_and_says_how_to_settle_it(self) -> None:
fake = FakeGh({6: link(6, "lane", 1, None, body="hand-written, no block")})
code, _, err = run(fake, "current", "--repo", "o/r")
self.assertEqual(code, 1)
self.assertIn("#6", err)
self.assertIn("by hand", err)
def test_one_on_the_track_prints_number_and_url(self) -> None:
fake = FakeGh({8: link(8, "default", 4, 7)})
code, out, _ = run(fake, "current", "--repo", "o/r")
self.assertEqual(code, 0)
self.assertIn("#8", out)
self.assertIn("https://github.com/o/r/issues/8", out)
self.assertIn("round=4", out)
def test_a_sibling_track_does_not_answer_for_this_one(self) -> None:
"""Parallel lanes each close their own predecessor, so neither reads the other's state."""
fake = FakeGh({9: link(9, "other", 1, None)})
self.assertEqual(run(fake, "current", "--repo", "o/r", "--track", "lane")[0], 1)
class ExitCodeCase(unittest.TestCase):
"""A finding and the check not having run never share a code."""
def test_an_execution_failure_is_two(self) -> None:
def boom(argv):
raise handoff.Execution("gh issue list failed rc=1")
out, err = io.StringIO(), io.StringIO()
with (
unittest.mock.patch.object(handoff, "run_gh", boom),
contextlib.redirect_stdout(out),
contextlib.redirect_stderr(err),
):
code = handoff.main(["current", "--repo", "o/r"])
self.assertEqual(code, 2)
self.assertIn("failed", err.getvalue())
def test_a_full_read_window_refuses_rather_than_undercounting(self) -> None:
rows = {n: link(n, f"lane-{n}", 1, None) for n in range(1, handoff.WINDOW + 1)}
code, _, err = run(FakeGh(rows), "tracks", "--repo", "o/r")
self.assertEqual(code, 1)
self.assertIn("window", err)
def test_a_long_unreadable_list_is_cut_the_way_gh_stderr_is(self) -> None:
"""A refusal nobody can read is a refusal that does not land."""
rows = {
n: link(n, "lane", 1, None, state="CLOSED", body=f"no block on issue number {n}")
for n in range(1, 400)
}
code, _, err = run(FakeGh(rows), "chain", "--repo", "o/r", "--track", "lane")
self.assertEqual(code, 1)
self.assertIn("more character(s) not shown", err)
self.assertLess(len(err), handoff.STDERR_CAP + 500)
def test_a_full_closed_window_refuses_only_where_no_link_was_found(self) -> None:
"""A closed link past the window reads as a track that never had one, which orphans it."""
rows = {
n: link(n, f"lane-{n}", 1, None, state="CLOSED")
for n in range(1, handoff.CLOSED_WINDOW + 1)
}
code, _, err = run(FakeGh(rows), "chain", "--repo", "o/r", "--track", "absent-lane")
self.assertEqual(code, 1)
self.assertIn("fills the read window", err)
self.assertIn("second chain beside the first", err)
def test_a_full_closed_window_does_not_block_a_track_it_did_contain(self) -> None:
"""Closed links accumulate one per round, so refusing on a full page alone is a wall."""
rows = {
n: link(n, f"lane-{n}", 1, None, state="CLOSED")
for n in range(1, handoff.CLOSED_WINDOW + 1)
}
code, out, _ = run(FakeGh(rows), "chain", "--repo", "o/r", "--track", "lane-7")
self.assertEqual(code, 0)
self.assertIn("#7", out)
def test_a_closed_head_reads_the_closed_list_once_per_command(self) -> None:
"""A second read would let the head and its doubts come from two snapshots."""
rows = {1: link(1, "lane", 1, None, state="CLOSED")}
gh = FakeGh(rows)
code, _, _ = run(gh, "chain", "--repo", "o/r", "--track", "lane")
self.assertEqual(code, 0)
reads = [c for c in gh.calls if c[:2] == ["api", "graphql"] and "states[]=CLOSED" in c]
self.assertEqual(len(reads), 1)
def test_a_usage_error_refuses_at_one_rather_than_sharing_argparse_s_two(self) -> None:
"""Two is the command not having run, so a mistyped flag must not land on it."""
err = io.StringIO()
with self.assertRaises(SystemExit) as caught, contextlib.redirect_stderr(err):
handoff.main(["current", "--repo", "justaname"])
self.assertEqual(caught.exception.code, 1)
self.assertIn("refused:", err.getvalue())
def test_a_below_one_argument_names_the_flag_the_caller_typed(self) -> None:
"""`new` and `previous` without their dashes name no flag the caller could have passed."""
err = io.StringIO()
with self.assertRaises(SystemExit), contextlib.redirect_stderr(err):
handoff.main(["link", "--repo", "o/r", "--new", "0", "--previous", "1"])
self.assertIn("--new takes an issue number", err.getvalue())
def test_a_round_below_one_never_reaches_the_block(self) -> None:
"""`round=0` parses nowhere, so writing it labels an issue no read can ever see again."""
with self.assertRaises(SystemExit), contextlib.redirect_stderr(io.StringIO()):
handoff.main(["chain", "--repo", "o/r", "--track", "lane", "--limit", "0"])
def test_a_history_or_limit_below_one_is_a_usage_error(self) -> None:
for flag, cmd in (("--history", "resume"), ("--limit", "chain")):
with (
self.subTest(flag=flag),
self.assertRaises(SystemExit),
contextlib.redirect_stderr(io.StringIO()),
):
handoff.main([cmd, "--repo", "o/r", flag, "0"])
def test_a_three_part_repo_is_a_usage_error(self) -> None:
"""OWNER/NAME has one slash, and `o/r/x` is the near-miss a bare check still admits."""
with self.assertRaises(SystemExit), contextlib.redirect_stderr(io.StringIO()):
handoff.main(["current", "--repo", "o/r/x"])
def test_an_unknown_flag_refuses_at_one_too(self) -> None:
with self.assertRaises(SystemExit) as caught, contextlib.redirect_stderr(io.StringIO()):
handoff.main(["current", "--repo", "o/r", "--nonsense"])
self.assertEqual(caught.exception.code, 1)
def test_an_unmodeled_exception_is_two_rather_than_cpython_s_one(self) -> None:
"""CPython exits 1 on an uncaught exception, which would read as a refusal."""
def wrong_shape(argv):
if argv[:2] == ["label", "list"]:
return json.dumps([{"name": handoff.LABEL}])
# A row of the right shape carrying a timestamp `gh` would never emit.
# No reader validates that, because none could name every field's own grammar.
return connection([{"number": 1, "updatedAt": None, "title": "t", "body": ""}])
out, err = io.StringIO(), io.StringIO()
with (
unittest.mock.patch.object(handoff, "run_gh", wrong_shape),
contextlib.redirect_stdout(out),
contextlib.redirect_stderr(err),
):
code = handoff.main(["tracks", "--repo", "o/r"])
self.assertEqual(code, 2)
self.assertIn("unmodeled", err.getvalue())
def test_a_track_that_is_not_a_slug_is_a_usage_error(self) -> None:
for track in ("Not A Slug", "sess\n", "lane\ttwo"):
with (
self.subTest(track=track),
self.assertRaises(SystemExit),
contextlib.redirect_stderr(io.StringIO()),
):
handoff.main(["current", "--repo", "o/r", "--track", track])
class NewCase(unittest.TestCase):
"""Create, comment, close, in that order, so a failure leaves a discoverable successor."""
def body_file(self, text: str) -> str:
return body_file(self, text)
def test_the_three_steps_run_in_order(self) -> None:
fake = FakeGh({30: link(30, "default", 2, 29)})
code, _, _ = run(
fake, "new", "--repo", "o/r", "--title", "Next", "--body-file", self.body_file("work")
)
self.assertEqual(code, 0)
writes = [
c[:2]
for c in fake.calls
if c[:2] in (["issue", "create"], ["issue", "comment"], ["issue", "close"])
]
self.assertEqual(writes, [["issue", "create"], ["issue", "comment"], ["issue", "close"]])
self.assertEqual(fake.issues[30]["state"], "CLOSED")
body = next(c for c in fake.calls if c[:2] == ["issue", "comment"])
self.assertIn("Continued in #1001", body[body.index("--body") + 1])
def test_new_onto_a_closed_head_reads_the_closed_list_once(self) -> None:
"""`new` shares `chain`'s head resolution, so it holds the same single read."""
rows = {1: link(1, "lane", 1, None, state="CLOSED")}
gh = FakeGh(rows)
code, _, _ = run(
gh,
"new",
"--repo",
"o/r",
"--track",
"lane",
"--title",
"t",
"--body-file",
self.body_file("work"),
"--dry-run",
)
self.assertEqual(code, 0)
reads = [c for c in gh.calls if c[:2] == ["api", "graphql"] and "states[]=CLOSED" in c]
self.assertEqual(len(reads), 1)
def test_the_round_increments_from_the_previous_link(self) -> None:
fake = FakeGh({30: link(30, "default", 7, 29)})
run(fake, "new", "--repo", "o/r", "--title", "Next", "--body-file", self.body_file("work"))
self.assertEqual(read_marker(fake.issues[1001]["body"], 1001)["round"], "8")
self.assertEqual(read_marker(fake.issues[1001]["body"], 1001)["previous"], "30")
def test_a_closed_out_lane_chains_on_rather_than_starting_a_second_chain(self) -> None:
"""The orphan case: no open handoff on a track is not the same as no handoff at all.
Reading the second as the first files round 1 with `previous=none` beside a chain that
already exists, which is exactly the lost history the chain replaces a file to avoid.
"""
fake = FakeGh({30: link(30, "default", 4, 29, state="CLOSED")})
code, out, _ = run(
fake, "new", "--repo", "o/r", "--title", "Next", "--body-file", self.body_file("work")
)
self.assertEqual(code, 0)
marker = read_marker(fake.issues[1001]["body"], 1001)
self.assertEqual(marker["round"], "5")
self.assertEqual(marker["previous"], "30")
self.assertIn("already closed", out)
def test_a_closed_predecessor_is_linked_but_not_closed_again(self) -> None:
fake = FakeGh({30: link(30, "default", 1, None, state="CLOSED")})
run(fake, "new", "--repo", "o/r", "--title", "Next", "--body-file", self.body_file("work"))
writes = [c[:2] for c in fake.calls]
self.assertIn(["issue", "comment"], writes)
self.assertNotIn(["issue", "close"], writes)
def test_a_closed_lane_on_another_track_does_not_chain_this_one(self) -> None:
fake = FakeGh({30: link(30, "other", 4, 29, state="CLOSED")})
run(
fake,
"new",
"--repo",
"o/r",
"--track",
"lane",
"--title",
"First",
"--body-file",
self.body_file("work"),
)
marker = read_marker(fake.issues[1001]["body"], 1001)
self.assertEqual(marker, {"track": "lane", "round": "1", "previous": "none"})
def test_the_first_handoff_on_a_track_closes_nothing(self) -> None:
fake = FakeGh()
code, out, _ = run(
fake, "new", "--repo", "o/r", "--title", "First", "--body-file", self.body_file("work")
)
self.assertEqual(code, 0)
self.assertNotIn(["issue", "close"], [c[:2] for c in fake.calls])
self.assertNotIn(["issue", "comment"], [c[:2] for c in fake.calls])