Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

gitLabMergeRequestJson.test.ts

717 lines21.2 KB

1import * as Result from "effect/Result";
2import { describe, expect, it } from "vite-plus/test";
3​
4import {
5 decodeAwardEmojiJson,
6 decodeRepositoryBlobsJson,
7 decodeCommitsJson,
8 decodeMergeRequestDetailJson,
9 decodeMergeRequestDiffsJson,
10 decodeMergeRequestListJson,
11 decodeMergeRequestFileStatsJson,
12 decodeMergeRequestStatsJson,
13 decodeNotesJson,
14 decodeOwnAwardIdJson,
15 decodeTriggerJobChecksJson,
16} from "./gitLabMergeRequestJson.ts";
17​
18function listJson(entries: ReadonlyArray<Record<string, unknown>>): string {
19 return JSON.stringify(
20 entries.map((entry) => ({
21 iid: 1,
22 title: "Add the merge requests page",
23 web_url: "https://gitlab.com/acme/web/-/merge_requests/1",
24 source_branch: "feat/page",
25 target_branch: "main",
26 created_at: "2026-07-01T00:00:00Z",
27 updated_at: "2026-07-02T00:00:00Z",
28 ...entry,
29 })),
30 );
32​
33function detailJson(entry: Record<string, unknown>): string {
34 return JSON.stringify({
35 iid: 1,
36 title: "Add the merge requests page",
37 web_url: "https://gitlab.com/acme/web/-/merge_requests/1",
38 source_branch: "feat/page",
39 target_branch: "main",
40 created_at: "2026-07-01T00:00:00Z",
41 updated_at: "2026-07-02T00:00:00Z",
42 ...entry,
43 });
45​
46function expectSuccess<A>(result: Result.Result<A, unknown>): A {
47 expect(Result.isSuccess(result)).toBe(true);
48 if (!Result.isSuccess(result)) throw new Error("expected a successful decode");
49 return result.success;
51​
52describe("decodeMergeRequestListJson", () => {
53 it("reads a merge request as a change request", () => {
54 const batch = expectSuccess(
55 decodeMergeRequestListJson(
56 listJson([
57 {
58 iid: 42,
59 author: { username: "bilal", name: "Bilal" },
60 state: "opened",
61 merge_status: "can_be_merged",
62 draft: false,
63 reviewers: [{ username: "julius" }],
64 labels: ["backend", " "],
65 },
66 ]),
67 ),
68 );
69​
70 expect(batch.items).toHaveLength(1);
71 expect(batch.items[0]).toMatchObject({
72 number: 42,
73 author: { login: "bilal", name: "Bilal" },
74 headBranch: "feat/page",
75 baseBranch: "main",
76 state: "open",
77 isDraft: false,
78 mergeability: "mergeable",
79 reviewRequestLogins: ["julius"],
80 labels: [{ name: "backend", color: null }],
81 });
82 });
83​
84 it("treats a merged timestamp as merged whatever the state says", () => {
85 const batch = expectSuccess(
86 decodeMergeRequestListJson(
87 listJson([{ state: "opened", merged_at: "2026-07-03T00:00:00Z" }]),
88 ),
89 );
90​
91 expect(batch.items[0]?.state).toBe("merged");
92 });
93​
94 it("reads the legacy draft flag", () => {
95 const batch = expectSuccess(decodeMergeRequestListJson(listJson([{ work_in_progress: true }])));
96​
97 expect(batch.items[0]?.isDraft).toBe(true);
98 });
99​
100 it("calls a conflicted merge request conflicting even while the merge check is pending", () => {
101 const batch = expectSuccess(
102 decodeMergeRequestListJson(listJson([{ merge_status: "checking", has_conflicts: true }])),
103 );
104​
105 expect(batch.items[0]?.mergeability).toBe("conflicting");
106 });
107​
108 it("skips a malformed row but still counts it, so paging does not stop early", () => {
109 const batch = expectSuccess(
110 decodeMergeRequestListJson(
111 JSON.stringify([{ iid: "not a number" }, ...JSON.parse(listJson([{}]))]),
112 ),
113 );
114​
115 expect(batch.items).toHaveLength(1);
116 expect(batch.rawIndexes).toEqual([1]);
117 expect(batch.rawCount).toBe(2);
118 });
119});
120​
121describe("decodeMergeRequestDetailJson", () => {
122 it("reads the description, file count and pipeline", () => {
123 const detail = expectSuccess(
124 decodeMergeRequestDetailJson(
125 detailJson({
126 description: "Ships the page.",
127 changes_count: "3",
128 reviewers: [{ username: "julius", name: "Julius" }],
129 head_pipeline: {
130 status: "success",
131 web_url: "https://gitlab.com/acme/web/-/pipelines/9",
132 source: "merge_request_event",
133 },
134 }),
135 ),
136 );
137​
138 expect(detail.body).toBe("Ships the page.");
139 expect(detail.changedFiles).toBe(3);
140 expect(detail.reviewers).toEqual([{ login: "julius", name: "Julius", avatarUrl: null }]);
141 expect(detail.checks).toEqual([
142 {
143 name: "Pipeline",
144 status: "success",
145 description: "merge_request_event",
146 url: "https://gitlab.com/acme/web/-/pipelines/9",
147 },
148 ]);
149 });
150​
151 it.each(["canceled", "canceling"])("maps a %s pipeline to cancelled", (status) => {
152 const detail = expectSuccess(
153 decodeMergeRequestDetailJson(detailJson({ head_pipeline: { status } })),
154 );
155​
156 expect(detail.checks[0]?.status).toBe("cancelled");
157 });
158​
159 it("reads an uncounted change set as its floor", () => {
160 const detail = expectSuccess(
161 decodeMergeRequestDetailJson(detailJson({ changes_count: "1000+" })),
162 );
163​
164 expect(detail.changedFiles).toBe(1000);
165 });
166​
167 it("reads the head commit, and says nothing where GitLab omitted it", () => {
168 const headSha = (entry: Record<string, unknown>) =>
169 expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).headSha;
170 const sha = "afce4da4d5fe7d2fd0647b5b864526ea0a2827cb";
171​
172 expect(headSha({ sha })).toBe(sha);
173 expect(headSha({ sha, diff_refs: null })).toBe(sha);
174 expect(headSha({ sha, merge_commit_sha: "0".repeat(40) })).toBe(sha);
175 expect(headSha({})).toBeUndefined();
176 expect(headSha({ sha: null })).toBeUndefined();
177 expect(headSha({ sha: " " })).toBeUndefined();
178 });
179​
180 it("reads either auto-merge field, and says nothing where GitLab named neither", () => {
181 const armed = (entry: Record<string, unknown>) =>
182 expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).autoMergeEnabled;
183​
184 expect(armed({ merge_when_pipeline_succeeds: true })).toBe(true);
185 expect(armed({ auto_merge_enabled: true })).toBe(true);
186 expect(armed({ merge_when_pipeline_succeeds: false })).toBe(false);
187 expect(armed({})).toBeUndefined();
188 });
189​
190 it("keeps the squash choice stored with auto-merge", () => {
191 expect(
192 expectSuccess(
193 decodeMergeRequestDetailJson(
194 detailJson({ auto_merge_enabled: true, squash_on_merge: true }),
195 ),
196 ),
197 ).toMatchObject({ autoMergeEnabled: true, autoMergeMethod: "squash" });
198​
199 expect(
200 expectSuccess(
201 decodeMergeRequestDetailJson(
202 detailJson({
203 auto_merge_enabled: true,
204 squash: true,
205 squash_on_merge: false,
206 }),
207 ),
208 ).autoMergeMethod,
209 ).toBeUndefined();
210 });
211​
212 it("keeps a divergence GitLab did not count apart from a divergence of none", () => {
213 const behind = (entry: Record<string, unknown>) =>
214 expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).divergedCommits;
215​
216 expect(behind({ diverged_commits_count: 3 })).toBe(3);
217 expect(behind({ diverged_commits_count: 0 })).toBe(0);
218 expect(behind({})).toBeUndefined();
219 expect(behind({ diverged_commits_count: null })).toBeUndefined();
220 });
221​
222 it.each(["scheduled", " SCHEDULED "])("keeps a delayed pipeline pending: %s", (status) => {
223 const detail = expectSuccess(
224 decodeMergeRequestDetailJson(detailJson({ head_pipeline: { status } })),
225 );
226​
227 expect(detail.checks[0]?.status).toBe("pending");
228 });
229​
230 it("maps a pipeline waiting on a person to neutral, not failure", () => {
231 const detail = expectSuccess(
232 decodeMergeRequestDetailJson(detailJson({ head_pipeline: { status: "manual" } })),
233 );
234​
235 expect(detail.checks[0]?.status).toBe("neutral");
236 });
237});
238​
239describe("decodeNotesJson", () => {
240 it("keeps comments and drops GitLab's own activity notes", () => {
241 const notes = expectSuccess(
242 decodeNotesJson(
243 JSON.stringify([
244 {
245 id: 1,
246 body: "assigned to @bilal",
247 system: true,
248 created_at: "2026-07-01T00:00:00Z",
249 },
250 {
251 id: 2,
252 body: "Looks good.",
253 author: { username: "julius" },
254 created_at: "2026-07-02T00:00:00Z",
255 },
256 { id: 3, body: " ", created_at: "2026-07-03T00:00:00Z" },
257 ]),
258 ),
259 );
260​
261 expect(notes.comments).toHaveLength(1);
262 expect(notes.comments[0]).toMatchObject({
263 id: "2",
264 kind: "issue-comment",
265 body: "Looks good.",
266 });
267 expect(notes.rawCount).toBe(3);
268 });
269​
270 it("reads a line note as a review comment on its file", () => {
271 const notes = expectSuccess(
272 decodeNotesJson(
273 JSON.stringify([
274 {
275 id: 7,
276 type: "DiffNote",
277 body: "Rename this.",
278 created_at: "2026-07-02T00:00:00Z",
279 position: { new_path: "src/app.ts", old_path: "src/old.ts" },
280 },
281 ]),
282 ),
283 );
284​
285 expect(notes.comments[0]).toMatchObject({ kind: "review-comment", path: "src/app.ts" });
286 });
287​
288 it("falls back to the old path for a note on a deleted line", () => {
289 const notes = expectSuccess(
290 decodeNotesJson(
291 JSON.stringify([
292 {
293 id: 8,
294 type: "DiffNote",
295 body: "Gone.",
296 created_at: "2026-07-02T00:00:00Z",
297 position: { new_path: null, old_path: "src/old.ts" },
298 },
299 ]),
300 ),
301 );
302​
303 expect(notes.comments[0]?.path).toBe("src/old.ts");
304 });
305});
306​
307describe("decodeCommitsJson", () => {
308 it("falls back to the creation timestamp when there is no commit date", () => {
309 const commits = expectSuccess(
310 decodeCommitsJson(
311 JSON.stringify([
312 {
313 id: "aaa",
314 created_at: "2026-07-01T00:00:00+08:00",
315 author_name: "Ada Lovelace",
316 author_email: "ada@example.com",
317 },
318 ]),
319 ),
320 );
321​
322 expect(commits[0]).toMatchObject({
323 oid: "aaa",
324 committedDate: "2026-07-01T00:00:00+08:00",
325 authors: [{ login: "Ada Lovelace", name: "Ada Lovelace", avatarUrl: null }],
326 });
327 });
328});
329​
330describe("decodeMergeRequestDiffsJson", () => {
331 it("quotes literal backslashes without interpreting them as escapes", () => {
332 const result = expectSuccess(
333 decodeMergeRequestDiffsJson(
334 JSON.stringify([
335 {
336 old_path: String.raw`src\notes.ts`,
337 new_path: String.raw`src\notes.ts`,
338 diff: "@@ -1 +1 @@\n-old\n+new",
339 },
340 ]),
341 ),
342 );
343​
344 expect(result.patch).toBe(
345 [
346 String.raw`diff --git "a/src\\notes.ts" "b/src\\notes.ts"`,
347 String.raw`--- "a/src\\notes.ts"`,
348 String.raw`+++ "b/src\\notes.ts"`,
349 "@@ -1 +1 @@",
350 "-old",
351 "+new",
352 "",
353 ].join("\n"),
354 );
355 });
356​
357 it("preserves spaces and literal backslashes in both rename paths", () => {
358 const result = expectSuccess(
359 decodeMergeRequestDiffsJson(
360 JSON.stringify([
361 {
362 old_path: String.raw` old\name.ts `,
363 new_path: String.raw` new\name.ts `,
364 renamed_file: true,
365 diff: "",
366 },
367 ]),
368 ),
369 );
370​
371 expect(result.patch).toBe(
372 [
373 String.raw`diff --git "a/ old\\name.ts " "b/ new\\name.ts "`,
374 String.raw`rename from " old\\name.ts "`,
375 String.raw`rename to " new\\name.ts "`,
376 String.raw`--- "a/ old\\name.ts "`,
377 String.raw`+++ "b/ new\\name.ts "`,
378 ].join("\n"),
379 );
380 });
381​
382 it("assembles a unified patch GitLab does not return", () => {
383 const result = expectSuccess(
384 decodeMergeRequestDiffsJson(
385 JSON.stringify([
386 {
387 old_path: "src/app.ts",
388 new_path: "src/app.ts",
389 diff: "@@ -1 +1 @@\n-old\n+new\n",
390 },
391 ]),
392 ),
393 );
394​
395 expect(result.patch).toBe(
396 [
397 "diff --git a/src/app.ts b/src/app.ts",
398 "--- a/src/app.ts",
399 "+++ b/src/app.ts",
400 "@@ -1 +1 @@",
401 "-old",
402 "+new",
403 "",
404 ].join("\n"),
405 );
406 expect(result.truncated).toBe(false);
407 });
408​
409 it("points a new file at /dev/null on the left and a deleted file on the right", () => {
410 const result = expectSuccess(
411 decodeMergeRequestDiffsJson(
412 JSON.stringify([
413 {
414 old_path: "src/new.ts",
415 new_path: "src/new.ts",
416 new_file: true,
417 b_mode: "100755",
418 diff: "@@ -0,0 +1 @@\n+hello\n",
419 },
420 {
421 old_path: "src/gone.ts",
422 new_path: "src/gone.ts",
423 deleted_file: true,
424 diff: "@@ -1 +0,0 @@\n-bye\n",
425 },
426 ]),
427 ),
428 );
429​
430 expect(result.patch).toContain("new file mode 100755");
431 expect(result.patch).toContain("--- /dev/null");
432 expect(result.patch).toContain("deleted file mode 100644");
433 expect(result.patch).toContain("+++ /dev/null");
434 });
435​
436 it("reports truncation for a file GitLab refused to inline", () => {
437 const result = expectSuccess(
438 decodeMergeRequestDiffsJson(
439 JSON.stringify([{ old_path: "big.bin", new_path: "big.bin", diff: "", too_large: true }]),
440 ),
441 );
442​
443 expect(result.truncated).toBe(true);
444 expect(result.patch).toContain("diff --git a/big.bin b/big.bin");
445 });
446​
447 it("reports how many files GitLab returned, so the caller can page", () => {
448 const result = expectSuccess(
449 decodeMergeRequestDiffsJson(
450 JSON.stringify(
451 Array.from({ length: 3 }, (_, index) => ({
452 old_path: `src/${index}.ts`,
453 new_path: `src/${index}.ts`,
454 diff: "@@ -1 +1 @@\n-a\n+b\n",
455 })),
456 ),
457 ),
458 );
459​
460 expect(result.rawCount).toBe(3);
461 expect(result.truncated).toBe(false);
462 expect(result.patch).toContain("src/2.ts");
463 });
464});
465​
466describe("decodeTriggerJobChecksJson", () => {
467 it("reads a downstream failure GitLab was told to allow as neutral, not failure", () => {
468 const result = expectSuccess(
469 decodeTriggerJobChecksJson(
470 JSON.stringify([
471 { name: "e2e", allow_failure: true, downstream_pipeline: { status: "failed" } },
472 { name: "deploy", allow_failure: false, downstream_pipeline: { status: "running" } },
473 { name: 7 },
474 ]),
475 ),
476 );
477​
478 expect(result.checks.map((check) => [check.name, check.status])).toEqual([
479 ["e2e", "neutral"],
480 ["deploy", "pending"],
481 ]);
482 expect(result.rawCount).toBe(3);
483 });
484});
485​
486describe("merge request viewer fields", () => {
487 it("leaves merging permitted where GitLab answered without the field", () => {
488 expect(expectSuccess(decodeMergeRequestDetailJson(detailJson({}))).viewerCanMerge).toBe(true);
489 expect(
490 expectSuccess(decodeMergeRequestDetailJson(detailJson({ user: null }))).viewerCanMerge,
491 ).toBe(true);
492 });
493});
494​
495describe("decodeAwardEmojiJson", () => {
496 it("reads MR-level awards, keys per-note awards by the REST id inside their gid, and ignores an award outside the eight", () => {
497 const result = expectSuccess(
498 decodeAwardEmojiJson(
499 JSON.stringify({
500 data: {
501 currentUser: { username: "bilal" },
502 project: {
503 mergeRequest: {
504 awardEmoji: {
505 nodes: [
506 { name: "thumbsup", user: { username: "bilal" } },
507 { name: "thumbsup", user: { username: "julius" } },
508 ],
509 },
510 notes: {
511 pageInfo: { hasNextPage: false, endCursor: null },
512 nodes: [
513 {
514 id: "gid://gitlab/DiffNote/42",
515 awardEmoji: { nodes: [{ name: "heart", user: { username: "julius" } }] },
516 },
517 {
518 id: "gid://gitlab/Note/7",
519 awardEmoji: {
520 nodes: [{ name: "partyparrot", user: { username: "bilal" } }],
521 },
522 },
523 ],
524 },
525 },
526 },
527 },
528 }),
529 ),
530 );
531​
532 expect(result.reactions).toEqual([
533 { content: "thumbs-up", count: 2, actors: ["julius"], viewerHasReacted: true },
534 ]);
535 expect([...result.reactionsByNoteId]).toEqual([
536 ["42", [{ content: "heart", count: 1, actors: ["julius"], viewerHasReacted: false }]],
537 ]);
538 expect(result.nextCursor).toBeNull();
539 });
540​
541 it("matches the viewer's username case-insensitively, since GitLab is not consistent about case", () => {
542 const result = expectSuccess(
543 decodeAwardEmojiJson(
544 JSON.stringify({
545 data: {
546 currentUser: { username: "Bilal" },
547 project: {
548 mergeRequest: {
549 awardEmoji: {
550 nodes: [
551 { name: "heart", user: { username: "bilal" } },
552 { name: "heart", user: { username: "julius" } },
553 ],
554 },
555 notes: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [] },
556 },
557 },
558 },
559 }),
560 ),
561 );
562​
563 expect(result.reactions).toEqual([
564 { content: "heart", count: 2, actors: ["julius"], viewerHasReacted: true },
565 ]);
566 });
567});
568​
569describe("decodeOwnAwardIdJson", () => {
570 const awards = JSON.stringify([
571 { id: 101, name: "thumbsup", user: { username: "julius" } },
572 { id: 102, name: "thumbsup", user: { username: "bilal" } },
573 ]);
574​
575 it("finds the reader's own award of that name, which is the one a removal deletes", () => {
576 expect(
577 expectSuccess(decodeOwnAwardIdJson(awards, { content: "thumbs-up", viewer: "bilal" })),
578 ).toBe(102);
579 });
580});
581​
582describe("decodeRepositoryBlobsJson", () => {
583 function expectBlobs(result: Result.Result<ReadonlyMap<string, string> | null, unknown>) {
584 const blobs = expectSuccess(result);
585 expect(blobs).not.toBe(null);
586 if (blobs === null) throw new Error("expected an answered blobs query");
587 return blobs;
588 }
589​
590 it("leaves out a node missing either half, which names no version", () => {
591 const blobs = expectBlobs(
592 decodeRepositoryBlobsJson(
593 JSON.stringify({
594 data: {
595 project: {
596 repository: {
597 blobs: {
598 nodes: [
599 { path: "src/a.ts", oid: null },
600 { path: null, oid: "bbb222" },
601 null,
602 { path: "src/c.ts", oid: "ccc333" },
603 ],
604 },
605 },
606 },
607 },
608 }),
609 ),
610 );
611​
612 expect([...blobs]).toEqual([["src/c.ts", "ccc333"]]);
613 });
614​
615 it("keys a blob by the path the host spelled, spaces and all", () => {
616 const blobs = expectBlobs(
617 decodeRepositoryBlobsJson(
618 JSON.stringify({
619 data: {
620 project: {
621 repository: {
622 blobs: {
623 nodes: [
624 { path: " leading.ts", oid: "aaa111" },
625 { path: "trailing.ts ", oid: "bbb222" },
626 { path: " ", oid: "ccc333" },
627 { path: "", oid: "ddd444" },
628 ],
629 },
630 },
631 },
632 },
633 }),
634 ),
635 );
636​
637 expect([...blobs]).toEqual([
638 [" leading.ts", "aaa111"],
639 ["trailing.ts ", "bbb222"],
640 [" ", "ccc333"],
641 ]);
642 });
643​
644 it("tells a project the reader cannot see from a revision with none of the files", () => {
645 expect(
646 expectSuccess(decodeRepositoryBlobsJson(JSON.stringify({ data: { project: null } }))),
647 ).toBe(null);
648 expect(
649 expectSuccess(
650 decodeRepositoryBlobsJson(JSON.stringify({ data: { project: { repository: null } } })),
651 ),
652 ).toBe(null);
653 expect(
654 expectSuccess(
655 decodeRepositoryBlobsJson(
656 JSON.stringify({ data: { project: { repository: { blobs: { nodes: [] } } } } }),
657 ),
658 ),
659 ).toEqual(new Map());
660 });
661});
662​
663describe("decodeMergeRequestStatsJson", () => {
664 it("keys the counts by merge request number", () => {
665 const stats = expectSuccess(
666 decodeMergeRequestStatsJson(
667 JSON.stringify({
668 data: {
669 project: {
670 mergeRequests: {
671 nodes: [
672 { iid: "7", diffStatsSummary: { additions: 12, deletions: 3 } },
673 { iid: "8", diffStatsSummary: null },
674 ],
675 },
676 },
677 },
678 }),
679 ),
680 );
681​
682 // A merge request without a summary is left out rather than shown as zero lines changed.
683 expect([...stats]).toEqual([[7, { additions: 12, deletions: 3 }]]);
684 });
685​
686 it("answers nothing for a project the token cannot see", () => {
687 const stats = expectSuccess(
688 decodeMergeRequestStatsJson(JSON.stringify({ data: { project: null } })),
689 );
690​
691 expect(stats.size).toBe(0);
692 });
693​
694 it("reports a file list shorter than the summary as truncated", () => {
695 const read = (fileCount: number) =>
696 expectSuccess(
697 decodeMergeRequestFileStatsJson(
698 JSON.stringify({
699 data: {
700 project: {
701 mergeRequest: {
702 diffStatsSummary: { fileCount },
703 diffStats: [{ path: "src/a.ts", additions: 2, deletions: 1 }],
704 },
705 },
706 },
707 }),
708 ),
709 );
710​
711 expect(read(1)).toEqual({
712 files: [{ path: "src/a.ts", additions: 2, deletions: 1 }],
713 truncated: false,
714 });
715 expect(read(2).truncated).toBe(true);
716 });
717});