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

BitbucketPullRequestApi.test.ts

1,128 lines37.8 KB

1import { afterEach, assert, expect, it, vi } from "@effect/vitest";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as TestClock from "effect/testing/TestClock";
6​
7import * as BitbucketApi from "./BitbucketApi.ts";
8import * as BitbucketPullRequestApi from "./BitbucketPullRequestApi.ts";
9​
10const mockedRequest = vi.fn<BitbucketApi.BitbucketApi["Service"]["request"]>();
11​
12const layer = it.layer(
13 BitbucketPullRequestApi.layer.pipe(
14 Layer.provide(
15 Layer.mock(BitbucketApi.BitbucketApi)({
16 request: mockedRequest,
17 }),
18 ),
19 ),
20);
21​
22function response(body: string) {
23 return { body, truncated: false };
25​
26function page(count: number, firstNumber: number, next?: string): string {
27 return JSON.stringify({
28 pagelen: 50,
29 size: count,
30 values: Array.from({ length: count }, (_, index) => ({
31 id: firstNumber + index,
32 title: `Pull request ${firstNumber + index}`,
33 state: "OPEN",
34 created_on: "2026-06-16T05:04:32+00:00",
35 updated_on: "2026-06-16T05:04:33+00:00",
36 source: { branch: { name: "feat/page" } },
37 destination: { branch: { name: "master" } },
38 links: { html: { href: `https://bitbucket.org/acme/web/pull-requests/${firstNumber}` } },
39 })),
40 ...(next === undefined ? {} : { next }),
41 });
43​
44function valuePage(values: ReadonlyArray<unknown>, next?: string): string {
45 return JSON.stringify({ values, ...(next === undefined ? {} : { next }) });
47​
48const bilal = { uuid: "{bilal}", nickname: "bilal" };
49const octocat = { uuid: "{octocat}", nickname: "octocat" };
50const hubot = { uuid: "{hubot}", nickname: "hubot" };
51​
52function pullRequestJson(overrides: Record<string, unknown>): string {
53 return JSON.stringify({
54 id: 7,
55 title: "Pull request 7",
56 state: "OPEN",
57 author: bilal,
58 created_on: "2026-06-16T05:04:32+00:00",
59 updated_on: "2026-06-16T05:04:33+00:00",
60 source: { branch: { name: "feat/page" } },
61 destination: { branch: { name: "master" } },
62 links: { html: { href: "https://bitbucket.org/acme/web/pull-requests/7" } },
63 ...overrides,
64 });
66​
67function callAt(index: number) {
68 const call = mockedRequest.mock.calls[index];
69 assert.isDefined(call);
70 return call[0];
72​
73function filterOfCall(index: number): string | null {
74 const url = callAt(index).url;
75 return new URLSearchParams(url.slice(url.indexOf("?") + 1)).get("q");
77​
78afterEach(() => {
79 mockedRequest.mockReset();
80});
81​
82layer("BitbucketPullRequestApi.layer", (it) => {
83 it.effect("asks for reviewers, newest first, at Bitbucket's page ceiling", () =>
84 Effect.gen(function* () {
85 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(3, 1))));
86 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
87​
88 const batch = yield* api.listPullRequests({
89 repository: "acme/web",
90 state: "open",
91 limit: 50,
92 });
93​
94 assert.strictEqual(batch.items.length, 3);
95 assert.isFalse(batch.truncated);
96 const url = callAt(0).url;
97 expect(url).toContain("/repositories/acme/web/pullrequests");
98 expect(url).toContain("state=OPEN");
99 // Over 50 Bitbucket answers with an empty page and no error, so it is never exceeded.
100 expect(url).toContain("pagelen=50");
101 expect(url).toContain("sort=-updated_on");
102 expect(url).toContain("fields=%2Bvalues.reviewers");
103 }),
104 );
105​
106 it.effect("follows the cursor Bitbucket sends rather than counting offsets", () =>
107 Effect.gen(function* () {
108 const next = "https://api.bitbucket.org/2.0/repositories/acme/web/pullrequests?page=2";
109 mockedRequest
110 .mockReturnValueOnce(Effect.succeed(response(page(50, 1, next))))
111 .mockReturnValueOnce(Effect.succeed(response(page(50, 51))));
112 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
113​
114 const batch = yield* api.listPullRequests({
115 repository: "acme/web",
116 state: "open",
117 limit: 100,
118 });
119​
120 assert.strictEqual(batch.items.length, 100);
121 assert.isFalse(batch.truncated);
122 assert.strictEqual(callAt(1).url, next);
123 }),
124 );
125​
126 it.effect("stops at the caller's page and says more remain", () =>
127 Effect.gen(function* () {
128 const next = "https://api.bitbucket.org/2.0/repositories/acme/web/pullrequests?page=2";
129 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(50, 1, next))));
130 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
131​
132 const batch = yield* api.listPullRequests({
133 repository: "acme/web",
134 state: "open",
135 limit: 50,
136 });
137​
138 assert.strictEqual(batch.items.length, 50);
139 assert.isTrue(batch.truncated);
140 assert.strictEqual(mockedRequest.mock.calls.length, 1);
141 }),
142 );
143​
144 it.effect("counts the rows it walked past as more to come", () =>
145 Effect.gen(function* () {
146 // Bitbucket pages in fifties whatever was asked for, so a request for ninety-nine reads a
147 // hundred and drops one.
148 const next = "https://api.bitbucket.org/2.0/repositories/acme/web/pullrequests?page=2";
149 mockedRequest
150 .mockReturnValueOnce(Effect.succeed(response(page(50, 1, next))))
151 .mockReturnValueOnce(Effect.succeed(response(page(50, 51))));
152 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
153​
154 const batch = yield* api.listPullRequests({
155 repository: "acme/web",
156 state: "open",
157 limit: 99,
158 });
159​
160 assert.strictEqual(batch.items.length, 99);
161 assert.isTrue(batch.truncated);
162 }),
163 );
164​
165 it.effect("searches with a filter expression, which is all Bitbucket offers", () =>
166 Effect.gen(function* () {
167 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
168 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
169​
170 yield* api.listPullRequests({
171 repository: "acme/web",
172 state: "open",
173 limit: 50,
174 query: "page",
175 });
176​
177 expect(filterOfCall(0)).toBe('(title ~ "page" OR description ~ "page")');
178 expect(callAt(0).url).toContain("state=OPEN");
179 }),
180 );
181​
182 it.effect("escapes a quote and a backslash, so a search cannot reshape the filter", () =>
183 Effect.gen(function* () {
184 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
185 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
186​
187 yield* api.listPullRequests({
188 repository: "acme/web",
189 state: "open",
190 limit: 50,
191 query: String.raw`a\" OR state = "MERGED"`,
192 });
193​
194 const literal = String.raw`a\\\" OR state = \"MERGED\"`;
195 expect(filterOfCall(0)).toBe(`(title ~ "${literal}" OR description ~ "${literal}")`);
196 }),
197 );
198​
199 it.effect("asks for no filter at all when the reader typed only spaces", () =>
200 Effect.gen(function* () {
201 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
202 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
203​
204 yield* api.listPullRequests({
205 repository: "acme/web",
206 state: "open",
207 limit: 50,
208 query: " ",
209 });
210​
211 assert.isNull(filterOfCall(0));
212 }),
213 );
214​
215 it.effect("carries on from the instant the last slice ended on", () =>
216 Effect.gen(function* () {
217 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
218 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
219​
220 yield* api.listPullRequests({
221 repository: "acme/web",
222 state: "open",
223 limit: 50,
224 cursor: { updatedBefore: "2026-07-02T00:00:00.123456+00:00", delivered: 50 },
225 });
226​
227 expect(filterOfCall(0)).toBe("updated_on <= 2026-07-02T00:00:00.123456+00:00");
228 expect(callAt(0).url).toContain("sort=-updated_on");
229 }),
230 );
231​
232 it.effect("narrows by the reader's words and by where it left off at once", () =>
233 Effect.gen(function* () {
234 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
235 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
236​
237 yield* api.listPullRequests({
238 repository: "acme/web",
239 state: "open",
240 limit: 50,
241 query: "page",
242 cursor: { updatedBefore: "2026-07-02T00:00:00+00:00", delivered: 50 },
243 });
244​
245 // Bitbucket takes one `q`, so the two narrowings are joined rather than one replacing the
246 // other — and the search keeps its brackets, which is what keeps the AND out of its OR.
247 expect(filterOfCall(0)).toBe(
248 '(title ~ "page" OR description ~ "page") AND updated_on <= 2026-07-02T00:00:00+00:00',
249 );
250 }),
251 );
252​
253 it.effect("asks for declined pull requests on the closed tab", () =>
254 Effect.gen(function* () {
255 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
256 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
257​
258 yield* api.listPullRequests({ repository: "acme/web", state: "closed", limit: 50 });
259​
260 expect(callAt(0).url).toContain("state=DECLINED");
261 }),
262 );
263​
264 it.effect("asks for every state at once on the All tab", () =>
265 Effect.gen(function* () {
266 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
267 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
268​
269 yield* api.listPullRequests({ repository: "acme/web", state: "all", limit: 50 });
270​
271 // Bitbucket unions repeated state parameters, which is the only way to span them.
272 const url = callAt(0).url;
273 for (const state of ["OPEN", "MERGED", "DECLINED", "SUPERSEDED"]) {
274 expect(url).toContain(`state=${state}`);
275 }
276 }),
277 );
278​
279 it.effect("counts a superseded pull request as closed", () =>
280 Effect.gen(function* () {
281 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
282 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
283​
284 yield* api.listPullRequests({ repository: "acme/web", state: "closed", limit: 50 });
285​
286 expect(callAt(0).url).toContain("state=DECLINED");
287 expect(callAt(0).url).toContain("state=SUPERSEDED");
288 }),
289 );
290​
291 it.effect("refuses a repository that is not workspace and slug", () =>
292 Effect.gen(function* () {
293 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
294​
295 const error = yield* Effect.flip(
296 api.listPullRequests({ repository: "acme/team/web", state: "open", limit: 50 }),
297 );
298​
299 assert.strictEqual(error._tag, "BitbucketRepositoryUnsupportedError");
300 assert.strictEqual(mockedRequest.mock.calls.length, 0);
301 }),
302 );
303​
304 it.effect("returns the diff verbatim, because Bitbucket already sends a patch", () =>
305 Effect.gen(function* () {
306 const patch = "diff --git a/a.ts b/a.ts\n--- a/a.ts\n+++ b/a.ts\n@@ -1 +1 @@\n-a\n+b\n";
307 mockedRequest.mockReturnValueOnce(Effect.succeed(response(patch)));
308 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
309​
310 const diff = yield* api.getPullRequestDiff({ repository: "acme/web", number: 7 });
311​
312 assert.strictEqual(diff.patch, patch);
313 assert.isFalse(diff.truncated);
314 expect(callAt(0)).toMatchObject({
315 url: "/repositories/acme/web/pullrequests/7/diff",
316 maxBytes: 8 * 1024 * 1024,
317 });
318 }),
319 );
320​
321 it.effect("reads a named commit's own patch, which pages no further than the whole of it", () =>
322 Effect.gen(function* () {
323 const patch = "diff --git a/a.ts b/a.ts\n--- a/a.ts\n+++ b/a.ts\n@@ -1 +1 @@\n-a\n+b\n";
324 mockedRequest.mockReturnValueOnce(Effect.succeed(response(patch)));
325 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
326​
327 const diff = yield* api.getPullRequestDiff({
328 repository: "acme/web",
329 number: 7,
330 commit: "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0",
331 });
332​
333 assert.strictEqual(diff.patch, patch);
334 expect(callAt(0)).toMatchObject({
335 url: "/repositories/acme/web/diff/a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0",
336 maxBytes: 8 * 1024 * 1024,
337 });
338 }),
339 );
340​
341 it.effect("refuses a commit that is not a sha rather than reading it into a URL", () =>
342 Effect.gen(function* () {
343 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
344​
345 const error = yield* Effect.flip(
346 api.getPullRequestDiff({
347 repository: "acme/web",
348 number: 7,
349 commit: "../../acme/other/diff/deadbeef",
350 }),
351 );
352​
353 assert.strictEqual(error._tag, "BitbucketDiffCommitError");
354 assert.strictEqual(mockedRequest.mock.calls.length, 0);
355 }),
356 );
357​
358 it.effect("reads every file version the patch states, not only the paths asked about", () =>
359 Effect.gen(function* () {
360 mockedRequest.mockReturnValueOnce(
361 Effect.succeed(
362 response(
363 [
364 "diff --git a/a.ts b/a.ts",
365 "index 1111111..2222222 100644",
366 "--- a/a.ts",
367 "+++ b/a.ts",
368 "@@ -1 +1 @@",
369 "-a",
370 "+b",
371 "diff --git a/b.ts b/b.ts",
372 "index 3333333..4444444 100644",
373 "--- a/b.ts",
374 "+++ b/b.ts",
375 "@@ -1 +1 @@",
376 "-c",
377 "+d",
378 "",
379 ].join("\n"),
380 ),
381 ),
382 );
383 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
384​
385 const revisions = yield* api.getFileRevisions({
386 repository: "acme/web",
387 number: 71,
388 paths: ["a.ts", "missing.ts"],
389 });
390​
391 assert.deepStrictEqual(
392 [...revisions.revisions],
393 [
394 ["a.ts", "2222222"],
395 ["b.ts", "4444444"],
396 ["missing.ts", ""],
397 ],
398 );
399 assert.strictEqual(revisions.complete, true);
400 expect(callAt(0)).toMatchObject({ url: "/repositories/acme/web/pullrequests/71/diff" });
401 }),
402 );
403​
404 it.effect("says nothing about the files past the end of a patch it could not read whole", () =>
405 Effect.gen(function* () {
406 mockedRequest.mockReturnValueOnce(
407 Effect.succeed({
408 body: "diff --git a/a.ts b/a.ts\nindex 1111111..2222222 100644\n@@ -1 +1 @@\n",
409 truncated: true,
410 }),
411 );
412 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
413​
414 const revisions = yield* api.getFileRevisions({
415 repository: "acme/web",
416 number: 72,
417 paths: ["a.ts", "past-the-cut.ts"],
418 });
419​
420 assert.deepStrictEqual([...revisions.revisions], [["a.ts", "2222222"]]);
421 assert.strictEqual(revisions.complete, false);
422 }),
423 );
424​
425 it.effect("reads the patch once for a run of ticks, not once a tick", () =>
426 Effect.gen(function* () {
427 mockedRequest.mockReturnValue(
428 Effect.succeed(
429 response(
430 [
431 "diff --git a/a.ts b/a.ts",
432 "index 1111111..2222222 100644",
433 "@@ -1 +1 @@",
434 "diff --git a/b.ts b/b.ts",
435 "index 3333333..4444444 100644",
436 "@@ -1 +1 @@",
437 "",
438 ].join("\n"),
439 ),
440 ),
441 );
442 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
443​
444 const first = yield* api.getFileRevisions({
445 repository: "acme/web",
446 number: 74,
447 paths: ["a.ts"],
448 });
449 const second = yield* api.getFileRevisions({
450 repository: "acme/web",
451 number: 74,
452 paths: ["b.ts"],
453 });
454​
455 const both = [
456 ["a.ts", "2222222"],
457 ["b.ts", "4444444"],
458 ];
459 assert.deepStrictEqual([...first.revisions], both);
460 assert.deepStrictEqual([...second.revisions], both);
461 assert.strictEqual(mockedRequest.mock.calls.length, 1);
462 }),
463 );
464​
465 it.effect("reads the patch afresh once the one it held has aged out", () =>
466 Effect.gen(function* () {
467 mockedRequest.mockReturnValue(
468 Effect.succeed(
469 response("diff --git a/a.ts b/a.ts\nindex 1111111..2222222 100644\n@@ -1 +1 @@\n"),
470 ),
471 );
472 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
473 const read = () =>
474 api.getFileRevisions({ repository: "acme/web", number: 75, paths: ["a.ts"] });
475​
476 yield* read();
477 yield* read();
478 assert.strictEqual(mockedRequest.mock.calls.length, 1);
479​
480 yield* TestClock.adjust(Duration.seconds(30));
481 yield* read();
482 assert.strictEqual(mockedRequest.mock.calls.length, 2);
483 }),
484 );
485​
486 it.effect("asks Bitbucket nothing when no file has been ticked off", () =>
487 Effect.gen(function* () {
488 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
489​
490 const revisions = yield* api.getFileRevisions({
491 repository: "acme/web",
492 number: 73,
493 paths: [],
494 });
495​
496 assert.strictEqual(revisions.revisions.size, 0);
497 assert.strictEqual(mockedRequest.mock.calls.length, 0);
498 }),
499 );
500​
501 it.effect("aggregates every diffstat page", () =>
502 Effect.gen(function* () {
503 const next = "https://api.bitbucket.org/2.0/diffstat?page=2";
504 mockedRequest
505 .mockReturnValueOnce(
506 Effect.succeed(
507 response(
508 valuePage(
509 [
510 { lines_added: 9, lines_removed: 2 },
511 { lines_added: 3, lines_removed: 1 },
512 ],
513 next,
514 ),
515 ),
516 ),
517 )
518 .mockReturnValueOnce(
519 Effect.succeed(response(valuePage([{ lines_added: 4, lines_removed: 7 }]))),
520 );
521 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
522​
523 const stat = yield* api.getDiffStat({ repository: "acme/web", number: 7 });
524​
525 expect(stat).toEqual({ additions: 16, deletions: 10, changedFiles: 3 });
526 expect(callAt(1).url).toBe(next);
527 }),
528 );
529​
530 it.effect("returns the complete commit timeline oldest first across pages", () =>
531 Effect.gen(function* () {
532 const next = "https://api.bitbucket.org/2.0/commits?page=2";
533 mockedRequest
534 .mockReturnValueOnce(
535 Effect.succeed(
536 response(
537 valuePage(
538 [
539 { hash: "ddd", message: "fourth", date: "2026-07-04T00:00:00Z" },
540 { hash: "ccc", message: "third", date: "2026-07-03T00:00:00Z" },
541 ],
542 next,
543 ),
544 ),
545 ),
546 )
547 .mockReturnValueOnce(
548 Effect.succeed(
549 response(
550 valuePage([
551 { hash: "bbb", message: "second", date: "2026-07-02T00:00:00Z" },
552 { hash: "aaa", message: "first", date: "2026-07-01T00:00:00Z" },
553 ]),
554 ),
555 ),
556 );
557 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
558​
559 const commits = yield* api.listCommits({ repository: "acme/web", number: 7 });
560​
561 expect(commits.map((commit) => commit.oid)).toEqual(["aaa", "bbb", "ccc", "ddd"]);
562 expect(callAt(1).url).toBe(next);
563 }),
564 );
565​
566 it.effect("returns build statuses from every page", () =>
567 Effect.gen(function* () {
568 const next = "https://api.bitbucket.org/2.0/statuses?page=2";
569 mockedRequest
570 .mockReturnValueOnce(
571 Effect.succeed(response(valuePage([{ name: "Build", state: "SUCCESSFUL" }], next))),
572 )
573 .mockReturnValueOnce(
574 Effect.succeed(response(valuePage([{ name: "Lint", state: "FAILED" }]))),
575 );
576 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
577​
578 const checks = yield* api.listChecks({ repository: "acme/web", number: 7 });
579​
580 expect(checks.map((check) => [check.name, check.status])).toEqual([
581 ["Build", "success"],
582 ["Lint", "failure"],
583 ]);
584 expect(callAt(1).url).toBe(next);
585 }),
586 );
587​
588 it.effect("reads an empty conflict list as mergeable", () =>
589 Effect.gen(function* () {
590 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
591 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
592​
593 const mergeability = yield* api.getMergeability({ repository: "acme/web", number: 7 });
594​
595 assert.strictEqual(mergeability, "mergeable");
596 expect(callAt(0).url).toBe("/repositories/acme/web/pullrequests/7/conflicts");
597 }),
598 );
599​
600 it.effect("merges with Bitbucket's own name for the strategy", () =>
601 Effect.gen(function* () {
602 mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
603 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
604​
605 yield* api.runAction({
606 repository: "acme/web",
607 number: 7,
608 action: "merge",
609 mergeMethod: "rebase",
610 });
611​
612 expect(callAt(0)).toMatchObject({
613 method: "POST",
614 url: "/repositories/acme/web/pullrequests/7/merge",
615 body: '{"merge_strategy":"rebase_fast_forward"}',
616 });
617 }),
618 );
619​
620 it.effect("closes a pull request by declining it", () =>
621 Effect.gen(function* () {
622 mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
623 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
624​
625 yield* api.runAction({ repository: "acme/web", number: 7, action: "close" });
626​
627 expect(callAt(0)).toMatchObject({
628 method: "POST",
629 url: "/repositories/acme/web/pullrequests/7/decline",
630 });
631 }),
632 );
633​
634 it.effect("posts a comment as a JSON document, so the body stays text", () =>
635 Effect.gen(function* () {
636 mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
637 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
638​
639 yield* api.comment({ repository: "acme/web", number: 7, body: "true" });
640​
641 expect(callAt(0)).toMatchObject({
642 method: "POST",
643 url: "/repositories/acme/web/pullrequests/7/comments",
644 body: '{"content":{"raw":"true"}}',
645 });
646 }),
647 );
648​
649 it.effect("rewrites a title alone, without touching anything else", () =>
650 Effect.gen(function* () {
651 mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
652 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
653​
654 yield* api.updateChangeRequest({ repository: "acme/web", number: 7, title: "A new title" });
655​
656 const call = callAt(0);
657 expect(call.method).toBe("PUT");
658 expect(call.url).toBe("/repositories/acme/web/pullrequests/7");
659 // Bitbucket's PUT is a partial update, so a field left out of the body is left as it was.
660 expect(JSON.parse(call.body ?? "")).toEqual({ title: "A new title" });
661 }),
662 );
663​
664 it.effect("leaves out the half of the pull request it was not asked about", () =>
665 Effect.gen(function* () {
666 mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
667 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
668​
669 yield* api.updateChangeRequest({ repository: "acme/web", number: 7, body: "New body." });
670​
671 expect(JSON.parse(callAt(0).body ?? "")).toEqual({ description: "New body." });
672 }),
673 );
674​
675 it.effect("writes both fields when both were rewritten", () =>
676 Effect.gen(function* () {
677 mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
678 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
679​
680 yield* api.updateChangeRequest({
681 repository: "acme/web",
682 number: 7,
683 title: "A new title",
684 body: "New body.",
685 });
686​
687 expect(JSON.parse(callAt(0).body ?? "")).toEqual({
688 title: "A new title",
689 description: "New body.",
690 });
691 }),
692 );
693​
694 it.effect("rewrites a comment where it stands, whichever kind it is", () =>
695 Effect.gen(function* () {
696 mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
697 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
698​
699 yield* api.updateComment({
700 repository: "acme/web",
701 number: 7,
702 commentId: "10",
703 body: "Edited.",
704 });
705​
706 expect(callAt(0)).toMatchObject({
707 method: "PUT",
708 url: "/repositories/acme/web/pullrequests/7/comments/10",
709 body: '{"content":{"raw":"Edited."}}',
710 });
711 }),
712 );
713​
714 it.effect("asks for the time a pull request closed, which Bitbucket leaves out by default", () =>
715 Effect.gen(function* () {
716 mockedRequest.mockReturnValueOnce(
717 Effect.succeed(
718 response(
719 pullRequestJson({ state: "MERGED", closed_on: "2025-06-16T23:40:46.222238+00:00" }),
720 ),
721 ),
722 );
723 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
724​
725 const pullRequest = yield* api.getPullRequest({ repository: "acme/web", number: 7 });
726​
727 expect(callAt(0).url).toBe("/repositories/acme/web/pullrequests/7?fields=%2Bclosed_on");
728 assert.strictEqual(pullRequest.closedAt, "2025-06-16T23:40:46.222Z");
729 }),
730 );
731​
732 it.effect("fails the read when Bitbucket answers with something unreadable", () =>
733 Effect.gen(function* () {
734 mockedRequest.mockReturnValueOnce(
735 Effect.succeed(response(JSON.stringify({ error: "nope" }))),
736 );
737 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
738​
739 const error = yield* Effect.flip(api.getPullRequest({ repository: "acme/web", number: 7 }));
740​
741 assert.strictEqual(error._tag, "BitbucketPullRequestReadError");
742 }),
743 );
744​
745 it.effect("states a failure once, without stacking one message inside another", () =>
746 Effect.gen(function* () {
747 mockedRequest.mockReturnValueOnce(
748 Effect.fail(
749 new BitbucketApi.BitbucketResponseError({
750 operation: "request",
751 status: 500,
752 responseBodyLength: 0,
753 }),
754 ),
755 );
756 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
757​
758 const error = yield* Effect.flip(api.getViewer());
759​
760 assert.strictEqual(error.detail, "Bitbucket returned HTTP 500.");
761 }),
762 );
763​
764 it.effect("fails when the credentials belong to no named account", () =>
765 Effect.gen(function* () {
766 mockedRequest.mockReturnValueOnce(Effect.succeed(response(JSON.stringify({}))));
767 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
768​
769 const error = yield* Effect.flip(api.getViewer());
770​
771 assert.strictEqual(error._tag, "BitbucketViewerUnavailableError");
772 }),
773 );
774​
775 it.effect("follows Bitbucket's cursor and reassembles a thread that spans two pages", () =>
776 Effect.gen(function* () {
777 mockedRequest.mockReturnValueOnce(
778 Effect.succeed(
779 response(
780 JSON.stringify({
781 next: "https://api.bitbucket.org/2.0/comments?page=2",
782 values: [
783 {
784 id: 10,
785 content: { raw: "rename this" },
786 user: { nickname: "bilal" },
787 created_on: "2026-06-16T05:04:32+00:00",
788 inline: { path: "src/a.ts", to: 12 },
789 },
790 ],
791 }),
792 ),
793 ),
794 );
795 mockedRequest.mockReturnValueOnce(
796 Effect.succeed(
797 response(
798 JSON.stringify({
799 values: [
800 {
801 id: 11,
802 content: { raw: "done" },
803 user: { nickname: "julius" },
804 created_on: "2026-06-16T06:04:32+00:00",
805 parent: { id: 10 },
806 },
807 ],
808 }),
809 ),
810 ),
811 );
812 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
813​
814 const { comments, threads, truncated } = yield* api.listComments({
815 repository: "acme/web",
816 number: 7,
817 });
818​
819 expect(callAt(1).url).toBe("https://api.bitbucket.org/2.0/comments?page=2");
820 expect(comments.map((comment) => comment.id)).toEqual(["10", "11"]);
821 expect(threads[0]?.comments.map((comment) => comment.id)).toEqual(["10", "11"]);
822 assert.isFalse(truncated);
823 }),
824 );
825​
826 it.effect("stops the comment walk at its bound and says the conversation was cut short", () =>
827 Effect.gen(function* () {
828 mockedRequest.mockReturnValue(
829 Effect.succeed(
830 response(
831 JSON.stringify({
832 next: "https://api.bitbucket.org/2.0/comments?page=2",
833 values: [
834 {
835 id: 10,
836 content: { raw: "again" },
837 created_on: "2026-06-16T05:04:32+00:00",
838 },
839 ],
840 }),
841 ),
842 ),
843 );
844 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
845​
846 const { truncated } = yield* api.listComments({ repository: "acme/web", number: 7 });
847​
848 assert.strictEqual(mockedRequest.mock.calls.length, 10);
849 assert.isTrue(truncated);
850 }),
851 );
852​
853 it.effect("reassembles a thread from the flat comment list, replies included", () =>
854 Effect.gen(function* () {
855 mockedRequest.mockReturnValueOnce(
856 Effect.succeed(
857 response(
858 JSON.stringify({
859 values: [
860 {
861 id: 10,
862 content: { raw: "rename this" },
863 user: { nickname: "bilal" },
864 created_on: "2026-06-16T05:04:32+00:00",
865 inline: { path: "src/a.ts", to: 12, from: null },
866 resolution: { type: "pullrequest_comment_resolution" },
867 },
868 {
869 id: 11,
870 content: { raw: "done" },
871 user: { nickname: "julius" },
872 created_on: "2026-06-16T06:04:32+00:00",
873 parent: { id: 10 },
874 },
875 {
876 id: 12,
877 content: { raw: "thanks" },
878 user: { nickname: "bilal" },
879 created_on: "2026-06-16T07:04:32+00:00",
880 parent: { id: 11 },
881 },
882 {
883 id: 13,
884 content: { raw: "ship it" },
885 user: { nickname: "bilal" },
886 created_on: "2026-06-16T08:04:32+00:00",
887 },
888 ],
889 }),
890 ),
891 ),
892 );
893 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
894​
895 const { threads } = yield* api.listComments({ repository: "acme/web", number: 7 });
896​
897 assert.strictEqual(threads.length, 1);
898 expect(threads[0]).toMatchObject({
899 id: "10",
900 path: "src/a.ts",
901 line: 12,
902 side: "right",
903 isResolved: true,
904 });
905 expect(threads[0]?.comments.map((comment) => comment.id)).toEqual(["10", "11", "12"]);
906 }),
907 );
908​
909 it.effect("writes a review's line comments, its summary, then its verdict", () =>
910 Effect.gen(function* () {
911 mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
912 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
913​
914 yield* api.submitReview({
915 repository: "acme/web",
916 number: 7,
917 verdict: "request-changes",
918 body: "Two things.",
919 comments: [
920 {
921 path: "src/a.ts",
922 position: { kind: "deleted", oldLine: 12 },
923 body: "why remove?",
924 },
925 ],
926 });
927​
928 expect(callAt(0).url).toContain("/pullrequests/7/comments");
929 expect(JSON.parse(callAt(0).body ?? "")).toEqual({
930 content: { raw: "why remove?" },
931 inline: { path: "src/a.ts", from: 12 },
932 });
933 expect(callAt(1).url).toContain("/pullrequests/7/comments");
934 expect(callAt(2).url).toContain("/pullrequests/7/request-changes");
935 }),
936 );
937​
938 it.effect("resolves by creating the sub-resource and unresolves by deleting it", () =>
939 Effect.gen(function* () {
940 mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
941 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
942​
943 yield* api.setCommentResolution({
944 repository: "acme/web",
945 number: 7,
946 commentId: "10",
947 resolved: true,
948 });
949 yield* api.setCommentResolution({
950 repository: "acme/web",
951 number: 7,
952 commentId: "10",
953 resolved: false,
954 });
955​
956 assert.strictEqual(callAt(0).method, "POST");
957 assert.strictEqual(callAt(1).method, "DELETE");
958 expect(callAt(0).url).toContain("/comments/10/resolve");
959 }),
960 );
961​
962 it.effect("replies by naming the comment it answers", () =>
963 Effect.gen(function* () {
964 mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
965 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
966​
967 yield* api.replyToComment({
968 repository: "acme/web",
969 number: 7,
970 commentId: "10",
971 body: "Fixed.",
972 });
973​
974 expect(JSON.parse(callAt(0).body ?? "")).toEqual({
975 content: { raw: "Fixed." },
976 parent: { id: 10 },
977 });
978 }),
979 );
980​
981 it.effect("asks for the credentials' permission on this repository, and nobody else's", () =>
982 Effect.gen(function* () {
983 mockedRequest.mockReturnValue(
984 Effect.succeed(
985 response(
986 JSON.stringify({ values: [{ type: "repository_permission", permission: "read" }] }),
987 ),
988 ),
989 );
990 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
991​
992 assert.isFalse(yield* api.getRepositoryPermission({ repository: "acme/web" }));
993​
994 expect(new URL(callAt(0).url, "https://api.bitbucket.org").pathname).toBe(
995 "/user/workspaces/acme/permissions/repositories",
996 );
997 assert.strictEqual(filterOfCall(0), 'repository.full_name="acme/web"');
998 }),
999 );
1000​
1001 it.effect("matches repository permissions after normalizing whitespace around segments", () =>
1002 Effect.gen(function* () {
1003 mockedRequest.mockImplementation((input) => {
1004 const url = new URL(input.url, "https://api.bitbucket.org");
1005 const matches =
1006 url.pathname === "/user/workspaces/acme/permissions/repositories" &&
1007 url.searchParams.get("q") === 'repository.full_name="acme/web"';
1008 return Effect.succeed(response(valuePage(matches ? [{ permission: "read" }] : [])));
1009 });
1010 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
1011​
1012 assert.isFalse(yield* api.getRepositoryPermission({ repository: " acme / web " }));
1013 }),
1014 );
1015​
1016 it.effect("escapes a repository name before it goes inside a filter literal", () =>
1017 Effect.gen(function* () {
1018 mockedRequest.mockReturnValue(Effect.succeed(response(JSON.stringify({ values: [] }))));
1019 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
1020​
1021 yield* api.getRepositoryPermission({ repository: 'acme/we"b' });
1022​
1023 assert.strictEqual(filterOfCall(0), 'repository.full_name="acme/we\\"b"');
1024 }),
1025 );
1026​
1027 const permissionFailure = (status: number) =>
1028 Effect.fail(
1029 new BitbucketApi.BitbucketResponseError({
1030 operation: "request",
1031 status,
1032 responseBodyLength: 0,
1033 }),
1034 );
1035​
1036 it.effect.each([403, 404, 410])(
1037 "reads HTTP %s from the permissions endpoint as an unknown permission",
1038 (status) =>
1039 Effect.gen(function* () {
1040 mockedRequest.mockReturnValue(permissionFailure(status));
1041 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
1042​
1043 assert.isTrue(yield* api.getRepositoryPermission({ repository: "acme/web" }));
1044 }),
1045 );
1046​
1047 it.effect.each([401, 500])("still fails the permission read on HTTP %s", (status) =>
1048 Effect.gen(function* () {
1049 mockedRequest.mockReturnValue(permissionFailure(status));
1050 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
1051​
1052 const error = yield* Effect.flip(api.getRepositoryPermission({ repository: "acme/web" }));
1053 assert.strictEqual(error._tag, "BitbucketResponseError");
1054 if (error._tag === "BitbucketResponseError") {
1055 assert.strictEqual(error.status, status);
1057 }),
1058 );
1059​
1060 it.effect("reads the workspace's people and marks whoever is already a reviewer", () =>
1061 Effect.gen(function* () {
1062 mockedRequest
1063 .mockReturnValueOnce(Effect.succeed(response(pullRequestJson({ reviewers: [octocat] }))))
1064 .mockReturnValueOnce(
1065 Effect.succeed(
1066 response(
1067 JSON.stringify({ values: [{ user: bilal }, { user: octocat }, { user: hubot }] }),
1068 ),
1069 ),
1070 );
1071 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
1072​
1073 const list = yield* api.listReviewerCandidates({ repository: "acme/web", number: 7 });
1074​
1075 expect(callAt(1).url).toBe("/workspaces/acme/members?pagelen=50");
1076 expect(list.candidates.map((candidate) => [candidate.id, candidate.isRequested])).toEqual([
1077 ["{octocat}", true],
1078 ["{hubot}", false],
1079 ]);
1080 assert.isFalse(list.truncated);
1081 }),
1082 );
1083​
1084 it.effect("writes the reviewer set back with the one being asked added to it", () =>
1085 Effect.gen(function* () {
1086 mockedRequest
1087 .mockReturnValueOnce(Effect.succeed(response(pullRequestJson({ reviewers: [octocat] }))))
1088 .mockReturnValueOnce(Effect.succeed(response("{}")));
1089 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
1090​
1091 yield* api.setReviewerRequest({
1092 repository: "acme/web",
1093 number: 7,
1094 reviewers: [{ id: "{hubot}" }],
1095 requested: true,
1096 });
1097​
1098 // Bitbucket writes `reviewers` whole, so the one already on the pull request travels with
1099 // the new one or the request would take them off it.
1100 const call = callAt(1);
1101 expect(call.method).toBe("PUT");
1102 expect(call.url).toBe("/repositories/acme/web/pullrequests/7");
1103 expect(JSON.parse(call.body ?? "")).toEqual({
1104 reviewers: [{ uuid: "{octocat}" }, { uuid: "{hubot}" }],
1105 });
1106 }),
1107 );
1108​
1109 it.effect("takes a reviewer out of the set rather than clearing it", () =>
1110 Effect.gen(function* () {
1111 mockedRequest
1112 .mockReturnValueOnce(
1113 Effect.succeed(response(pullRequestJson({ reviewers: [octocat, hubot] }))),
1115 .mockReturnValueOnce(Effect.succeed(response("{}")));
1116 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
1117​
1118 yield* api.setReviewerRequest({
1119 repository: "acme/web",
1120 number: 7,
1121 reviewers: [{ id: "{hubot}" }],
1122 requested: false,
1123 });
1124​
1125 expect(JSON.parse(callAt(1).body ?? "")).toEqual({ reviewers: [{ uuid: "{octocat}" }] });
1126 }),
1127 );
1128});