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

GitLabIssueTracker.test.ts

478 lines17.3 KB

1import { describe, expect, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
5​
6import * as GitLabCli from "./GitLabCli.ts";
7import * as GitLabIssueTracker from "./GitLabIssueTracker.ts";
8​
9const encode = (value: unknown) => JSON.stringify(value);
10​
11const ISSUE = {
12 iid: 42,
13 title: "Composer loses focus",
14 web_url: "https://gitlab.com/acme/web/-/issues/42",
15 description: "Typing in the composer drops focus after a paste.",
16 author: { id: 1, username: "octocat", name: "Octo Cat", avatar_url: "https://avatars/octocat" },
17 state: "closed",
18 created_at: "2026-07-01T00:00:00Z",
19 updated_at: "2026-07-03T00:00:00Z",
20 closed_at: "2026-07-03T00:00:00Z",
21 assignees: [{ id: 2, username: "theo", name: null }],
22 labels: ["bug", " "],
23 user_notes_count: 3,
24};
25​
26/** Every endpoint the detail read touches, answered by the path `glab api` is given. */
27function answer(path: string): string {
28 if (path === "user") return encode({ username: "julius" });
29 if (path === "projects/acme%2Fweb/issues?iids[]=42&with_labels_details=true&per_page=1") {
30 return encode([
31 {
32 ...ISSUE,
33 labels: [
34 { name: "bug", color: "#E24329", description: "Something is broken" },
35 { name: " ", color: "#000000" },
36 ],
37 },
38 ]);
39 }
40 if (path.startsWith("projects/acme%2Fweb/issues/42/notes")) {
41 return encode([
42 {
43 id: 7,
44 body: "Repro attached.",
45 author: { username: "julius" },
46 created_at: "2026-07-02T00:00:00Z",
47 },
48 {
49 id: 8,
50 body: "closed",
51 author: { username: "theo" },
52 created_at: "2026-07-03T00:00:00Z",
53 system: true,
54 },
55 {
56 id: 9,
57 body: "added ~7 label",
58 author: { username: "theo" },
59 created_at: "2026-07-03T00:00:00Z",
60 system: true,
61 },
62 {
63 id: 10,
64 body: "mentioned in merge request api!51",
65 author: { username: "theo" },
66 created_at: "2026-07-04T00:00:00Z",
67 system: true,
68 },
69 ]);
70 }
71 if (path.startsWith("projects/acme%2Fweb/issues/42/resource_label_events")) {
72 return encode([
73 {
74 id: 3,
75 action: "add",
76 created_at: "2026-07-01T01:00:00Z",
77 user: { username: "theo" },
78 label: { name: "bug" },
79 },
80 ]);
81 }
82 if (path.startsWith("projects/acme%2Fweb/issues/42/closed_by")) {
83 return encode([
84 {
85 iid: 50,
86 title: "fix(web): keep composer focus",
87 web_url: "https://gitlab.com/acme/web/-/merge_requests/50",
88 state: "merged",
89 references: { full: "acme/web!50" },
90 },
91 ]);
92 }
93 if (path.startsWith("projects/acme%2Fweb/issues/42/related_merge_requests")) {
94 return encode([
95 {
96 iid: 50,
97 title: "fix(web): keep composer focus",
98 web_url: "https://gitlab.com/acme/web/-/merge_requests/50",
99 state: "merged",
100 references: { full: "acme/web!50" },
101 },
102 {
103 iid: 51,
104 title: "chore: mention",
105 web_url: "https://gitlab.com/acme/web/-/merge_requests/51",
106 state: "opened",
107 draft: true,
108 references: { full: "acme/web!51" },
109 },
110 ]);
111 }
112 if (path.startsWith("projects/acme%2Fweb/issues/42/award_emoji")) {
113 return encode([{ id: 11, name: "eyes", user: { username: "theo" } }]);
114 }
115 if (path === "graphql") {
116 return encode({
117 data: {
118 currentUser: { username: "julius" },
119 project: {
120 mergeRequest: {
121 notes: {
122 pageInfo: { hasNextPage: false },
123 nodes: [
124 {
125 id: "gid://gitlab/Note/7",
126 awardEmoji: {
127 nodes: [
128 { name: "thumbsup", user: { username: "julius" } },
129 { name: "thumbsup", user: { username: "theo" } },
130 ],
131 },
132 },
133 ],
134 },
135 },
136 },
137 },
138 });
139 }
140 throw new Error(`unexpected path ${path}`);
142​
143function tracker(
144 onExecute: (
145 args: ReadonlyArray<string>,
146 input: { readonly host?: string | undefined; readonly stdin?: string },
147 ) => string,
148) {
149 return GitLabIssueTracker.make.pipe(
150 Effect.provide(
151 Layer.mock(GitLabCli.GitLabCli)({
152 execute: (input) =>
153 Effect.succeed(TestSourceControlHost.processOutput(onExecute(input.args, input))),
154 }),
155 ),
156 );
158​
159describe("GitLabIssueTracker", () => {
160 it.effect("joins the detail's endpoints into the neutral issue shape", () =>
161 Effect.gen(function* () {
162 const hosts = new Set<string | undefined>();
163 const awardCursors: unknown[] = [];
164 const api = yield* tracker((args, input) => {
165 hosts.add(input.host);
166 if (args[1] === "graphql") {
167 const request = JSON.parse(input.stdin!);
168 // gitlab.com's schema has no `Issue.awardEmoji`; glab exits 1 on such a query.
169 const issueFields = /issue\(iid: \$iid\) \{([\s\S]*?)notes\(/.exec(request.query)?.[1];
170 if (issueFields?.includes("awardEmoji")) {
171 throw new Error("Field 'awardEmoji' doesn't exist on type 'Issue'");
172 }
173 awardCursors.push(request.variables.cursor);
174 }
175 return answer(args[1]!);
176 });
177 const target = { cwd: "/w", host: "gitlab.example.com", scope: "acme/web", key: "42" };
178 const issue = yield* api.getIssue(target);
179 // A later page of comments carries its own awards, found by the cursor's second half.
180 const later = yield* api.getComments({ ...target, cursor: "2:after-100" });
181 expect(later.comments.map((comment) => comment.reactions?.[0]?.count)).toEqual([2]);
182 expect(awardCursors).toEqual([null, "after-100"]);
183 // Every request names the tracker's own host rather than leaving glab to pick one.
184 expect([...hosts]).toEqual(["gitlab.example.com"]);
185 expect(issue).toMatchObject({
186 key: "42",
187 displayKey: "#42",
188 state: { category: "closed", name: "Closed" },
189 states: [
190 { category: "open", name: "Open" },
191 { category: "closed", name: "Closed" },
192 ],
193 author: { login: "octocat", name: "Octo Cat" },
194 assignees: [{ login: "theo" }],
195 labels: [{ name: "bug", color: "#E24329", description: "Something is broken" }],
196 commentCount: 3,
197 viewer: "julius",
198 viewerPermissions: { setState: true, edit: true, labels: true, assignees: true },
199 commentsCursor: null,
200 reactions: [{ content: "eyes", count: 1, actors: ["theo"], viewerHasReacted: false }],
201 });
202 expect(issue.comments).toEqual([
203 {
204 id: "7",
205 author: { login: "julius", name: null, avatarUrl: null },
206 body: "Repro attached.",
207 createdAt: "2026-07-02T00:00:00Z",
208 url: null,
209 reactions: [{ content: "thumbs-up", count: 2, actors: ["theo"], viewerHasReacted: true }],
210 },
211 ]);
212 // System notes become events; label notes are dropped in favour of the label events.
213 expect(issue.events.map((event) => [event.kind, event.detail])).toEqual([
214 ["labeled", "bug"],
215 ["closed", null],
216 ["referenced", "merge request api!51"],
217 ]);
218 expect(issue.events.at(-1)?.reference).toEqual({
219 repository: "acme/api",
220 number: 51,
221 kind: "pull-request",
222 url: "https://gitlab.com/acme/api/-/merge_requests/51",
223 });
224 // A closing merge request is not repeated as a related one.
225 expect(
226 issue.linkedPullRequests.map((link) => [link.number, link.closesIssue, link.isDraft]),
227 ).toEqual([
228 [50, true, false],
229 [51, false, true],
230 ]);
231 }),
232 );
233​
234 it.effect("loads the detail without comment reactions where GitLab has no Note.awardEmoji", () =>
235 Effect.gen(function* () {
236 // GitLab before 16.1 has no `Note.awardEmoji`; glab exits 1 on any query naming it.
237 const api = yield* GitLabIssueTracker.make.pipe(
238 Effect.provide(
239 Layer.mock(GitLabCli.GitLabCli)({
240 execute: (input) =>
241 input.args[1] === "graphql"
242 ? Effect.fail(
243 new GitLabCli.GitLabCliCommandError({
244 operation: "execute",
245 command: "glab",
246 cwd: input.cwd,
247 cause: new Error("glab: Field 'awardEmoji' doesn't exist on type 'Note'"),
248 }),
249 )
250 : Effect.succeed(TestSourceControlHost.processOutput(answer(input.args[1]!))),
251 }),
252 ),
253 );
254 const target = { cwd: "/w", host: "gitlab.example.com", scope: "acme/web", key: "42" };
255 const issue = yield* api.getIssue(target);
256 expect(issue.comments.map((comment) => [comment.id, comment.reactions])).toEqual([["7", []]]);
257 expect(issue.reactions).toEqual([
258 { content: "eyes", count: 1, actors: ["theo"], viewerHasReacted: false },
259 ]);
260 const later = yield* api.getComments({ ...target, cursor: "2:after-100" });
261 expect(later.comments.map((comment) => comment.reactions)).toEqual([[]]);
262 }),
263 );
264​
265 it.effect("keeps system events after the first hundred notes in the issue timeline", () =>
266 Effect.gen(function* () {
267 const firstPage = Array.from({ length: 100 }, (_, index) => ({
268 id: index + 1000,
269 body: "Discussion",
270 author: { username: "julius" },
271 created_at: "2026-07-02T00:00:00Z",
272 }));
273 const api = yield* tracker((args) => {
274 const path = args[1]!;
275 if (path.includes("/notes?")) {
276 const page = new URLSearchParams(path.split("?")[1]).get("page");
277 if (page === "1") return encode(firstPage);
278 if (page === "2") {
279 return encode([
280 {
281 id: 1100,
282 body: "closed",
283 system: true,
284 author: { username: "theo" },
285 created_at: "2026-07-03T00:00:00Z",
286 },
287 ]);
288 }
289 return encode([]);
290 }
291 return answer(path);
292 });
293 const target = { cwd: "/w", host: "gitlab.com", scope: "acme/web", key: "42" };
294 const issue = yield* api.getIssue(target);
295 let cursor = issue.commentsCursor;
296 while (cursor !== null) {
297 cursor = (yield* api.getComments({ ...target, cursor })).nextCursor;
298 }
299 expect(issue.events).toContainEqual(
300 expect.objectContaining({ id: "note-1100", kind: "closed" }),
301 );
302 }),
303 );
304​
305 it.effect("follows GitLab's next page past a short page of notes", () =>
306 Effect.gen(function* () {
307 const notes = (next: string, rows: ReadonlyArray<unknown>) =>
308 `HTTP/2.0 200 OK\r\nContent-Type: application/json\r\nX-Next-Page: ${next}\r\nX-Page: 1\r\n\r\n${encode(rows)}`;
309 const api = yield* tracker((args) => {
310 const path = args[1]!;
311 if (path.includes("/notes?")) {
312 const params = new URLSearchParams(path.split("?")[1]);
313 if (params.get("activity_filter") === "only_activity") {
314 return params.get("page") === "1"
315 ? notes("2", [])
316 : notes("", [
317 {
318 id: 300,
319 body: "closed",
320 system: true,
321 author: { username: "theo" },
322 created_at: "2026-07-03T00:00:00Z",
323 },
324 ]);
325 }
326 return notes("2", [
327 {
328 id: 1,
329 body: "Hi",
330 author: { username: "julius" },
331 created_at: "2026-07-02T00:00:00Z",
332 },
333 ]);
334 }
335 return answer(path);
336 });
337 const issue = yield* api.getIssue({
338 cwd: "/w",
339 host: "gitlab.com",
340 scope: "acme/web",
341 key: "42",
342 });
343 expect(issue.commentsCursor).toBe("2");
344 expect(issue.events.map((event) => event.id)).toEqual(["label-3", "note-300"]);
345 }),
346 );
347​
348 it.effect("pages a listing by GitLab's page number and stops on a short page", () =>
349 Effect.gen(function* () {
350 const paths: string[] = [];
351 const api = yield* tracker((args) => {
352 paths.push(args[1]!);
353 return encode([ISSUE]);
354 });
355 const page = yield* api.listIssues({
356 cwd: "/w",
357 host: "gitlab.com",
358 scope: "acme/web",
359 state: "open",
360 involvement: "assigned",
361 viewer: "julius",
362 sort: "updated",
363 limit: 1,
364 cursor: "3",
365 });
366 expect(paths[0]).toBe(
367 "projects/acme%2Fweb/issues?state=opened&assignee_username=julius&order_by=updated_at&sort=desc&with_labels_details=true&per_page=1&page=3",
368 );
369 // A named assignee takes the one parameter GitLab reads, so "assigned to me" drops rows here.
370 const both = yield* api.listIssues({
371 cwd: "/w",
372 host: "gitlab.com",
373 scope: "acme/web",
374 state: "open",
375 involvement: "assigned",
376 viewer: "julius",
377 labels: ["bug", "needs triage"],
378 assignee: "theo",
379 sort: "created",
380 limit: 1,
381 });
382 expect(paths[1]).toBe(
383 "projects/acme%2Fweb/issues?state=opened&labels=bug%2Cneeds%20triage&assignee_username=theo&order_by=created_at&sort=desc&with_labels_details=true&per_page=1&page=1",
384 );
385 expect(both.items).toEqual([]);
386 expect(page.items[0]?.key).toBe("42");
387 // A host that ignores with_labels_details still sends names, which keep their chips.
388 expect(page.items[0]?.labels).toEqual([{ name: "bug", color: null }]);
389 expect(page.nextCursor).toBe("4");
390 }),
391 );
392​
393 it.effect("removes the viewer's own award by id, paging until it is found", () =>
394 Effect.gen(function* () {
395 const calls: string[] = [];
396 const api = yield* tracker((args) => {
397 const path = args[1]!;
398 calls.push(args.includes("DELETE") ? `DELETE ${path}` : path);
399 if (path === "user") return encode({ username: "julius" });
400 if (path.endsWith("page=1")) {
401 return encode([{ id: 1, name: "thumbsup", user: { username: "theo" } }]);
402 }
403 if (path.endsWith("page=2") && path.includes("/notes/7/")) {
404 return encode([{ id: 9, name: "thumbsup", user: { username: "julius" } }]);
405 }
406 return "[]";
407 });
408 const target = { cwd: "/w", host: "gitlab.com", scope: "acme/web", key: "42" };
409 yield* api.setReaction!({ ...target, subjectId: "7", content: "thumbs-up", reacted: false });
410 expect(calls.at(-1)).toBe("DELETE projects/acme%2Fweb/issues/42/notes/7/award_emoji/9");
411 // Nothing to delete is success, with no DELETE sent.
412 calls.length = 0;
413 yield* api.setReaction!({ ...target, content: "thumbs-up", reacted: false });
414 expect(calls).toEqual([
415 "user",
416 "projects/acme%2Fweb/issues/42/award_emoji?per_page=100&page=1",
417 "projects/acme%2Fweb/issues/42/award_emoji?per_page=100&page=2",
418 ]);
419 }),
420 );
421​
422 it.effect("writes a kept assignee by the id its username resolves to", () =>
423 Effect.gen(function* () {
424 const calls: string[] = [];
425 const bodies: string[] = [];
426 const api = yield* tracker((args, input) => {
427 const path = args[1]!;
428 calls.push(path);
429 if (input.stdin !== undefined) bodies.push(input.stdin);
430 if (path === "users?username=theo") return encode([{ id: 2, username: "theo" }]);
431 if (path.startsWith("users?username=")) return "[]";
432 return "{}";
433 });
434 const target = { cwd: "/w", host: "gitlab.com", scope: "acme/web", key: "42" };
435 // The issue's own assignee comes back by login; a newly picked one by id.
436 yield* api.update!({ ...target, assignees: ["theo", "7"] });
437 expect(calls).toEqual(["users?username=theo", "projects/acme%2Fweb/issues/42"]);
438 expect(JSON.parse(bodies.at(-1)!)).toEqual({ assignee_ids: [2, 7] });
439 const error = yield* Effect.flip(api.update!({ ...target, assignees: ["nobody"] }));
440 expect(error.reason).toBe("failed");
441 }),
442 );
443​
444 it.effect("moves an issue to a state by its name and refuses any other name", () =>
445 Effect.gen(function* () {
446 const writes: unknown[] = [];
447 const api = yield* tracker((args, input) => {
448 writes.push([args[1], JSON.parse(input.stdin ?? "null")]);
449 return "{}";
450 });
451 const target = { cwd: "/w", host: "gitlab.com", scope: "acme/web", key: "42" };
452 yield* api.setState!({ ...target, state: "Closed" });
453 yield* api.setState!({ ...target, state: "Open" });
454 // The category is not a state name: nothing is sent for it.
455 const error = yield* Effect.flip(api.setState!({ ...target, state: "closed" }));
456 expect(error).toMatchObject({ operation: "setState", reason: "failed" });
457 expect(writes).toEqual([
458 ["projects/acme%2Fweb/issues/42", { state_event: "close" }],
459 ["projects/acme%2Fweb/issues/42", { state_event: "reopen" }],
460 ]);
461 }),
462 );
463​
464 it.effect("refuses a key that names no GitLab issue without a request", () =>
465 Effect.gen(function* () {
466 let requests = 0;
467 const api = yield* tracker(() => {
468 requests += 1;
469 return "{}";
470 });
471 const error = yield* Effect.flip(
472 api.getIssue({ cwd: "/w", host: "gitlab.com", scope: "acme/web", key: "ENG-42" }),
473 );
474 expect(error.reason).toBe("not-found");
475 expect(requests).toBe(0);
476 }),
477 );
478});