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

gitLabMergeRequestJson.test.ts

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