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

BitbucketPullRequestApi.test.ts

988 lines34.6 KB

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