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

azureDevOpsPullRequestJson.test.ts

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