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

AzureDevOpsIssueTracker.test.ts

537 lines20.1 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 let finished = "Shipped";
224 let workflowUnavailable = false;
225 const api = yield* AzureDevOpsIssueTracker.make.pipe(
226 Effect.provide(
227 Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({
228 execute: ({ args }) => {
229 const resource = args[args.indexOf("--resource") + 1];
230 if (resource === "workitems") {
231 // `az devops invoke` resolves `wit/workitems` to the create route
232 // (`.../workitems/${type}`) and fails before sending anything.
233 return Effect.fail(
234 new AzureDevOpsCli.AzureDevOpsCommandFailedError({
235 operation: "execute",
236 command: "az",
237 cwd: "/w",
238 argumentCount: args.length,
239 cause: "KeyError: 'type'",
240 }),
241 );
242 }
243 if (resource === "workitemtypes") {
244 typeReads += 1;
245 if (workflowUnavailable) {
246 return Effect.fail(
247 new AzureDevOpsCli.AzureDevOpsCommandFailedError({
248 operation: "execute",
249 command: "az",
250 cwd: "/w",
251 argumentCount: args.length,
252 cause: "workflow metadata unavailable",
253 }),
254 );
255 }
256 return Effect.succeed(
257 TestSourceControlHost.processOutput(
258 encode({
259 value: [{ name: "Bug", states: [{ name: finished, category: "Completed" }] }],
260 }),
261 ),
262 );
263 }
264 if (resource !== "wiql" && resource !== "workitemsbatch") {
265 return Effect.succeed(TestSourceControlHost.processOutput(answer(args)));
266 }
267 return fs.readFileString(args[args.indexOf("--in-file") + 1]!).pipe(
268 Effect.orDie,
269 Effect.map((body) => {
270 if (resource === "wiql") {
271 bodies.push(body);
272 return TestSourceControlHost.processOutput(
273 encode({ workItems: [{ id: 9 }, { id: 7 }, { id: 3 }] }),
274 );
275 }
276 hydrated.push((JSON.parse(body) as { ids: number[] }).ids.join(","));
277 // The page as REST answers it: an envelope, in an order of its own.
278 return TestSourceControlHost.processOutput(
279 encode({ count: 2, value: [WORK_ITEM, { ...WORK_ITEM, id: 9 }] }),
280 );
281 }),
282 );
283 },
284 }),
285 ),
286 );
287 const list = api.listIssues({
288 cwd: "/w",
289 host: "dev.azure.com",
290 scope: "acme/Web App",
291 state: "open",
292 involvement: "mentioned",
293 viewer: "octo@acme.test",
294 labels: ["o'hare"],
295 assignee: "theo@acme.test",
296 sort: "created",
297 limit: 2,
298 cursor: "2026-07-01T00:00:00Z|7",
299 });
300 const page = yield* list;
301 yield* list;
302 // The rows come back in WIQL's order, and the cursor is the last one of the page.
303 expect(hydrated).toEqual(["9,7", "9,7"]);
304 expect(page.items.map((item) => item.key)).toEqual(["9", "7"]);
305 expect(page.nextCursor).toBe("2026-07-01T00:00:00Z|7");
306 // Each `az` call costs seconds, so a second list reuses the project's states.
307 expect(typeReads).toBe(1);
308 expect(bodies).toHaveLength(2);
309 expect(bodies[1]).toBe(bodies[0]);
310 expect(bodies[0]).toContain("AND [System.State] NOT IN ('shipped')");
311 const { query } = JSON.parse(bodies[0]!) as { query: string };
312 // Mentions cannot be asked for over REST, so the filter sends no clause for them.
313 expect(query).not.toContain("@RecentMentions");
314 expect(query).toContain(
315 " AND [System.Tags] CONTAINS 'o''hare' AND [System.AssignedTo] = 'theo@acme.test'" +
316 " AND ([System.CreatedDate] < '2026-07-01T00:00:00Z' OR ([System.CreatedDate] = '2026-07-01T00:00:00Z' AND [System.Id] < 7))" +
317 " ORDER BY [System.CreatedDate] DESC, [System.Id] DESC",
318 );
319​
320 // An explicit refresh rereads the workflow; a failed one keeps the last good states.
321 const firstPage = {
322 cwd: "/w",
323 host: "dev.azure.com",
324 scope: "acme/Web App",
325 state: "open",
326 involvement: "all",
327 sort: "updated",
328 limit: 2,
329 } as const;
330 finished = "Released";
331 yield* api.listIssues({ ...firstPage, refresh: true });
332 expect(typeReads).toBe(2);
333 expect(bodies[2]).toContain("AND [System.State] NOT IN ('released')");
334 workflowUnavailable = true;
335 const refreshError = yield* Effect.flip(api.listIssues({ ...firstPage, refresh: true }));
336 expect(refreshError).toMatchObject({ operation: "listIssues", reason: "failed" });
337 yield* api.listIssues(firstPage);
338 expect(typeReads).toBe(3);
339 expect(bodies[3]).toContain("AND [System.State] NOT IN ('released')");
340 }).pipe(Effect.provide(NodeFileSystem.layer)),
341 );
342​
343 it.effect("names the viewer without a request that a sign-in could refuse", () =>
344 Effect.gen(function* () {
345 const api = yield* tracker((args) => {
346 throw new Error(`unexpected az invocation ${args.join(" ")}`);
347 });
348 expect(yield* api.getViewer({ cwd: "/w", host: "dev.azure.com" })).toBe("@Me");
349 }),
350 );
351​
352 it.effect("refuses a scope that is not organization/project without a request", () =>
353 Effect.gen(function* () {
354 let requests = 0;
355 const api = yield* tracker(() => {
356 requests += 1;
357 return "{}";
358 });
359 const error = yield* Effect.flip(
360 api.getIssue({ cwd: "/w", host: "dev.azure.com", scope: "web", key: "7" }),
361 );
362 expect(error.reason).toBe("failed");
363 expect(requests).toBe(0);
364 }),
365 );
366​
367 it.effect("reads a legacy organization's work item and every page of its updates", () =>
368 Effect.gen(function* () {
369 const seen: string[][] = [];
370 const api = yield* tracker((args) => {
371 seen.push([...args]);
372 if (args[0] === "boards") {
373 return encode({
374 ...WORK_ITEM,
375 url: "https://acme.visualstudio.com/p-guid/_apis/wit/workItems/7",
376 relations: [],
377 });
378 }
379 if (args[args.indexOf("--resource") + 1] !== "updates") return answer(args);
380 const rename = (id: number) => ({
381 id,
382 revisedDate: "2026-07-02T00:00:00Z",
383 fields: { "System.Title": { oldValue: "a", newValue: `title ${id}` } },
384 });
385 return encode({
386 value: args.includes("$skip=100")
387 ? [rename(102)]
388 : Array.from({ length: 100 }, (_, index) => rename(index + 2)),
389 });
390 });
391 const issue = yield* api.getIssue({
392 cwd: "/w",
393 host: "acme.visualstudio.com",
394 scope: "Web App",
395 key: "7",
396 });
397 for (const args of seen) {
398 expect(args).toContain("https://acme.visualstudio.com");
399 }
400 expect(issue.url).toBe("https://acme.visualstudio.com/Web%20App/_workitems/edit/7");
401 expect(issue.events).toHaveLength(101);
402 expect(issue.events.at(-1)?.detail).toBe("title 102");
403 }),
404 );
405​
406 it.effect("refuses a write Azure cannot carry out as asked, without writing", () =>
407 Effect.gen(function* () {
408 const writes: string[][] = [];
409 const api = yield* tracker((args) => {
410 if (args[0] === "boards" && args[2] !== "show") writes.push([...args]);
411 return answer(args);
412 });
413 const target = { cwd: "/w", host: "dev.azure.com", key: "7" };
414 const own = { ...target, scope: "acme/Web App" };
415 // Work item 7 is in "Web App"; an id alone would let another project's scope write to it.
416 const elsewhere = { ...target, scope: "acme/Other" };
417 const refusals = yield* Effect.all([
418 Effect.flip(api.update!({ ...elsewhere, title: "x" })),
419 Effect.flip(api.setState!({ ...elsewhere, state: "Active" })),
420 Effect.flip(api.update!({ ...own, assignees: ["a@acme.test", "b@acme.test"] })),
421 // `az` would send the contents of that file as the tag.
422 Effect.flip(api.update!({ ...own, labels: ["@/etc/hostname"] })),
423 Effect.flip(api.getIssue({ ...target, scope: "acme/@secrets" })),
424 // A stock state and another type's state, neither in this Bug's custom workflow.
425 Effect.flip(api.setState!({ ...own, state: "Closed" })),
426 Effect.flip(api.setState!({ ...own, state: "Funded" })),
427 ]);
428 expect(refusals.map((error) => error.reason)).toEqual([
429 "not-found",
430 "not-found",
431 "failed",
432 "failed",
433 "failed",
434 "failed",
435 "failed",
436 ]);
437 expect(writes).toEqual([]);
438 }),
439 );
440​
441 it.effect("moves a work item to a state of its own type, custom ones included", () =>
442 Effect.gen(function* () {
443 const writes: string[][] = [];
444 const api = yield* tracker((args) => {
445 if (args[0] === "boards" && args[2] !== "show") writes.push([...args]);
446 return answer(args);
447 });
448 const own = { cwd: "/w", host: "dev.azure.com", scope: "acme/Web App", key: "7" };
449 yield* api.setState!({ ...own, state: "Shipped" });
450 expect(writes.map((args) => args[args.indexOf("--state") + 1])).toEqual(["Shipped"]);
451 // A type that reports no states falls back to the stock workflow, plus where the item is.
452 const stock = yield* tracker((args) =>
453 args[args.indexOf("--resource") + 1] === "workitemtypes"
454 ? encode({ value: [{ name: "Bug" }] })
455 : answer(args),
456 );
457 expect((yield* stock.getIssue(own)).states.map((state) => state.name)).toEqual([
458 "New",
459 "To Do",
460 "Active",
461 "Doing",
462 "Resolved",
463 "Done",
464 "Closed",
465 "Removed",
466 "Shipped",
467 ]);
468 }),
469 );
470​
471 it.effect("sends text that starts with @ on stdin, where az reads no file for it", () =>
472 Effect.gen(function* () {
473 const writes: Array<{ args: string[]; stdin: string | undefined }> = [];
474 const api = yield* tracker((args, stdin) => {
475 if (args[0] === "boards" && args[2] !== "show") writes.push({ args: [...args], stdin });
476 return answer(args);
477 });
478 const scope = { cwd: "/w", host: "dev.azure.com", scope: "acme/Web App" };
479 yield* api.update!({ ...scope, key: "7", title: "@/etc/hostname", body: "@notes" });
480 yield* api.create!({
481 ...scope,
482 title: "@/etc/hostname",
483 body: "@notes",
484 labels: [],
485 assignees: [],
486 });
487 for (const write of writes) {
488 expect(write.args.filter((arg) => arg.startsWith("@") || arg.includes("=@/"))).toEqual([]);
489 }
490 expect(
491 writes.map((write) => [
492 write.args[2],
493 write.args.find((arg) => arg.endsWith("=@-")),
494 write.stdin,
495 ]),
496 ).toEqual([
497 ["update", "--title=@-", "@/etc/hostname"],
498 ["update", "--description=@-", "@notes"],
499 ["create", "--title=@-", "@/etc/hostname"],
500 ["update", "--description=@-", "@notes"],
501 ]);
502 }),
503 );
504​
505 it.effect("keeps a failure's own text in the cause, out of the detail a caller reads", () =>
506 Effect.gen(function* () {
507 const denied = PlatformError.systemError({
508 _tag: "PermissionDenied",
509 module: "FileSystem",
510 method: "makeTempFileScoped",
511 pathOrDescriptor: "/private/tmp/secret-dir",
512 });
513 const api = yield* AzureDevOpsIssueTracker.make.pipe(
514 Effect.provide(
515 Layer.mergeAll(
516 Layer.succeed(
517 FileSystem.FileSystem,
518 FileSystem.makeNoop({ makeTempFileScoped: () => Effect.fail(denied) }),
519 ),
520 Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),
521 ),
522 ),
523 );
524 const error = yield* Effect.flip(
525 api.comment!({
526 cwd: "/w",
527 host: "dev.azure.com",
528 scope: "acme/Web App",
529 key: "7",
530 body: "x",
531 }),
532 );
533 expect(error.detail).toBe("Could not write the Azure DevOps request body.");
534 expect(error.cause).toBe(denied);
535 }),
536 );
537});