-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathgithub-sync.test.ts
More file actions
1831 lines (1571 loc) · 56.1 KB
/
github-sync.test.ts
File metadata and controls
1831 lines (1571 loc) · 56.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
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
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import nock from "nock";
import {
GitHubSyncService,
getGitHubToken,
createGitHubSyncService,
createGitHubSyncServiceOrThrow,
} from "./github/index.js";
import type { TaskStore, GithubMetadata } from "../types.js";
import type { SyncResult } from "./sync/registry.js";
/**
* Cast SyncResult metadata to GithubMetadata for test assertions.
*/
function getGitHubMetadata(
result: SyncResult | null | undefined,
): GithubMetadata | undefined {
return result?.metadata as GithubMetadata | undefined;
}
import type { GitHubMock } from "../test-utils/github-mock.js";
import {
setupGitHubMock,
cleanupGitHubMock,
createIssueFixture,
createTask,
createStore,
} from "../test-utils/github-mock.js";
// Mock git remote detection
vi.mock("./github/remote.js", async (importOriginal) => {
const original = await importOriginal<typeof import("./github/remote.js")>();
return {
...original,
getGitHubRepo: vi.fn(() => ({ owner: "test-owner", repo: "test-repo" })),
};
});
// Mock execSync for git operations
vi.mock("node:child_process", async (importOriginal) => {
const original = await importOriginal<typeof import("node:child_process")>();
return {
...original,
execSync: vi.fn((cmd: string) => {
if (cmd.includes("gh auth token")) {
throw new Error("gh not authenticated");
}
// Default: commits are on remote (for most tests)
if (cmd.includes("git merge-base --is-ancestor")) {
return ""; // Success = commit is on remote
}
return "";
}),
};
});
describe("GitHubSyncService", () => {
let service: GitHubSyncService;
let githubMock: GitHubMock;
let originalEnv: string | undefined;
beforeEach(() => {
originalEnv = process.env.GITHUB_TOKEN;
process.env.GITHUB_TOKEN = "test-token";
githubMock = setupGitHubMock();
service = new GitHubSyncService({
repo: { owner: "test-owner", repo: "test-repo" },
token: "test-token",
});
});
afterEach(() => {
cleanupGitHubMock();
if (originalEnv !== undefined) {
process.env.GITHUB_TOKEN = originalEnv;
} else {
delete process.env.GITHUB_TOKEN;
}
vi.restoreAllMocks();
});
describe("syncTask", () => {
describe("401 unauthorized errors", () => {
it("throws error when creating issue with invalid token", async () => {
const task = createTask();
const store = createStore([task]);
// First, search for existing issue returns 401
githubMock.listIssues401("test-owner", "test-repo");
await expect(service.syncTask(task, store)).rejects.toThrow();
});
it("throws error when updating issue with invalid token", async () => {
const task = createTask({
metadata: {
github: {
issueNumber: 123,
issueUrl: "https://github.com/test-owner/test-repo/issues/123",
repo: "test-owner/test-repo",
},
},
});
const store = createStore([task]);
// Get issue returns 401
githubMock.getIssue401("test-owner", "test-repo", 123);
await expect(service.syncTask(task, store)).rejects.toThrow();
});
});
describe("403 forbidden errors", () => {
it("throws error when rate limited during issue creation", async () => {
const task = createTask();
const store = createStore([task]);
// Search returns rate limit error
githubMock.listIssues403("test-owner", "test-repo", true);
await expect(service.syncTask(task, store)).rejects.toThrow();
});
it("throws error when lacking permissions to update issue", async () => {
const task = createTask({
metadata: {
github: {
issueNumber: 456,
issueUrl: "https://github.com/test-owner/test-repo/issues/456",
repo: "test-owner/test-repo",
},
},
});
const store = createStore([task]);
// Get issue returns 403 forbidden
githubMock.getIssue403("test-owner", "test-repo", 456, false);
await expect(service.syncTask(task, store)).rejects.toThrow();
});
});
describe("404 not found errors", () => {
it("creates new issue when no existing issue tracked", async () => {
// Task without any GitHub metadata - needs to search then create
const task = createTask({ id: "brand-new-task" });
const store = createStore([task]);
// Search for existing issue by task ID - none found
githubMock.listIssues("test-owner", "test-repo", []);
// Create new issue
githubMock.createIssue(
"test-owner",
"test-repo",
createIssueFixture({
number: 1001,
title: task.description,
}),
);
const result = await service.syncTask(task, store);
expect(result).not.toBeNull();
expect(result?.created).toBe(true);
expect(getGitHubMetadata(result)?.issueNumber).toBe(1001);
});
it("throws when tracked issue returns 404 during update check", async () => {
// Task with GitHub metadata pointing to a deleted issue
const task = createTask({
metadata: {
github: {
issueNumber: 999,
issueUrl: "https://github.com/test-owner/test-repo/issues/999",
repo: "test-owner/test-repo",
},
},
});
const store = createStore([task]);
// Get issue returns 404 (issue was deleted), hasIssueChanged catches and returns true
// Then updateIssue is called and also returns 404
githubMock.getIssue404("test-owner", "test-repo", 999);
githubMock.updateIssue404("test-owner", "test-repo", 999);
await expect(service.syncTask(task, store)).rejects.toThrow();
});
});
describe("500 server errors", () => {
it("throws error when GitHub server fails during issue creation", async () => {
const task = createTask();
const store = createStore([task]);
// Search works but create fails
githubMock.listIssues("test-owner", "test-repo", []);
githubMock.createIssue500("test-owner", "test-repo");
await expect(service.syncTask(task, store)).rejects.toThrow();
});
it("throws error when GitHub server fails during issue update", async () => {
const task = createTask({
metadata: {
github: {
issueNumber: 789,
issueUrl: "https://github.com/test-owner/test-repo/issues/789",
repo: "test-owner/test-repo",
},
},
});
const store = createStore([task]);
// Get issue works but indicates change needed, then update fails
githubMock.getIssue(
"test-owner",
"test-repo",
789,
createIssueFixture({
number: 789,
title: "Old title", // Different from task.description to trigger update
}),
);
githubMock.updateIssue500("test-owner", "test-repo", 789);
await expect(service.syncTask(task, store)).rejects.toThrow();
});
});
describe("fast-path state tracking", () => {
// Tasks without commit SHA don't close issues (can't verify merge)
// Tasks with commit SHA require the commit to be on origin/HEAD
it("syncs completed task with pushed commit when previously synced as open", async () => {
const { execSync } = await import("node:child_process");
vi.mocked(execSync).mockImplementation((cmd: string) => {
if (typeof cmd === "string" && cmd.includes("gh auth token")) {
throw new Error("gh not authenticated");
}
// Commit IS on remote
if (
typeof cmd === "string" &&
cmd.includes("git merge-base --is-ancestor")
) {
return ""; // Success
}
return "";
});
// Task synced while pending (state: "open"), then completed with pushed commit
// The sync should update the issue to close it
const task = createTask({
completed: true,
metadata: {
github: {
issueNumber: 100,
issueUrl: "https://github.com/test-owner/test-repo/issues/100",
repo: "test-owner/test-repo",
state: "open", // Previously synced as open
},
commit: {
sha: "abc123",
message: "Fix bug",
},
},
});
const store = createStore([task]);
// Should fetch the issue and update it (not skip via fast-path)
githubMock.getIssue(
"test-owner",
"test-repo",
100,
createIssueFixture({
number: 100,
title: task.description,
state: "open",
}),
);
githubMock.updateIssue(
"test-owner",
"test-repo",
100,
createIssueFixture({
number: 100,
title: task.description,
state: "closed",
}),
);
const result = await service.syncTask(task, store);
expect(result).not.toBeNull();
expect(result?.skipped).toBeFalsy();
expect(getGitHubMetadata(result)?.state).toBe("closed");
});
it("skips completed task with pushed commit when already synced as closed", async () => {
const { execSync } = await import("node:child_process");
vi.mocked(execSync).mockImplementation((cmd: string) => {
if (typeof cmd === "string" && cmd.includes("gh auth token")) {
throw new Error("gh not authenticated");
}
// Commit IS on remote
if (
typeof cmd === "string" &&
cmd.includes("git merge-base --is-ancestor")
) {
return ""; // Success
}
return "";
});
// Fast-path: completed task with pushed commit and state: "closed" should skip API call
const task = createTask({
completed: true,
metadata: {
github: {
issueNumber: 101,
issueUrl: "https://github.com/test-owner/test-repo/issues/101",
repo: "test-owner/test-repo",
state: "closed", // Already synced as closed
},
commit: {
sha: "abc123",
message: "Fix bug",
},
},
});
const store = createStore([task]);
// Should NOT make any API calls (fast-path)
const result = await service.syncTask(task, store);
expect(result).not.toBeNull();
expect(result?.skipped).toBe(true);
expect(getGitHubMetadata(result)?.state).toBe("closed");
});
it("checks API for open task even with matching state", async () => {
// Open tasks can change, so we always check the API (no fast-path for open tasks)
const task = createTask({
completed: false,
metadata: {
github: {
issueNumber: 102,
issueUrl: "https://github.com/test-owner/test-repo/issues/102",
repo: "test-owner/test-repo",
state: "open",
},
},
});
const store = createStore([task]);
// Should fetch issue to check for changes
// Body won't match (mock has null), so update will be called
githubMock.getIssue(
"test-owner",
"test-repo",
102,
createIssueFixture({
number: 102,
title: task.description,
state: "open",
}),
);
githubMock.updateIssue(
"test-owner",
"test-repo",
102,
createIssueFixture({
number: 102,
title: task.description,
state: "open",
}),
);
const result = await service.syncTask(task, store);
// Open task was checked and updated (not fast-pathed)
expect(result).not.toBeNull();
expect(result?.skipped).toBeFalsy();
expect(getGitHubMetadata(result)?.state).toBe("open");
});
});
describe("commit-based completion checking", () => {
it("keeps issue open when task has unpushed commit", async () => {
const { execSync } = await import("node:child_process");
vi.mocked(execSync).mockImplementation((cmd: string) => {
if (typeof cmd === "string" && cmd.includes("gh auth token")) {
throw new Error("gh not authenticated");
}
// Commit is NOT on remote
if (
typeof cmd === "string" &&
cmd.includes("git merge-base --is-ancestor")
) {
throw new Error("not ancestor");
}
return "";
});
// Task is completed locally with a commit SHA that's not pushed
const task = createTask({
completed: true,
metadata: {
commit: {
sha: "abc123",
message: "Fix bug",
},
},
});
const store = createStore([task]);
// Should create issue as OPEN (not closed) because commit isn't pushed
githubMock.listIssues("test-owner", "test-repo", []);
githubMock.createIssue(
"test-owner",
"test-repo",
createIssueFixture({
number: 1,
title: task.name,
state: "open",
}),
);
const result = await service.syncTask(task, store);
expect(result).not.toBeNull();
expect(getGitHubMetadata(result)?.state).toBe("open");
});
it("closes issue when task has pushed commit", async () => {
const { execSync } = await import("node:child_process");
vi.mocked(execSync).mockImplementation((cmd: string) => {
if (typeof cmd === "string" && cmd.includes("gh auth token")) {
throw new Error("gh not authenticated");
}
// Commit IS on remote (success = exit 0)
if (
typeof cmd === "string" &&
cmd.includes("git merge-base --is-ancestor")
) {
return ""; // Success
}
return "";
});
// Task is completed locally with a commit SHA that IS pushed
const task = createTask({
completed: true,
metadata: {
commit: {
sha: "abc123",
message: "Fix bug",
},
},
});
const store = createStore([task]);
// Should create issue as CLOSED because commit is pushed
githubMock.listIssues("test-owner", "test-repo", []);
githubMock.createIssue(
"test-owner",
"test-repo",
createIssueFixture({
number: 1,
title: task.name,
state: "open",
}),
);
githubMock.updateIssue(
"test-owner",
"test-repo",
1,
createIssueFixture({
number: 1,
title: task.name,
state: "closed",
}),
);
const result = await service.syncTask(task, store);
expect(result).not.toBeNull();
expect(getGitHubMetadata(result)?.state).toBe("closed");
});
it("keeps issue open when task has no commit SHA (can't verify merge)", async () => {
// Task is completed locally without a commit SHA
// Should keep issue OPEN because we can't verify the work is merged
const task = createTask({
completed: true,
// No commit metadata - completed with --no-commit
});
const store = createStore([task]);
// Should create issue as OPEN because there's no commit to verify
githubMock.listIssues("test-owner", "test-repo", []);
githubMock.createIssue(
"test-owner",
"test-repo",
createIssueFixture({
number: 1,
title: task.name,
state: "open",
}),
);
const result = await service.syncTask(task, store);
expect(result).not.toBeNull();
expect(getGitHubMetadata(result)?.state).toBe("open");
});
it("does not reopen a closed issue when local task has no verified commit", async () => {
// Scenario: Task was completed on Machine A (with commit), issue closed
// Machine B has the task locally completed but without a verified commit
// When Machine B syncs, it should NOT reopen the closed issue
const task = createTask({
id: "test-task",
completed: true,
metadata: {
github: {
issueNumber: 42,
issueUrl: "https://github.com/test-owner/test-repo/issues/42",
repo: "test-owner/test-repo",
state: "open", // Local metadata is stale
},
},
// No commit metadata - can't verify merge
});
const store = createStore([task]);
// Single-task sync uses getIssue (not listIssues) since task already has issueNumber
// Issue is already CLOSED on GitHub (was closed on another machine)
githubMock.getIssue(
"test-owner",
"test-repo",
42,
createIssueFixture({
number: 42,
title: task.name,
state: "closed",
body: `<!-- dex:task:id:test-task -->`,
}),
);
// Update should keep the issue closed (not reopen it)
// The key assertion: update is called but doesn't include state: "open"
githubMock.updateIssue(
"test-owner",
"test-repo",
42,
createIssueFixture({
number: 42,
title: task.name,
state: "closed", // Stays closed
}),
);
const result = await service.syncTask(task, store);
// The sync completes successfully
expect(result).not.toBeNull();
// We report "open" as expected state (since we can't verify commit)
// but the issue stays closed on GitHub (we don't reopen it)
expect(getGitHubMetadata(result)?.state).toBe("open");
});
it("does not reopen closed issue when syncing incomplete task without cache", async () => {
// Critical test for the fix: when syncTask is called directly (not through syncAll),
// there's no issue cache, so getIssueChangeResult must fetch the current state.
// If the remote issue is closed, we must not reopen it by sending state: "open".
const task = createTask({
id: "incomplete-task",
name: "Incomplete Task",
completed: false, // Task is NOT completed locally
metadata: {
github: {
issueNumber: 99,
issueUrl: "https://github.com/test-owner/test-repo/issues/99",
repo: "test-owner/test-repo",
state: "open", // Stale local metadata
},
},
});
const store = createStore([task]);
// The GitHub issue is already CLOSED (closed externally or by another machine)
githubMock.getIssue(
"test-owner",
"test-repo",
99,
createIssueFixture({
number: 99,
title: task.name,
state: "closed", // CLOSED on remote
body: `<!-- dex:task:id:incomplete-task -->`,
}),
);
// The update should NOT include state: "open" (would reopen the issue)
// Since the local content differs from remote, an update is needed
// but the state field should be omitted to preserve the closed state
githubMock.updateIssue(
"test-owner",
"test-repo",
99,
createIssueFixture({
number: 99,
title: task.name,
state: "closed", // Should stay closed
}),
);
const result = await service.syncTask(task, store);
expect(result).not.toBeNull();
// Expected state is "open" (task not completed), but issue should stay closed on GitHub
expect(getGitHubMetadata(result)?.state).toBe("open");
});
it("verifies request body does not contain state:open when issue is closed", async () => {
// This test uses nock body matching to PROVE we don't send state: "open"
const task = createTask({
id: "body-check-task",
name: "Body Check Task",
completed: false,
metadata: {
github: {
issueNumber: 88,
issueUrl: "https://github.com/test-owner/test-repo/issues/88",
repo: "test-owner/test-repo",
state: "open",
},
},
});
const store = createStore([task]);
// Setup getIssue to return closed issue
githubMock.getIssue(
"test-owner",
"test-repo",
88,
createIssueFixture({
number: 88,
title: task.name,
state: "closed",
body: `<!-- dex:task:id:body-check-task -->`,
}),
);
// Use nock directly with body matching to verify state is NOT "open"
let capturedBody: Record<string, unknown> | null = null;
nock("https://api.github.com")
.patch(`/repos/test-owner/test-repo/issues/88`, (body) => {
capturedBody = body as Record<string, unknown>;
// Accept any body - we'll verify after
return true;
})
.reply(200, {
number: 88,
title: task.name,
state: "closed",
html_url: "https://github.com/test-owner/test-repo/issues/88",
});
await service.syncTask(task, store);
// THE CRITICAL ASSERTION: state should NOT be "open"
expect(capturedBody).not.toBeNull();
expect(capturedBody!.state).not.toBe("open");
// state should either be undefined (not sent) or "closed"
expect(
capturedBody!.state === undefined || capturedBody!.state === "closed",
).toBe(true);
});
});
});
describe("syncAll", () => {
describe("partial sync failures", () => {
it("continues syncing after one task fails", async () => {
const task1 = createTask({ id: "task1", description: "Task 1" });
const task2 = createTask({ id: "task2", description: "Task 2" });
const store = createStore([task1, task2]);
// Task 1: search then create fails
githubMock.listIssues("test-owner", "test-repo", []);
githubMock.createIssue500("test-owner", "test-repo");
// Note: syncAll doesn't continue after failure by default
// This tests that errors propagate correctly
await expect(service.syncAll(store)).rejects.toThrow();
});
it("reports progress for each task", async () => {
const task1 = createTask({ id: "task1", description: "Task 1" });
const task2 = createTask({ id: "task2", description: "Task 2" });
const store = createStore([task1, task2]);
const progressEvents: string[] = [];
// Both tasks: search then create
githubMock.listIssues("test-owner", "test-repo", []);
githubMock.createIssue(
"test-owner",
"test-repo",
createIssueFixture({
number: 1,
title: "Task 1",
}),
);
githubMock.listIssues("test-owner", "test-repo", []);
githubMock.createIssue(
"test-owner",
"test-repo",
createIssueFixture({
number: 2,
title: "Task 2",
}),
);
const results = await service.syncAll(store, {
onProgress: (progress) => {
progressEvents.push(`${progress.phase}:${progress.task.id}`);
},
});
expect(results).toHaveLength(2);
expect(progressEvents).toContain("checking:task1");
expect(progressEvents).toContain("creating:task1");
expect(progressEvents).toContain("checking:task2");
expect(progressEvents).toContain("creating:task2");
});
});
describe("401 unauthorized during bulk sync", () => {
it("fails immediately on auth error", async () => {
const task = createTask();
const store = createStore([task]);
githubMock.listIssues401("test-owner", "test-repo");
await expect(service.syncAll(store)).rejects.toThrow();
});
});
describe("rate limiting during bulk sync", () => {
it("fails on rate limit error", async () => {
const task = createTask();
const store = createStore([task]);
githubMock.listIssues403("test-owner", "test-repo", true);
await expect(service.syncAll(store)).rejects.toThrow();
});
});
});
describe("findIssueByTaskId", () => {
it("returns null when API returns 401", async () => {
githubMock.listIssues401("test-owner", "test-repo");
const result = await service.findIssueByTaskId("some-task");
// findIssueByTaskId catches errors and returns null
expect(result).toBeNull();
});
it("returns null when API returns 403", async () => {
githubMock.listIssues403("test-owner", "test-repo");
const result = await service.findIssueByTaskId("some-task");
expect(result).toBeNull();
});
it("returns null when API returns 500", async () => {
githubMock.listIssues500("test-owner", "test-repo");
const result = await service.findIssueByTaskId("some-task");
expect(result).toBeNull();
});
it("finds issue by task ID in new format", async () => {
githubMock.listIssues("test-owner", "test-repo", [
createIssueFixture({
number: 42,
title: "Test",
body: "<!-- dex:task:id:abc12345 -->\nSome context",
}),
]);
const result = await service.findIssueByTaskId("abc12345");
expect(result).toBe(42);
});
it("finds issue by task ID in legacy format", async () => {
githubMock.listIssues("test-owner", "test-repo", [
createIssueFixture({
number: 43,
title: "Test",
body: "<!-- dex:task:legacy123 -->\nSome context",
}),
]);
const result = await service.findIssueByTaskId("legacy123");
expect(result).toBe(43);
});
});
});
describe("getGitHubToken", () => {
let originalEnv: string | undefined;
beforeEach(() => {
originalEnv = process.env.GITHUB_TOKEN;
});
afterEach(() => {
if (originalEnv !== undefined) {
process.env.GITHUB_TOKEN = originalEnv;
} else {
delete process.env.GITHUB_TOKEN;
}
});
it("returns token from environment variable", () => {
process.env.GITHUB_TOKEN = "env-token-123";
const token = getGitHubToken();
expect(token).toBe("env-token-123");
});
it("returns token from custom environment variable", () => {
process.env.MY_CUSTOM_TOKEN = "custom-token-456";
const token = getGitHubToken("MY_CUSTOM_TOKEN");
expect(token).toBe("custom-token-456");
delete process.env.MY_CUSTOM_TOKEN;
});
it("returns null when no token available", () => {
delete process.env.GITHUB_TOKEN;
const token = getGitHubToken();
// With our mock, gh auth token throws, so returns null
expect(token).toBeNull();
});
});
describe("createGitHubSyncService", () => {
let originalEnv: string | undefined;
beforeEach(() => {
originalEnv = process.env.GITHUB_TOKEN;
vi.clearAllMocks();
});
afterEach(() => {
if (originalEnv !== undefined) {
process.env.GITHUB_TOKEN = originalEnv;
} else {
delete process.env.GITHUB_TOKEN;
}
});
it("returns null when sync is disabled", async () => {
const result = await createGitHubSyncService({ enabled: false });
expect(result).toBeNull();
});
it("returns null when config is undefined", async () => {
const result = await createGitHubSyncService(undefined);
expect(result).toBeNull();
});
it("returns null when no token available", async () => {
delete process.env.GITHUB_TOKEN;
// Suppress console.warn for this test
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const result = await createGitHubSyncService({ enabled: true });
expect(result).toBeNull();
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining("no token found"),
);
warnSpy.mockRestore();
});
it("creates service when properly configured", async () => {
process.env.GITHUB_TOKEN = "valid-token";
const result = await createGitHubSyncService({ enabled: true });
expect(result).not.toBeNull();
expect(result?.getRepoString()).toBe("test-owner/test-repo");
});
});
describe("createGitHubSyncServiceOrThrow", () => {
let originalEnv: string | undefined;
beforeEach(() => {
originalEnv = process.env.GITHUB_TOKEN;
vi.clearAllMocks();
});
afterEach(() => {
if (originalEnv !== undefined) {
process.env.GITHUB_TOKEN = originalEnv;
} else {
delete process.env.GITHUB_TOKEN;
}
});
it("throws when no token available", async () => {
delete process.env.GITHUB_TOKEN;
await expect(createGitHubSyncServiceOrThrow()).rejects.toThrow(
/GitHub token not found/,
);
});
it("throws with helpful message mentioning token env var", async () => {
delete process.env.GITHUB_TOKEN;
await expect(createGitHubSyncServiceOrThrow()).rejects.toThrow(
/GITHUB_TOKEN/,
);
});
it("throws with helpful message mentioning gh auth", async () => {
delete process.env.GITHUB_TOKEN;
await expect(createGitHubSyncServiceOrThrow()).rejects.toThrow(
/gh auth login/,
);
});
it("creates service when token available", async () => {
process.env.GITHUB_TOKEN = "valid-token";
const result = await createGitHubSyncServiceOrThrow();
expect(result).not.toBeNull();
expect(result.getRepoString()).toBe("test-owner/test-repo");
});
it("uses custom token env var from config", async () => {
process.env.CUSTOM_GH_TOKEN = "custom-token";
const result = await createGitHubSyncServiceOrThrow({
enabled: true,
token_env: "CUSTOM_GH_TOKEN",
});
expect(result).not.toBeNull();
delete process.env.CUSTOM_GH_TOKEN;
});
});
describe("fetchAllDexIssues", () => {
let service: GitHubSyncService;
let githubMock: GitHubMock;
beforeEach(() => {
process.env.GITHUB_TOKEN = "test-token";
githubMock = setupGitHubMock();
service = new GitHubSyncService({
repo: { owner: "test-owner", repo: "test-repo" },
token: "test-token",
});
});
afterEach(() => {
cleanupGitHubMock();
delete process.env.GITHUB_TOKEN;
});
it("returns empty map when no issues exist", async () => {
githubMock.listIssues("test-owner", "test-repo", []);
const result = await service.fetchAllDexIssues();