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

gitLabMergeRequestJson.test.ts

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