Repository navigation
Expand file tree
/
Copy pathtest-sync-github-forks
More file actions
executable file
·604 lines (476 loc) · 23.1 KB
/
Copy pathtest-sync-github-forks
File metadata and controls
executable file
·604 lines (476 loc) · 23.1 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
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "httpx>=0.27",
# "rich>=15.0",
# ]
# ///
"""Tests for sync-github-forks. Run with: ./test-sync-github-forks -v"""
import contextlib
import importlib.util
import io
import json
import sys
import tempfile
import unittest
from datetime import datetime, timedelta, timezone
from importlib.machinery import SourceFileLoader
from pathlib import Path
from unittest import mock
import httpx
def _load_script():
"""Import the extensionless `sync-github-forks` script as a module."""
path = Path(__file__).resolve().parent / "sync-github-forks"
loader = SourceFileLoader("sync_github_forks", str(path))
spec = importlib.util.spec_from_loader(loader.name, loader)
module = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = module # dataclasses resolve their module via sys.modules
loader.exec_module(module)
return module
sgf = _load_script()
NOW = datetime(2026, 6, 8, 12, 0, tzinfo=timezone.utc)
EARLIER = NOW - timedelta(hours=1)
LATER = NOW + timedelta(hours=1)
def github_with(handler) -> sgf.GitHub:
"""A GitHub client whose HTTP calls are served by `handler` (no network)."""
gh = sgf.GitHub("token")
gh.client = httpx.Client(
base_url="https://api.github.com", transport=httpx.MockTransport(handler)
)
return gh
class ShouldCheckTests(unittest.TestCase):
"""The gate that decides whether a fork is examined this run."""
def test_stale_upstream_not_conflicted_is_skipped(self):
parent = {"pushedAt": EARLIER.isoformat()}
self.assertFalse(sgf.should_check(parent, NOW, was_conflicted=False))
def test_fresh_upstream_is_checked(self):
parent = {"pushedAt": LATER.isoformat()}
self.assertTrue(sgf.should_check(parent, NOW, was_conflicted=False))
def test_regression_conflicted_fork_is_rechecked_even_with_stale_upstream(self):
# The bug: a fork left in conflict whose upstream has NOT moved since our
# baseline used to be skipped, so the conflict silently "vanished" next run.
parent = {"pushedAt": EARLIER.isoformat()}
self.assertTrue(sgf.should_check(parent, NOW, was_conflicted=True))
def test_no_timestamp_forces_check(self):
self.assertTrue(sgf.should_check({}, NOW, was_conflicted=False))
class CommitsBehindTests(unittest.TestCase):
def test_uses_upstream_branch_name_on_head_side(self):
seen = {}
def handler(request: httpx.Request) -> httpx.Response:
seen["path"] = request.url.path
return httpx.Response(200, json={"ahead_by": 4})
gh = github_with(handler)
behind = gh.commits_behind("me/fork", "master", "up", "main")
self.assertEqual(behind, 4)
self.assertEqual(seen["path"], "/repos/me/fork/compare/master...up:main")
def test_failure_returns_none_not_zero(self):
gh = github_with(lambda req: httpx.Response(404, json={}))
self.assertIsNone(gh.commits_behind("me/fork", "main", "up", "main"))
class SyncForkRecheckTests(unittest.TestCase):
def setUp(self):
self._delay = sgf.CONFLICT_RECHECK_DELAY
sgf.CONFLICT_RECHECK_DELAY = 0 # don't sleep in tests
def tearDown(self):
sgf.CONFLICT_RECHECK_DELAY = self._delay
def test_persistent_conflict_stays_conflict(self):
gh = github_with(lambda req: httpx.Response(409, text="conflict"))
result = gh.sync_fork("me/fork", "main")
self.assertTrue(result.conflict)
self.assertFalse(result.flaky)
def test_transient_conflict_clears_and_is_flagged_flaky(self):
calls = {"n": 0}
def handler(request: httpx.Request) -> httpx.Response:
calls["n"] += 1
if calls["n"] == 1:
return httpx.Response(409, text="conflict")
return httpx.Response(200, json={"merge_type": "fast-forward"})
gh = github_with(handler)
result = gh.sync_fork("me/fork", "main")
self.assertEqual(calls["n"], 2)
self.assertTrue(result.success)
self.assertTrue(result.flaky)
self.assertFalse(result.conflict)
def test_clean_merge_does_not_recheck(self):
calls = {"n": 0}
def handler(request: httpx.Request) -> httpx.Response:
calls["n"] += 1
return httpx.Response(200, json={"merge_type": "fast-forward"})
gh = github_with(handler)
result = gh.sync_fork("me/fork", "main")
self.assertEqual(calls["n"], 1)
self.assertTrue(result.success)
class ShouldAutoResolveTests(unittest.TestCase):
"""The threshold gate for auto-resolving a long-standing conflict."""
def test_at_threshold_not_resolved(self):
self.assertFalse(sgf.should_auto_resolve(sgf.AUTO_RESOLVE_AFTER_RUNS))
def test_one_past_threshold_is_resolved(self):
self.assertTrue(sgf.should_auto_resolve(sgf.AUTO_RESOLVE_AFTER_RUNS + 1))
def test_well_under_threshold_not_resolved(self):
self.assertFalse(sgf.should_auto_resolve(1))
class ExceedsDiscardLimitTests(unittest.TestCase):
"""The cap on how many of a fork's own commits auto-resolve may discard."""
def test_at_limit_still_discards(self):
self.assertFalse(sgf.exceeds_discard_limit(sgf.MAX_DISCARD_COMMITS))
def test_one_past_limit_needs_review(self):
self.assertTrue(sgf.exceeds_discard_limit(sgf.MAX_DISCARD_COMMITS + 1))
def test_typical_small_divergence_discards(self):
self.assertFalse(sgf.exceeds_discard_limit(3))
class UpstreamDivergenceTests(unittest.TestCase):
def test_parses_counts_and_merge_base_from_compare(self):
seen = {}
def handler(request: httpx.Request) -> httpx.Response:
seen["path"] = request.url.path
return httpx.Response(
200,
json={
"ahead_by": 4, # upstream ahead of fork -> fork behind by 4
"behind_by": 3, # fork ahead of upstream -> 3 divergent commits
"merge_base_commit": {"sha": "base123"},
},
)
gh = github_with(handler)
div = gh.upstream_divergence("me/fork", "master", "up", "main")
self.assertEqual(seen["path"], "/repos/me/fork/compare/master...up:main")
self.assertEqual(div.behind, 4)
self.assertEqual(div.diverged, 3)
self.assertEqual(div.merge_base_sha, "base123")
def test_failure_returns_none(self):
gh = github_with(lambda req: httpx.Response(404, json={}))
self.assertIsNone(gh.upstream_divergence("me/fork", "main", "up", "main"))
def test_missing_merge_base_returns_none(self):
gh = github_with(lambda req: httpx.Response(200, json={"ahead_by": 1, "behind_by": 1}))
self.assertIsNone(gh.upstream_divergence("me/fork", "main", "up", "main"))
class ForceResolveTests(unittest.TestCase):
def test_reset_branch_forces_ref_update(self):
seen = {}
def handler(request: httpx.Request) -> httpx.Response:
seen["method"] = request.method
seen["path"] = request.url.path
seen["body"] = json.loads(request.content)
return httpx.Response(200, json={})
gh = github_with(handler)
gh.reset_branch("me/fork", "main", "base123")
self.assertEqual(seen["method"], "PATCH")
self.assertEqual(seen["path"], "/repos/me/fork/git/refs/heads/main")
self.assertEqual(seen["body"], {"sha": "base123", "force": True})
def test_resets_then_fast_forwards(self):
calls = []
def handler(request: httpx.Request) -> httpx.Response:
calls.append((request.method, request.url.path))
if request.method == "PATCH":
return httpx.Response(200, json={})
return httpx.Response(200, json={"merge_type": "fast-forward"})
gh = github_with(handler)
result = gh.force_resolve("me/fork", "main", "base123")
self.assertTrue(result.success)
self.assertFalse(result.no_op)
self.assertEqual(calls[0], ("PATCH", "/repos/me/fork/git/refs/heads/main"))
self.assertEqual(calls[1], ("POST", "/repos/me/fork/merge-upstream"))
def test_failed_reset_does_not_merge(self):
calls = []
def handler(request: httpx.Request) -> httpx.Response:
calls.append(request.method)
return httpx.Response(422, text="reset rejected")
gh = github_with(handler)
result = gh.force_resolve("me/fork", "main", "base123")
self.assertFalse(result.success)
self.assertIn("branch reset failed", result.error)
self.assertEqual(calls, ["PATCH"]) # never attempted the merge
class StateRoundTripTests(unittest.TestCase):
def setUp(self):
self._orig = sgf.STATE_FILE
def tearDown(self):
sgf.STATE_FILE = self._orig
def _use_tmp(self, tmpdir):
sgf.STATE_FILE = Path(tmpdir) / "state.json"
def test_save_then_load(self):
with tempfile.TemporaryDirectory() as tmp:
self._use_tmp(tmp)
conflicts = {"me/fork": {"first_seen": NOW.isoformat(), "runs": 2}}
daily = {"date": "2026-06-08", "synced": {"a": 3}}
report = {"last_slot": "2026-06-08T08:50", "pending": {"flaky": ["a"]}}
sgf.save_state(NOW, conflicts, daily, report)
last_run, loaded, loaded_daily, loaded_report = sgf.load_state()
self.assertEqual(loaded_report, report)
self.assertEqual(last_run, NOW)
self.assertEqual(loaded, conflicts)
self.assertEqual(loaded_daily, daily)
def test_legacy_state_without_conflicts_key(self):
with tempfile.TemporaryDirectory() as tmp:
sgf.STATE_FILE = Path(tmp) / "state.json"
sgf.STATE_FILE.write_text(json.dumps({"last_run": NOW.isoformat()}))
last_run, loaded, daily, report = sgf.load_state()
self.assertEqual(report, {})
self.assertEqual(last_run, NOW)
self.assertEqual(loaded, {})
self.assertEqual(daily, {})
def test_missing_file(self):
with tempfile.TemporaryDirectory() as tmp:
sgf.STATE_FILE = Path(tmp) / "nope.json"
self.assertEqual(sgf.load_state(), (None, {}, {}, {}))
def test_save_creates_missing_config_dir(self):
with tempfile.TemporaryDirectory() as tmp:
sgf.STATE_FILE = Path(tmp) / "sync-github-forks" / "state.json"
sgf.save_state(NOW, {}, {}, {})
self.assertTrue(sgf.STATE_FILE.exists())
def test_default_location_is_under_config_dir(self):
self.assertEqual(sgf.STATE_FILE.name, "state.json")
self.assertEqual(sgf.STATE_FILE.parent.name, "sync-github-forks")
class LocalTimestampTests(unittest.TestCase):
def test_converts_utc_with_offset(self):
mountain = timezone(timedelta(hours=-6))
self.assertEqual(sgf.local_timestamp(NOW, mountain), "2026-06-08 06:00:00 -0600")
def test_defaults_to_machine_local_time(self):
self.assertEqual(
sgf.local_timestamp(NOW), NOW.astimezone().strftime("%Y-%m-%d %H:%M:%S %z")
)
class LocalTodayTests(unittest.TestCase):
def test_returns_iso_date_string(self):
self.assertRegex(sgf.local_today(), r"^\d{4}-\d{2}-\d{2}$")
class BuildRunReportTests(unittest.TestCase):
def test_includes_brief_synced_line(self):
report = "\n".join(sgf.build_run_report({3: ["a"]}, [], [], [], []))
self.assertIn("*Synced Repositories:* 3 commits across 1 repo", report)
def test_conflict_shows_persistence_duration(self):
report = "\n".join(
sgf.build_run_report({}, [("fork", 3, EARLIER.isoformat())], [], [], [])
)
self.assertIn("unresolved across 3 runs", report)
def test_resolved_section_reports_self_clearing(self):
report = "\n".join(
sgf.build_run_report(
{}, [], [], [("fork", {"first_seen": EARLIER.isoformat(), "runs": 2})], []
)
)
self.assertIn("Cleared Since Last Report", report)
self.assertIn("cleared without intervention after being flagged 2 runs", report)
def test_flaky_section(self):
report = "\n".join(sgf.build_run_report({}, [], [], [], ["fork"]))
self.assertIn("Transient Conflicts", report)
self.assertIn("`fork`", report)
def test_force_resolved_section(self):
report = "\n".join(
sgf.build_run_report({}, [], [], [], [], force_resolved=[("fork", 11, 3)])
)
self.assertIn("Auto-Resolved Conflicts", report)
self.assertIn("discarded 3 commits", report)
self.assertIn("after 11 runs", report)
def test_force_resolved_singular_commit(self):
report = "\n".join(
sgf.build_run_report({}, [], [], [], [], force_resolved=[("fork", 6, 1)])
)
self.assertIn("discarded 1 commit and", report)
def test_needs_review_section(self):
report = "\n".join(
sgf.build_run_report({}, [], [], [], [], needs_review=[("fork", 7, 34)])
)
self.assertIn("Review Required", report)
self.assertIn("34 commits ahead of upstream after 7 runs", report)
self.assertIn(str(sgf.MAX_DISCARD_COMMITS), report)
def test_needs_review_omitted_when_empty(self):
self.assertNotIn("Review Required", "\n".join(sgf.build_run_report({}, [], [], [], [])))
def test_prev_day_block_precedes_brief_line(self):
prev = sgf.build_daily_summary({"a": 5}, "2026-06-18")
report = "\n".join(
sgf.build_run_report({3: ["b"]}, [], [], [], [], prev_day_lines=prev)
)
self.assertLess(report.index("Daily Sync Summary"), report.index("3 commits across 1 repo"))
class DailySummaryTests(unittest.TestCase):
def test_groups_by_total_descending(self):
text = "\n".join(
sgf.build_daily_summary({"repo-a": 14, "repo-b": 3, "repo-c": 3}, "2026-06-18")
)
self.assertIn("*📅 Daily Sync Summary — 2026-06-18*", text)
self.assertIn("• 14 commits: `repo-a`", text)
self.assertIn("• 3 commits: `repo-b`, `repo-c`", text)
self.assertLess(text.index("14 commits"), text.index("3 commits"))
def test_empty_returns_no_lines(self):
self.assertEqual(sgf.build_daily_summary({}, "2026-06-18"), [])
def test_unknown_count_bucket(self):
text = "\n".join(sgf.build_daily_summary({"repo-x": -1}, "2026-06-18"))
self.assertIn("unknown commit count: `repo-x`", text)
def test_singular_commit(self):
text = "\n".join(sgf.build_daily_summary({"repo-a": 1}, "2026-06-18"))
self.assertIn("• 1 commit: `repo-a`", text)
class BriefSyncedLineTests(unittest.TestCase):
def test_sums_commits_and_counts_repos(self):
self.assertEqual(
sgf.brief_synced_line({14: ["a"], 3: ["b", "c"]}),
"*Synced Repositories:* 20 commits across 3 repos",
)
def test_empty_run(self):
self.assertEqual(
sgf.brief_synced_line({}),
"*Synced Repositories:* 0 commits across 0 repos",
)
def test_unknown_count_counts_repo_not_commits(self):
self.assertEqual(
sgf.brief_synced_line({-1: ["a"], 5: ["b"]}),
"*Synced Repositories:* 5 commits across 2 repos",
)
def test_singular(self):
self.assertEqual(
sgf.brief_synced_line({1: ["a"]}),
"*Synced Repositories:* 1 commit across 1 repo",
)
class AccrueSyncedTests(unittest.TestCase):
def test_adds_new_repos(self):
self.assertEqual(sgf.accrue_synced({}, {3: ["a"], 5: ["b"]}), {"a": 3, "b": 5})
def test_sums_repeat_repo_across_runs(self):
self.assertEqual(sgf.accrue_synced({"a": 3}, {5: ["a"]}), {"a": 8})
def test_unknown_makes_repo_unknown(self):
self.assertEqual(sgf.accrue_synced({"a": 3}, {-1: ["a"]}), {"a": -1})
def test_unknown_is_sticky(self):
self.assertEqual(sgf.accrue_synced({"a": -1}, {5: ["a"]}), {"a": -1})
def test_does_not_mutate_input(self):
original = {"a": 3}
sgf.accrue_synced(original, {5: ["a"]})
self.assertEqual(original, {"a": 3})
class DailyRolloverTests(unittest.TestCase):
def test_same_day_carries_accumulator(self):
report, acc = sgf.daily_rollover({"date": "2026-06-19", "synced": {"a": 3}}, "2026-06-19")
self.assertEqual(report, [])
self.assertEqual(acc, {"a": 3})
def test_new_day_reports_and_resets(self):
report, acc = sgf.daily_rollover({"date": "2026-06-18", "synced": {"a": 3}}, "2026-06-19")
self.assertIn("Daily Sync Summary — 2026-06-18", "\n".join(report))
self.assertEqual(acc, {})
def test_new_day_with_no_accruals_no_report(self):
report, acc = sgf.daily_rollover({"date": "2026-06-18", "synced": {}}, "2026-06-19")
self.assertEqual(report, [])
self.assertEqual(acc, {})
def test_first_ever_run_no_report(self):
report, acc = sgf.daily_rollover({}, "2026-06-19")
self.assertEqual(report, [])
self.assertEqual(acc, {})
def test_multi_day_gap_reports_under_accrual_date(self):
report, acc = sgf.daily_rollover({"date": "2026-06-15", "synced": {"a": 2}}, "2026-06-19")
self.assertIn("2026-06-15", "\n".join(report))
self.assertEqual(acc, {})
class ConsoleLoggingTests(unittest.TestCase):
"""What lands in the scheduled job's log file."""
def test_errors_are_printed_verbatim(self):
# Brackets must not be eaten as rich markup, and long lines must not wrap.
error = 'repo: {"errors":["[/bad]"]} ' + "x" * 200
with sgf.console.capture() as capture:
sgf.print_errors([error])
self.assertIn(error, capture.get())
def test_no_errors_prints_nothing(self):
with sgf.console.capture() as capture:
sgf.print_errors([])
self.assertEqual(capture.get(), "")
def test_slack_failure_does_not_log_webhook_url(self):
url = "https://hooks.slack.test/services/SECRET"
request = httpx.Request("POST", url)
failures = [
{"return_value": httpx.Response(404, request=request)},
{"side_effect": httpx.ConnectError(f"cannot reach {url}", request=request)},
]
for failure, expected in zip(failures, ["HTTP 404", "ConnectError"]):
with mock.patch.object(sgf.httpx, "post", **failure):
with sgf.console.capture() as capture:
sgf.notify_slack(url, ["report"])
self.assertIn(expected, capture.get())
self.assertNotIn("SECRET", capture.get())
class ReportScheduleTests(unittest.TestCase):
"""Slack is posted once per slot: 02:50, 08:50, 14:50 and 20:50 local."""
def test_slot_starts_exactly_on_report_time(self):
self.assertEqual(sgf.report_slot(datetime(2026, 6, 8, 8, 50)), "2026-06-08T08:50")
def test_just_before_report_time_is_previous_slot(self):
self.assertEqual(sgf.report_slot(datetime(2026, 6, 8, 8, 49)), "2026-06-08T02:50")
def test_late_run_stays_in_same_slot(self):
self.assertEqual(sgf.report_slot(datetime(2026, 6, 8, 19, 50)), "2026-06-08T14:50")
def test_before_first_slot_belongs_to_previous_day(self):
self.assertEqual(sgf.report_slot(datetime(2026, 6, 8, 1, 50)), "2026-06-07T20:50")
class PendingReportTests(unittest.TestCase):
"""Results held between hourly runs until the next report."""
def test_accumulates_across_runs(self):
first = sgf.add_to_pending(
{},
synced_by_count={3: ["a"]},
errors=["x: boom"],
force_resolved=[("f", 16, 2)],
flaky=["a"],
)
second = sgf.add_to_pending(
first,
synced_by_count={2: ["a", "b"]},
errors=["x: boom", "y: bang"],
resolved=[("c", {"runs": 1})],
flaky=["a"],
day_lines=["summary"],
)
self.assertEqual(second["synced"], {"a": 5, "b": 2})
self.assertEqual(second["errors"], ["x: boom", "y: bang"]) # repeats listed once
self.assertEqual(second["force_resolved"], [("f", 16, 2)])
self.assertEqual(second["resolved"], [("c", {"runs": 1})])
self.assertEqual(second["flaky"], ["a"])
self.assertEqual(second["day_lines"], ["summary"])
self.assertEqual(first["synced"], {"a": 3}) # input not mutated
class MainReportingTests(unittest.TestCase):
"""main() end to end, with GitHub and Slack faked."""
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
github = mock.Mock()
github.forks.return_value = [
{
"nameWithOwner": "me/fork",
"defaultBranchRef": {"name": "main"},
"parent": {"owner": {"login": "up"}, "defaultBranchRef": {"name": "main"}},
}
]
github.commits_behind.return_value = 3
github.sync_fork.return_value = sgf.SyncResult(success=True)
self.slot = "slot-1"
self.post = mock.Mock(return_value=True)
for patcher in (
mock.patch.object(sgf, "STATE_FILE", Path(tmp.name) / "state.json"),
mock.patch.object(sgf, "GitHub", return_value=github),
mock.patch.object(sgf, "resolve_token", return_value="t"),
mock.patch.object(sgf, "notify_slack", self.post),
mock.patch.object(sgf, "report_slot", lambda now: self.slot),
mock.patch.dict(sgf.os.environ, {"SLACK_WEBHOOK_URL": "https://slack.test"}),
):
patcher.start()
self.addCleanup(patcher.stop)
def run_main(self):
"""Run main(); return (console output, stderr output)."""
stderr = io.StringIO()
with sgf.console.capture() as capture, contextlib.redirect_stderr(stderr):
sgf.main()
return capture.get(), stderr.getvalue()
def test_run_header_goes_to_stdout_and_stderr(self):
out, err = self.run_main()
for stream in (out, err):
self.assertRegex(stream, r"=== Run started \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} [+-]\d{4} ===")
def test_last_run_shown_in_local_time(self):
self.run_main()
out, _ = self.run_main()
self.assertRegex(out, r"Last successful run: \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} [+-]\d{4}\n")
self.assertNotIn("UTC", out)
def posted(self):
return "\n".join(self.post.call_args.args[1])
def test_posts_only_when_a_new_slot_begins(self):
self.run_main()
self.run_main()
self.post.assert_not_called()
self.slot = "slot-2"
self.run_main()
self.run_main()
self.post.assert_called_once()
self.assertIn("9 commits across 1 repo", self.posted())
# only the run after the report is still pending
self.assertEqual(sgf.load_state()[3]["pending"]["synced"], {"fork": 3})
def test_failed_post_keeps_results_for_next_run(self):
self.run_main()
self.slot = "slot-2"
self.post.return_value = False
self.run_main()
self.post.return_value = True
self.run_main()
self.assertEqual(self.post.call_count, 2)
self.assertIn("9 commits across 1 repo", self.posted())
if __name__ == "__main__":
unittest.main()