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

azureDevOpsPullRequestJson.test.ts

652 lines20.1 KB

1import * as Result from "effect/Result";
2import { describe, expect, it } from "vite-plus/test";
3​
4import {
5 decodeItemContentJson,
6 decodeIterationChangesJson,
7 decodeIterationsJson,
8 decodePolicyChecksJson,
9 decodePullRequestJson,
10 decodePullRequestListJson,
11 decodeThreadsJson,
12} from "./azureDevOpsPullRequestJson.ts";
13​
14const REST_URL =
15 "https://dev.azure.com/acme/_apis/git/repositories/6f9c9b7f-0000-0000-0000-000000000000/pullRequests/42";
16​
17function pullRequest(overrides: Record<string, unknown> = {}): Record<string, unknown> {
18 return {
19 pullRequestId: 42,
20 title: "Add the change requests page",
21 description: "Ships the page.",
22 status: "active",
23 isDraft: false,
24 mergeStatus: "succeeded",
25 createdBy: { displayName: "Bilal Hassan", uniqueName: "bilal@acme.dev" },
26 sourceRefName: "refs/heads/feat/page",
27 targetRefName: "refs/heads/main",
28 creationDate: "2026-07-01T00:00:00Z",
29 url: REST_URL,
30 repository: { name: "web", project: { name: "platform" } },
31 ...overrides,
32 };
34​
35function expectSuccess<A>(result: Result.Result<A, unknown>): A {
36 expect(Result.isSuccess(result)).toBe(true);
37 if (!Result.isSuccess(result)) throw new Error("expected a successful decode");
38 return result.success;
40​
41const asJson = (value: unknown) => JSON.stringify(value);
42​
43describe("decodePullRequestListJson", () => {
44 it("reads a pull request as a change request", () => {
45 const batch = expectSuccess(decodePullRequestListJson(asJson([pullRequest()])));
46​
47 expect(batch.items).toHaveLength(1);
48 expect(batch.items[0]).toMatchObject({
49 number: 42,
50 title: "Add the change requests page",
51 author: { login: "bilal@acme.dev", name: "Bilal Hassan" },
52 headBranch: "feat/page",
53 baseBranch: "main",
54 state: "open",
55 isDraft: false,
56 mergeability: "mergeable",
57 });
58 });
59​
60 it("assembles a browser url when Azure reports no web link", () => {
61 const batch = expectSuccess(decodePullRequestListJson(asJson([pullRequest()])));
62​
63 expect(batch.items[0]?.url).toBe("https://dev.azure.com/acme/platform/_git/web/pullrequest/42");
64 });
65​
66 it.each([
67 ["completed", "merged"],
68 ["something new", "open"],
69 ])("reads the %s status as %s", (status, expected) => {
70 const batch = expectSuccess(decodePullRequestListJson(asJson([pullRequest({ status })])));
71​
72 expect(batch.items[0]?.state).toBe(expected);
73 });
74​
75 it.each([
76 ["succeeded", "mergeable"],
77 ["conflicts", "conflicting"],
78 ["queued", "unknown"],
79 ])("reads the %s merge status as %s", (mergeStatus, expected) => {
80 const batch = expectSuccess(decodePullRequestListJson(asJson([pullRequest({ mergeStatus })])));
81​
82 expect(batch.items[0]?.mergeability).toBe(expected);
83 });
84​
85 it("stands the closing time in for a last-touched time Azure does not keep", () => {
86 const batch = expectSuccess(
87 decodePullRequestListJson(
88 asJson([pullRequest({ status: "completed", closedDate: "2026-07-05T00:00:00Z" })]),
89 ),
90 );
91​
92 expect(batch.items[0]).toMatchObject({
93 createdAt: "2026-07-01T00:00:00Z",
94 updatedAt: "2026-07-05T00:00:00Z",
95 });
96 });
97​
98 it("skips a malformed row but still counts it, so paging does not stop early", () => {
99 const batch = expectSuccess(
100 decodePullRequestListJson(asJson([{ pullRequestId: "nope" }, pullRequest()])),
101 );
102​
103 expect(batch.items).toHaveLength(1);
104 expect(batch.rawCount).toBe(2);
105 expect(batch.rawIndexes).toEqual([1]);
106 });
107});
108​
109describe("decodePullRequestJson", () => {
110 it("keeps the strategy stored with auto-complete", () => {
111 const armed = expectSuccess(
112 decodePullRequestJson(
113 asJson(
114 pullRequest({
115 autoCompleteSetBy: { displayName: "Bilal Hassan" },
116 completionOptions: { mergeStrategy: "squash" },
117 }),
118 ),
119 ),
120 );
121​
122 expect(armed).toMatchObject({ autoMergeEnabled: true, autoMergeMethod: "squash" });
123​
124 const unspecified = expectSuccess(
125 decodePullRequestJson(
126 asJson(
127 pullRequest({
128 autoCompleteSetBy: { displayName: "Bilal Hassan" },
129 completionOptions: { squashMerge: false },
130 }),
131 ),
132 ),
133 );
134 expect(unspecified?.autoMergeEnabled).toBe(true);
135 expect(unspecified?.autoMergeMethod).toBeUndefined();
136 });
137​
138 it("works out where the repository lives from what Azure returned", () => {
139 const detail = expectSuccess(decodePullRequestJson(asJson(pullRequest())));
140​
141 expect(detail?.location).toEqual({ project: "platform", repository: "web" });
142 });
143​
144 it("reports no repository location when Azure said too little to name one", () => {
145 const detail = expectSuccess(
146 decodePullRequestJson(
147 asJson(
148 pullRequest({
149 url: null,
150 repository: null,
151 _links: {
152 web: { href: "https://dev.azure.com/acme/platform/_git/web/pullrequest/42" },
153 },
154 }),
155 ),
156 ),
157 );
158​
159 expect(detail?.location).toBeNull();
160 });
161​
162 it("returns nothing when Azure gave no way to place the pull request at all", () => {
163 const detail = expectSuccess(
164 decodePullRequestJson(asJson(pullRequest({ url: null, repository: null }))),
165 );
166​
167 expect(detail).toBeNull();
168 });
169});
170​
171describe("decodeThreadsJson", () => {
172 it("takes every real comment of every thread, oldest first", () => {
173 const comments = expectSuccess(
174 decodeThreadsJson(
175 asJson({
176 value: [
177 {
178 id: 2,
179 comments: [
180 {
181 id: 1,
182 content: "Second remark.",
183 author: { displayName: "Julius", uniqueName: "julius@acme.dev" },
184 publishedDate: "2026-07-03T00:00:00Z",
185 },
186 ],
187 },
188 {
189 id: 1,
190 comments: [
191 { id: 1, content: "Bilal voted", commentType: "system", publishedDate: "x" },
192 {
193 id: 2,
194 content: "First remark.",
195 author: { displayName: "Bilal", uniqueName: "bilal@acme.dev" },
196 publishedDate: "2026-07-02T00:00:00Z",
197 },
198 ],
199 },
200 ],
201 }),
202 ),
203 );
204​
205 expect(comments.map((comment) => comment.body)).toEqual(["First remark.", "Second remark."]);
206 expect(comments[0]).toMatchObject({
207 kind: "issue-comment",
208 author: { login: "bilal@acme.dev" },
209 });
210 });
211​
212 it("reads a thread pinned to a file as a review comment on the path its diff uses", () => {
213 const comments = expectSuccess(
214 decodeThreadsJson(
215 asJson({
216 value: [
217 {
218 id: 3,
219 threadContext: { filePath: "/src/app.ts" },
220 comments: [{ id: 1, content: "Rename this.", publishedDate: "2026-07-02T00:00:00Z" }],
221 },
222 ],
223 }),
224 ),
225 );
226​
227 expect(comments[0]).toMatchObject({ kind: "review-comment", path: "src/app.ts" });
228 });
229​
230 it("keeps the replies under a thread, which are as much of the conversation", () => {
231 const comments = expectSuccess(
232 decodeThreadsJson(
233 asJson({
234 value: [
235 {
236 id: 4,
237 threadContext: { filePath: "/src/app.ts" },
238 comments: [
239 { id: 1, content: "Rename this.", publishedDate: "2026-07-02T00:00:00Z" },
240 { id: 2, content: "Renamed.", publishedDate: "2026-07-02T01:00:00Z" },
241 { id: 3, content: "Thanks.", publishedDate: "2026-07-02T02:00:00Z" },
242 ],
243 },
244 ],
245 }),
246 ),
247 );
248​
249 expect(comments.map((comment) => comment.id)).toEqual(["4:1", "4:2", "4:3"]);
250 });
251​
252 it("drops deleted threads and threads with nothing to show", () => {
253 const comments = expectSuccess(
254 decodeThreadsJson(
255 asJson({
256 value: [
257 {
258 id: 1,
259 isDeleted: true,
260 comments: [{ id: 1, content: "gone", publishedDate: "2026-07-02T00:00:00Z" }],
261 },
262 { id: 2, comments: [] },
263 {
264 id: 3,
265 comments: [{ id: 1, content: " ", publishedDate: "2026-07-02T00:00:00Z" }],
266 },
267 ],
268 }),
269 ),
270 );
271​
272 expect(comments).toEqual([]);
273 });
274});
275​
276describe("decodeIterationsJson", () => {
277 const iteration = (id: number, head: string, base: string) => ({
278 id,
279 sourceRefCommit: { commitId: head },
280 commonRefCommit: { commitId: base },
281 targetRefCommit: { commitId: base },
282 });
283​
284 it("reads every push in order, oldest first", () => {
285 const iterations = expectSuccess(
286 decodeIterationsJson(
287 asJson({ value: [iteration(2, "bbb", "base"), iteration(1, "aaa", "base")] }),
288 ),
289 );
290​
291 expect(iterations.map((entry) => entry.id)).toEqual([1, 2]);
292 expect(iterations.at(-1)).toEqual({ id: 2, headCommit: "bbb", mergeBaseCommit: "base" });
293 });
294​
295 it("skips a push Azure could not place both ends of", () => {
296 const iterations = expectSuccess(
297 decodeIterationsJson(
298 asJson({
299 value: [{ id: 1, sourceRefCommit: { commitId: "aaa" } }, iteration(2, "bbb", "base")],
300 }),
301 ),
302 );
303​
304 expect(iterations.map((entry) => entry.id)).toEqual([2]);
305 });
306});
307​
308describe("decodeIterationChangesJson", () => {
309 it("names each changed file without the slash Azure leads its paths with", () => {
310 const page = expectSuccess(
311 decodeIterationChangesJson(
312 asJson({
313 changeEntries: [
314 { changeType: "add", item: { path: "/DEMO.md", objectId: "ec00" } },
315 {
316 changeType: "edit",
317 item: { path: "/README.md", objectId: "8f80", originalObjectId: "0ca4" },
318 },
319 { changeType: "delete", item: { path: "/OLD.md", originalObjectId: "1111" } },
320 ],
321 }),
322 ),
323 );
324​
325 expect(page.changes.map((change) => [change.path, change.changeKind])).toEqual([
326 ["DEMO.md", "new"],
327 ["README.md", "change"],
328 ["OLD.md", "deleted"],
329 ]);
330 });
331​
332 it("keeps a space at the end of a file's name, which belongs to the name", () => {
333 const page = expectSuccess(
334 decodeIterationChangesJson(
335 asJson({
336 changeEntries: [
337 { changeType: "edit", item: { path: "/docs/readme.md ", objectId: "ec00" } },
338 {
339 changeType: "rename",
340 sourceServerItem: "/docs/old.md ",
341 item: { path: "/docs/moved.md", objectId: "aaaa", originalObjectId: "aaaa" },
342 },
343 ],
344 }),
345 ),
346 );
347​
348 expect(page.changes.map((change) => [change.path, change.oldPath])).toEqual([
349 ["docs/readme.md ", "docs/readme.md "],
350 ["docs/moved.md", "docs/old.md "],
351 ]);
352 });
353​
354 it("reads a rename as one file that moved, and says whether it also changed", () => {
355 const page = expectSuccess(
356 decodeIterationChangesJson(
357 asJson({
358 changeEntries: [
359 {
360 changeType: "rename",
361 sourceServerItem: "/docs/old.md",
362 item: { path: "/docs/new.md", objectId: "aaaa", originalObjectId: "aaaa" },
363 },
364 {
365 changeType: "edit, rename",
366 sourceServerItem: "/src/old.ts",
367 item: { path: "/src/new.ts", objectId: "bbbb", originalObjectId: "cccc" },
368 },
369 ],
370 }),
371 ),
372 );
373​
374 expect(page.changes).toEqual([
375 {
376 path: "docs/new.md",
377 oldPath: "docs/old.md",
378 changeKind: "rename-pure",
379 objectId: "aaaa",
380 originalObjectId: "aaaa",
381 },
382 {
383 path: "src/new.ts",
384 oldPath: "src/old.ts",
385 changeKind: "rename-changed",
386 objectId: "bbbb",
387 originalObjectId: "cccc",
388 },
389 ]);
390 });
391​
392 it("drops the folders Azure lists alongside the files that changed", () => {
393 const page = expectSuccess(
394 decodeIterationChangesJson(
395 asJson({
396 changeEntries: [
397 { changeType: "add", item: { path: "/docs", isFolder: true, gitObjectType: "tree" } },
398 { changeType: "add", item: { path: "/docs/page.md", objectId: "dddd" } },
399 ],
400 }),
401 ),
402 );
403​
404 expect(page.changes.map((change) => change.path)).toEqual(["docs/page.md"]);
405 });
406​
407 it("reads where a rename came from out of either of the two places Azure names it", () => {
408 const page = expectSuccess(
409 decodeIterationChangesJson(
410 asJson({
411 changeEntries: [
412 {
413 changeType: "rename",
414 originalPath: "/docs/old.md",
415 item: { path: "/docs/new.md", objectId: "aaaa", originalObjectId: "aaaa" },
416 },
417 ],
418 }),
419 ),
420 );
421​
422 expect(page.changes.at(0)?.oldPath).toBe("docs/old.md");
423 });
424});
425​
426describe("decodeItemContentJson", () => {
427 it("reads an empty file as empty rather than as a failure to look", () => {
428 expect(expectSuccess(decodeItemContentJson(asJson({ path: "/a.md" })))).toEqual({
429 contents: "",
430 isBinary: false,
431 });
432 });
433});
434​
435describe("what az devops invoke answers with", () => {
436 it("reads the envelope the extension adds its own continuation token to", () => {
437 expect(
438 expectSuccess(decodeThreadsJson(asJson({ value: [], count: 0, continuation_token: null }))),
439 ).toEqual([]);
440​
441 expect(
442 expectSuccess(
443 decodeIterationsJson(
444 asJson({
445 count: 1,
446 continuation_token: null,
447 value: [
448 {
449 id: 1,
450 sourceRefCommit: { commitId: "f4031105213c68f197cd46ea303bb5e72acc889a" },
451 commonRefCommit: { commitId: "acbc805382edd6c38b8d6de6ba9f9bba9da4ad35" },
452 },
453 ],
454 }),
455 ),
456 ),
457 ).toEqual([
458 {
459 id: 1,
460 headCommit: "f4031105213c68f197cd46ea303bb5e72acc889a",
461 mergeBaseCommit: "acbc805382edd6c38b8d6de6ba9f9bba9da4ad35",
462 },
463 ]);
464 });
465​
466 it("keeps the files of a change that names neither their object type nor their page after it", () => {
467 const page = expectSuccess(
468 decodeIterationChangesJson(
469 asJson({
470 continuation_token: null,
471 changeEntries: [
472 { changeType: "add", item: { path: "/DEMO.md", objectId: "EC005DB24" } },
473 { changeType: "edit", item: { path: "/README.md", objectId: "8F8047A49" } },
474 ],
475 }),
476 ),
477 );
478​
479 expect(page.nextSkip).toBeNull();
480 expect(page.changes).toEqual([
481 {
482 path: "DEMO.md",
483 oldPath: "DEMO.md",
484 changeKind: "new",
485 objectId: "EC005DB24",
486 originalObjectId: null,
487 },
488 {
489 path: "README.md",
490 oldPath: "README.md",
491 changeKind: "change",
492 objectId: "8F8047A49",
493 originalObjectId: null,
494 },
495 ]);
496 });
497​
498 it("reads a text file whose content type Azure calls a stream", () => {
499 expect(
500 expectSuccess(
501 decodeItemContentJson(
502 asJson({
503 path: "/README.md",
504 objectId: "8f8047a49",
505 gitObjectType: "blob",
506 content: "# T3Demo\n",
507 contentMetadata: {
508 contentType: "application/octet-stream",
509 encoding: 65001,
510 extension: "md",
511 fileName: "README.md",
512 },
513 continuation_token: null,
514 }),
515 ),
516 ),
517 ).toEqual({ contents: "# T3Demo\n", isBinary: false });
518 });
519});
520​
521describe("decodePolicyChecksJson", () => {
522 const BUILD_TYPE = "0609b952-1397-4640-95ec-e00a01b2c241";
523 const STATUS_TYPE = "cbdc66da-9728-4af8-aada-9a5a32e4a226";
524 const CONFIGURATION_URL =
525 "https://dev.azure.com/acme/6f9c9b7f-0000-0000-0000-000000000000/_apis/policy/configurations/54";
526​
527 const evaluation = (
528 status: string,
529 context: Record<string, unknown> | null,
530 settings: Record<string, unknown> = { displayName: "PR validation" },
531 configuration: Record<string, unknown> = {},
532 ) => ({
533 status,
534 context,
535 configuration: {
536 url: CONFIGURATION_URL,
537 isBlocking: true,
538 type: { id: BUILD_TYPE, displayName: "Build" },
539 settings,
540 ...configuration,
541 },
542 });
543​
544 const decodeOne = (value: unknown, isDraft = false) =>
545 expectSuccess(decodePolicyChecksJson(asJson([value]), { isDraft })).checks[0];
546​
547 it.each([
548 ["approved", "success"],
549 ["running", "pending"],
550 ["rejected", "failure"],
551 ["broken", "failure"],
552 ["notApplicable", "skipped"],
553 ["someNewStatus", "pending"],
554 ])("reads a build evaluation %s as %s", (status, expected) => {
555 expect(decodeOne(evaluation(status, { buildId: 21959 }))?.status).toBe(expected);
556 });
557​
558 it("links a build to its results page, in the project the policy belongs to", () => {
559 expect(decodeOne(evaluation("running", { buildId: 21959 }))).toEqual({
560 name: "PR validation",
561 status: "pending",
562 description: null,
563 url: "https://dev.azure.com/acme/6f9c9b7f-0000-0000-0000-000000000000/_build/results?buildId=21959",
564 required: true,
565 });
566 });
567​
568 it("names a build policy without its own name after the pipeline it runs", () => {
569 const check = decodeOne(evaluation("approved", { buildDefinitionName: "PR - Validation" }, {}));
570 expect(check?.name).toBe("PR - Validation");
571 expect(check?.url).toBeNull();
572 });
573​
574 it("reads a status policy, which reports an external service's verdict", () => {
575 expect(
576 decodeOne(
577 evaluation(
578 "rejected",
579 null,
580 { defaultDisplayName: "SonarCloud", statusName: "gate" },
581 {
582 type: { id: STATUS_TYPE, displayName: "Status" },
583 },
584 ),
585 ),
586 ).toMatchObject({ name: "SonarCloud", status: "failure", url: null });
587 });
588​
589 // Both arrive as `queued`; a spinner would never stop on either.
590 it.each([
591 {
592 name: "an expired build",
593 value: evaluation("queued", { buildId: 21919, isExpired: true }),
594 },
595 {
596 name: "a build only a person can queue",
597 value: evaluation("queued", null, { displayName: "Nightly", manualQueueOnly: true }),
598 },
599 ])("asks for action on $name", ({ value }) => {
600 const check = decodeOne(value);
601 expect(check?.status).toBe("action-required");
602 expect(check?.description).not.toBeNull();
603 });
604​
605 // A watch waits on every check that asks for action, and nobody has to queue an optional one.
606 it.each([
607 { name: "expired", value: evaluation("queued", { buildId: 21919, isExpired: true }) },
608 {
609 name: "manual-only",
610 value: evaluation("queued", null, { displayName: "Nightly", manualQueueOnly: true }),
611 },
612 ])("skips an optional $name build that nobody queued", ({ value }) => {
613 const check = decodeOne({
614 ...value,
615 configuration: { ...value.configuration, isBlocking: false },
616 });
617 expect(check?.status).toBe("skipped");
618 expect(check?.description).not.toBeNull();
619 });
620​
621 it("reports nothing for a build Azure holds back on a draft", () => {
622 expect(decodeOne(evaluation("queued", null), true)).toBeUndefined();
623 expect(decodeOne(evaluation("running", { buildId: 21960 }), true)?.status).toBe("pending");
624 });
625​
626 it("keeps a build that is really waiting for an agent as running", () => {
627 expect(decodeOne(evaluation("queued", { buildId: 21960, isExpired: false }))?.status).toBe(
628 "pending",
629 );
630 expect(decodeOne(evaluation("queued", null))?.status).toBe("pending");
631 });
632​
633 it.each([
634 {
635 name: "a review gate, which waits on people",
636 configuration: { type: { id: "fa4e907d-c16b-4a4c-9dfa-4906e5d171dd" } },
637 },
638 { name: "a disabled policy", configuration: { isEnabled: false } },
639 { name: "a deleted policy", configuration: { isDeleted: true } },
640 ])("leaves out $name but still counts the row for paging", ({ configuration }) => {
641 const row = evaluation("queued", null, {}, configuration);
642 expect(expectSuccess(decodePolicyChecksJson(asJson([row]), { isDraft: false }))).toEqual({
643 checks: [],
644 rawCount: 1,
645 });
646 });
647​
648 it("fails the page on a row it cannot read, which could be a required check", () => {
649 const rows = asJson([evaluation("rejected", null), { status: 7 }]);
650 expect(Result.isFailure(decodePolicyChecksJson(rows, { isDraft: false }))).toBe(true);
651 });
652});