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

GitLabIssueTracker.test.ts

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