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

gitLabMergeRequestJson.test.ts

610 lines19.1 KB

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