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

AzureDevOpsIssueTracker.test.ts

494 lines18.4 KB

1import { describe, expect, it } from "@effect/vitest";
2import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as PlatformError from "effect/PlatformError";
6import * as Layer from "effect/Layer";
7import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
8​
9import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
10import * as AzureDevOpsIssueTracker from "./AzureDevOpsIssueTracker.ts";
11​
12const encode = (value: unknown) => JSON.stringify(value);
13​
14const WORK_ITEM = {
15 id: 7,
16 url: "https://dev.azure.com/acme/_apis/wit/workItems/7",
17 fields: {
18 "System.Title": "Composer loses focus",
19 "System.State": "Shipped",
20 "System.CreatedDate": "2026-07-01T00:00:00Z",
21 "System.ChangedDate": "2026-07-03T00:00:00Z",
22 "Microsoft.VSTS.Common.ClosedDate": "2026-07-03T00:00:00Z",
23 "System.CreatedBy": { uniqueName: "octo@acme.test", displayName: "Octo Cat" },
24 "System.AssignedTo": "Theo <theo@acme.test>",
25 "System.Tags": "bug; ui; bug",
26 "System.TeamProject": "Web App",
27 "System.WorkItemType": "Bug",
28 "System.CommentCount": 2,
29 "System.Description": "<p>Typing drops focus.</p>",
30 },
31 relations: [
32 { rel: "ArtifactLink", url: "vstfs:///Git/PullRequestId/p-guid%2Fr-guid%2F50" },
33 { rel: "System.LinkTypes.Related", url: "https://dev.azure.com/acme/_apis/wit/workItems/8" },
34 ],
35};
36​
37/** A custom process: "Shipped" is finished only because its category says so. */
38const WORK_ITEM_TYPES = {
39 value: [
40 // Another type's workflow, which a Bug cannot be moved through.
41 { name: "Epic", states: [{ name: "Funded", category: "Proposed" }] },
42 {
43 name: "Bug",
44 states: [
45 { name: "Active", category: "InProgress" },
46 { name: "Shipped", category: "Completed" },
47 ],
48 },
49 ],
50};
51​
52/** Every `az` command the detail read runs, told apart by its first few arguments. */
53function answer(args: ReadonlyArray<string>): string {
54 const resource = args[args.indexOf("--resource") + 1];
55 if (args[0] === "boards") return encode(WORK_ITEM);
56 if (resource === "workitemtypes") return encode(WORK_ITEM_TYPES);
57 if (args[0] === "repos") {
58 return encode({
59 pullRequestId: 50,
60 title: "fix(web): keep composer focus",
61 status: "completed",
62 isDraft: false,
63 sourceRefName: "refs/heads/fix",
64 targetRefName: "refs/heads/main",
65 creationDate: "2026-07-02T00:00:00Z",
66 closedDate: "2026-07-03T00:00:00Z",
67 mergeStatus: "succeeded",
68 repository: {
69 id: "r-guid",
70 name: "web",
71 webUrl: "https://dev.azure.com/acme/Web%20App/_git/web",
72 project: { id: "p-guid", name: "Web App" },
73 },
74 createdBy: { uniqueName: "theo@acme.test", displayName: "Theo" },
75 description: "",
76 reviewers: [],
77 _links: { web: { href: "https://dev.azure.com/acme/Web%20App/_git/web/pullrequest/50" } },
78 });
79 }
80 if (resource === "comments") {
81 return encode({
82 continuationToken: "next-token",
83 // Newest first, as `order=desc` answers.
84 comments: [
85 {
86 id: 3,
87 text: "Still happening.",
88 createdDate: "2026-07-04T00:00:00Z",
89 createdBy: { uniqueName: "octo@acme.test" },
90 },
91 {
92 id: 1,
93 text: "Repro attached.",
94 createdDate: "2026-07-02T00:00:00Z",
95 createdBy: { uniqueName: "julius@acme.test", displayName: "Julius" },
96 reactions: [
97 { type: "like", count: 2, isCurrentUserEngaged: true },
98 { type: "dislike", count: 0 },
99 ],
100 },
101 { id: 2, text: "gone", createdDate: "2026-07-02T00:00:00Z", isDeleted: true },
102 ],
103 });
104 }
105 if (resource === "updates") {
106 return encode({
107 value: [
108 {
109 id: 1,
110 revisedDate: "2026-07-01T00:00:00Z",
111 fields: { "System.Title": { newValue: "x" } },
112 },
113 {
114 id: 2,
115 // The newest revision has not been superseded, which Azure writes as year 9999.
116 revisedDate: "9999-01-01T00:00:00Z",
117 revisedBy: { uniqueName: "theo@acme.test" },
118 fields: {
119 "System.ChangedDate": { newValue: "2026-07-03T00:00:00Z" },
120 "System.State": { oldValue: "Active", newValue: "Shipped" },
121 "System.Tags": { oldValue: "ui", newValue: "bug; ui" },
122 },
123 },
124 ],
125 });
126 }
127 throw new Error(`unexpected az invocation ${args.join(" ")}`);
129​
130function tracker(onExecute: (args: ReadonlyArray<string>, stdin: string | undefined) => string) {
131 return AzureDevOpsIssueTracker.make.pipe(
132 Effect.provide(
133 Layer.mergeAll(
134 NodeFileSystem.layer,
135 Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({
136 execute: ({ args, stdin }) =>
137 Effect.succeed(TestSourceControlHost.processOutput(onExecute(args, stdin))),
138 }),
139 ),
140 ),
141 );
143​
144describe("AzureDevOpsIssueTracker", () => {
145 it.effect("maps a work item, its conversation and revisions to the neutral issue shape", () =>
146 Effect.gen(function* () {
147 const seen: string[][] = [];
148 const api = yield* tracker((args) => {
149 seen.push([...args]);
150 return answer(args);
151 });
152 const issue = yield* api.getIssue({
153 cwd: "/w",
154 host: "dev.azure.com",
155 scope: "acme/Web App",
156 key: "7",
157 });
158 // Every command names the organization rather than detecting it from the checkout.
159 for (const args of seen) {
160 expect(args).toContain("https://dev.azure.com/acme");
161 }
162 expect(issue).toMatchObject({
163 key: "7",
164 displayKey: "#7",
165 title: "Composer loses focus",
166 url: "https://dev.azure.com/acme/Web%20App/_workitems/edit/7",
167 // The project's own state name survives; the category is what the list filters by.
168 state: { category: "closed", name: "Shipped" },
169 // Its own type's workflow, in Azure's order, not the stock list or another type's.
170 states: [
171 { category: "open", name: "Active" },
172 { category: "closed", name: "Shipped" },
173 ],
174 author: { login: "octo@acme.test", name: "Octo Cat" },
175 assignees: [{ login: "Theo <theo@acme.test>" }],
176 labels: [
177 { name: "bug", color: null },
178 { name: "ui", color: null },
179 ],
180 commentCount: 2,
181 body: "<p>Typing drops focus.</p>",
182 commentsCursor: "next-token",
183 viewerPermissions: { setState: true, edit: true, labels: true, assignees: true },
184 });
185 // The first page is the newest comments, handed over oldest first.
186 expect(seen.find((args) => args.includes("comments"))).toContain("order=desc");
187 expect(issue.comments.map((comment) => comment.id)).toEqual(["1", "3"]);
188 expect(issue.comments.slice(0, 1)).toEqual([
189 {
190 id: "1",
191 author: { login: "julius@acme.test", name: "Julius", avatarUrl: null },
192 body: "Repro attached.",
193 createdAt: "2026-07-02T00:00:00Z",
194 url: null,
195 reactions: [{ content: "thumbs-up", count: 2, actors: [], viewerHasReacted: true }],
196 },
197 ]);
198 // The first revision is the creation; a state move across the category line is a close.
199 expect(issue.events.map((event) => [event.kind, event.detail, event.createdAt])).toEqual([
200 ["closed", "Shipped", "2026-07-03T00:00:00Z"],
201 ["labeled", "bug", "2026-07-03T00:00:00Z"],
202 ]);
203 expect(issue.linkedPullRequests).toEqual([
204 {
205 repository: "Web App/web",
206 number: 50,
207 title: "fix(web): keep composer focus",
208 url: "https://dev.azure.com/acme/Web%20App/_git/web/pullrequest/50",
209 state: "merged",
210 isDraft: false,
211 closesIssue: false,
212 },
213 ]);
214 }),
215 );
216​
217 it.effect("filters open work items by the project's own finished states", () =>
218 Effect.gen(function* () {
219 const fs = yield* FileSystem.FileSystem;
220 const bodies: string[] = [];
221 const hydrated: string[] = [];
222 let typeReads = 0;
223 const api = yield* AzureDevOpsIssueTracker.make.pipe(
224 Effect.provide(
225 Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({
226 execute: ({ args }) => {
227 const resource = args[args.indexOf("--resource") + 1];
228 if (resource === "workitems") {
229 // `az devops invoke` resolves `wit/workitems` to the create route
230 // (`.../workitems/${type}`) and fails before sending anything.
231 return Effect.fail(
232 new AzureDevOpsCli.AzureDevOpsCommandFailedError({
233 operation: "execute",
234 command: "az",
235 cwd: "/w",
236 argumentCount: args.length,
237 cause: "KeyError: 'type'",
238 }),
239 );
240 }
241 if (resource !== "wiql" && resource !== "workitemsbatch") {
242 if (resource === "workitemtypes") typeReads += 1;
243 return Effect.succeed(TestSourceControlHost.processOutput(answer(args)));
244 }
245 return fs.readFileString(args[args.indexOf("--in-file") + 1]!).pipe(
246 Effect.orDie,
247 Effect.map((body) => {
248 if (resource === "wiql") {
249 bodies.push(body);
250 return TestSourceControlHost.processOutput(
251 encode({ workItems: [{ id: 9 }, { id: 7 }, { id: 3 }] }),
252 );
253 }
254 hydrated.push((JSON.parse(body) as { ids: number[] }).ids.join(","));
255 // The page as REST answers it: an envelope, in an order of its own.
256 return TestSourceControlHost.processOutput(
257 encode({ count: 2, value: [WORK_ITEM, { ...WORK_ITEM, id: 9 }] }),
258 );
259 }),
260 );
261 },
262 }),
263 ),
264 );
265 const list = api.listIssues({
266 cwd: "/w",
267 host: "dev.azure.com",
268 scope: "acme/Web App",
269 state: "open",
270 involvement: "mentioned",
271 viewer: "octo@acme.test",
272 labels: ["o'hare"],
273 assignee: "theo@acme.test",
274 sort: "created",
275 limit: 2,
276 cursor: "2026-07-01T00:00:00Z|7",
277 });
278 const page = yield* list;
279 yield* list;
280 // The rows come back in WIQL's order, and the cursor is the last one of the page.
281 expect(hydrated).toEqual(["9,7", "9,7"]);
282 expect(page.items.map((item) => item.key)).toEqual(["9", "7"]);
283 expect(page.nextCursor).toBe("2026-07-01T00:00:00Z|7");
284 // Each `az` call costs seconds, so a second list reuses the project's states.
285 expect(typeReads).toBe(1);
286 expect(bodies).toHaveLength(2);
287 expect(bodies[1]).toBe(bodies[0]);
288 expect(bodies[0]).toContain("AND [System.State] NOT IN ('shipped')");
289 const { query } = JSON.parse(bodies[0]!) as { query: string };
290 // Mentions cannot be asked for over REST, so the filter sends no clause for them.
291 expect(query).not.toContain("@RecentMentions");
292 expect(query).toContain(
293 " AND [System.Tags] CONTAINS 'o''hare' AND [System.AssignedTo] = 'theo@acme.test'" +
294 " AND ([System.CreatedDate] < '2026-07-01T00:00:00Z' OR ([System.CreatedDate] = '2026-07-01T00:00:00Z' AND [System.Id] < 7))" +
295 " ORDER BY [System.CreatedDate] DESC, [System.Id] DESC",
296 );
297 }).pipe(Effect.provide(NodeFileSystem.layer)),
298 );
299​
300 it.effect("names the viewer without a request that a sign-in could refuse", () =>
301 Effect.gen(function* () {
302 const api = yield* tracker((args) => {
303 throw new Error(`unexpected az invocation ${args.join(" ")}`);
304 });
305 expect(yield* api.getViewer({ cwd: "/w", host: "dev.azure.com" })).toBe("@Me");
306 }),
307 );
308​
309 it.effect("refuses a scope that is not organization/project without a request", () =>
310 Effect.gen(function* () {
311 let requests = 0;
312 const api = yield* tracker(() => {
313 requests += 1;
314 return "{}";
315 });
316 const error = yield* Effect.flip(
317 api.getIssue({ cwd: "/w", host: "dev.azure.com", scope: "web", key: "7" }),
318 );
319 expect(error.reason).toBe("failed");
320 expect(requests).toBe(0);
321 }),
322 );
323​
324 it.effect("reads a legacy organization's work item and every page of its updates", () =>
325 Effect.gen(function* () {
326 const seen: string[][] = [];
327 const api = yield* tracker((args) => {
328 seen.push([...args]);
329 if (args[0] === "boards") {
330 return encode({
331 ...WORK_ITEM,
332 url: "https://acme.visualstudio.com/p-guid/_apis/wit/workItems/7",
333 relations: [],
334 });
335 }
336 if (args[args.indexOf("--resource") + 1] !== "updates") return answer(args);
337 const rename = (id: number) => ({
338 id,
339 revisedDate: "2026-07-02T00:00:00Z",
340 fields: { "System.Title": { oldValue: "a", newValue: `title ${id}` } },
341 });
342 return encode({
343 value: args.includes("$skip=100")
344 ? [rename(102)]
345 : Array.from({ length: 100 }, (_, index) => rename(index + 2)),
346 });
347 });
348 const issue = yield* api.getIssue({
349 cwd: "/w",
350 host: "acme.visualstudio.com",
351 scope: "Web App",
352 key: "7",
353 });
354 for (const args of seen) {
355 expect(args).toContain("https://acme.visualstudio.com");
356 }
357 expect(issue.url).toBe("https://acme.visualstudio.com/Web%20App/_workitems/edit/7");
358 expect(issue.events).toHaveLength(101);
359 expect(issue.events.at(-1)?.detail).toBe("title 102");
360 }),
361 );
362​
363 it.effect("refuses a write Azure cannot carry out as asked, without writing", () =>
364 Effect.gen(function* () {
365 const writes: string[][] = [];
366 const api = yield* tracker((args) => {
367 if (args[0] === "boards" && args[2] !== "show") writes.push([...args]);
368 return answer(args);
369 });
370 const target = { cwd: "/w", host: "dev.azure.com", key: "7" };
371 const own = { ...target, scope: "acme/Web App" };
372 // Work item 7 is in "Web App"; an id alone would let another project's scope write to it.
373 const elsewhere = { ...target, scope: "acme/Other" };
374 const refusals = yield* Effect.all([
375 Effect.flip(api.update!({ ...elsewhere, title: "x" })),
376 Effect.flip(api.setState!({ ...elsewhere, state: "Active" })),
377 Effect.flip(api.update!({ ...own, assignees: ["a@acme.test", "b@acme.test"] })),
378 // `az` would send the contents of that file as the tag.
379 Effect.flip(api.update!({ ...own, labels: ["@/etc/hostname"] })),
380 Effect.flip(api.getIssue({ ...target, scope: "acme/@secrets" })),
381 // A stock state and another type's state, neither in this Bug's custom workflow.
382 Effect.flip(api.setState!({ ...own, state: "Closed" })),
383 Effect.flip(api.setState!({ ...own, state: "Funded" })),
384 ]);
385 expect(refusals.map((error) => error.reason)).toEqual([
386 "not-found",
387 "not-found",
388 "failed",
389 "failed",
390 "failed",
391 "failed",
392 "failed",
393 ]);
394 expect(writes).toEqual([]);
395 }),
396 );
397​
398 it.effect("moves a work item to a state of its own type, custom ones included", () =>
399 Effect.gen(function* () {
400 const writes: string[][] = [];
401 const api = yield* tracker((args) => {
402 if (args[0] === "boards" && args[2] !== "show") writes.push([...args]);
403 return answer(args);
404 });
405 const own = { cwd: "/w", host: "dev.azure.com", scope: "acme/Web App", key: "7" };
406 yield* api.setState!({ ...own, state: "Shipped" });
407 expect(writes.map((args) => args[args.indexOf("--state") + 1])).toEqual(["Shipped"]);
408 // A type that reports no states falls back to the stock workflow, plus where the item is.
409 const stock = yield* tracker((args) =>
410 args[args.indexOf("--resource") + 1] === "workitemtypes"
411 ? encode({ value: [{ name: "Bug" }] })
412 : answer(args),
413 );
414 expect((yield* stock.getIssue(own)).states.map((state) => state.name)).toEqual([
415 "New",
416 "To Do",
417 "Active",
418 "Doing",
419 "Resolved",
420 "Done",
421 "Closed",
422 "Removed",
423 "Shipped",
424 ]);
425 }),
426 );
427​
428 it.effect("sends text that starts with @ on stdin, where az reads no file for it", () =>
429 Effect.gen(function* () {
430 const writes: Array<{ args: string[]; stdin: string | undefined }> = [];
431 const api = yield* tracker((args, stdin) => {
432 if (args[0] === "boards" && args[2] !== "show") writes.push({ args: [...args], stdin });
433 return answer(args);
434 });
435 const scope = { cwd: "/w", host: "dev.azure.com", scope: "acme/Web App" };
436 yield* api.update!({ ...scope, key: "7", title: "@/etc/hostname", body: "@notes" });
437 yield* api.create!({
438 ...scope,
439 title: "@/etc/hostname",
440 body: "@notes",
441 labels: [],
442 assignees: [],
443 });
444 for (const write of writes) {
445 expect(write.args.filter((arg) => arg.startsWith("@") || arg.includes("=@/"))).toEqual([]);
446 }
447 expect(
448 writes.map((write) => [
449 write.args[2],
450 write.args.find((arg) => arg.endsWith("=@-")),
451 write.stdin,
452 ]),
453 ).toEqual([
454 ["update", "--title=@-", "@/etc/hostname"],
455 ["update", "--description=@-", "@notes"],
456 ["create", "--title=@-", "@/etc/hostname"],
457 ["update", "--description=@-", "@notes"],
458 ]);
459 }),
460 );
461​
462 it.effect("keeps a failure's own text in the cause, out of the detail a caller reads", () =>
463 Effect.gen(function* () {
464 const denied = PlatformError.systemError({
465 _tag: "PermissionDenied",
466 module: "FileSystem",
467 method: "makeTempFileScoped",
468 pathOrDescriptor: "/private/tmp/secret-dir",
469 });
470 const api = yield* AzureDevOpsIssueTracker.make.pipe(
471 Effect.provide(
472 Layer.mergeAll(
473 Layer.succeed(
474 FileSystem.FileSystem,
475 FileSystem.makeNoop({ makeTempFileScoped: () => Effect.fail(denied) }),
476 ),
477 Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),
478 ),
479 ),
480 );
481 const error = yield* Effect.flip(
482 api.comment!({
483 cwd: "/w",
484 host: "dev.azure.com",
485 scope: "acme/Web App",
486 key: "7",
487 body: "x",
488 }),
489 );
490 expect(error.detail).toBe("Could not write the Azure DevOps request body.");
491 expect(error.cause).toBe(denied);
492 }),
493 );
494});