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

BitbucketPullRequestApi.test.ts

874 lines30.8 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("fails the read when Bitbucket answers with something unreadable", () =>
514 Effect.gen(function* () {
515 mockedRequest.mockReturnValueOnce(
516 // @effect-diagnostics-next-line preferSchemaOverJson:off
517 Effect.succeed(response(JSON.stringify({ error: "nope" }))),
518 );
519 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
520​
521 const error = yield* Effect.flip(api.getPullRequest({ repository: "acme/web", number: 7 }));
522​
523 assert.strictEqual(error._tag, "BitbucketPullRequestReadError");
524 }),
525 );
526​
527 it.effect("states a failure once, without stacking one message inside another", () =>
528 Effect.gen(function* () {
529 mockedRequest.mockReturnValueOnce(
530 Effect.fail(
531 new BitbucketApi.BitbucketResponseError({
532 operation: "request",
533 status: 500,
534 responseBodyLength: 0,
535 }),
536 ),
537 );
538 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
539​
540 const error = yield* Effect.flip(api.getViewer());
541​
542 // The fact only; the provider adds the operation around it.
543 assert.strictEqual(error.detail, "Bitbucket returned HTTP 500.");
544 }),
545 );
546​
547 it.effect("fails when the credentials belong to no named account", () =>
548 Effect.gen(function* () {
549 // @effect-diagnostics-next-line preferSchemaOverJson:off
550 mockedRequest.mockReturnValueOnce(Effect.succeed(response(JSON.stringify({}))));
551 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
552​
553 const error = yield* Effect.flip(api.getViewer());
554​
555 assert.strictEqual(error._tag, "BitbucketViewerUnavailableError");
556 }),
557 );
558​
559 it.effect("follows Bitbucket's cursor and reassembles a thread that spans two pages", () =>
560 Effect.gen(function* () {
561 mockedRequest.mockReturnValueOnce(
562 Effect.succeed(
563 response(
564 // @effect-diagnostics-next-line preferSchemaOverJson:off
565 JSON.stringify({
566 next: "https://api.bitbucket.org/2.0/comments?page=2",
567 values: [
568 {
569 id: 10,
570 content: { raw: "rename this" },
571 user: { nickname: "bilal" },
572 created_on: "2026-06-16T05:04:32+00:00",
573 inline: { path: "src/a.ts", to: 12 },
574 },
575 ],
576 }),
577 ),
578 ),
579 );
580 mockedRequest.mockReturnValueOnce(
581 Effect.succeed(
582 response(
583 // The reply arrives a page after the remark it answers, which is why the threads
584 // are only assembled once every page is in hand.
585 // @effect-diagnostics-next-line preferSchemaOverJson:off
586 JSON.stringify({
587 values: [
588 {
589 id: 11,
590 content: { raw: "done" },
591 user: { nickname: "julius" },
592 created_on: "2026-06-16T06:04:32+00:00",
593 parent: { id: 10 },
594 },
595 ],
596 }),
597 ),
598 ),
599 );
600 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
601​
602 const { comments, threads, truncated } = yield* api.listComments({
603 repository: "acme/web",
604 number: 7,
605 });
606​
607 expect(callAt(1).url).toBe("https://api.bitbucket.org/2.0/comments?page=2");
608 expect(comments.map((comment) => comment.id)).toEqual(["10", "11"]);
609 expect(threads[0]?.comments.map((comment) => comment.id)).toEqual(["10", "11"]);
610 assert.isFalse(truncated);
611 }),
612 );
613​
614 it.effect("stops the comment walk at its bound and says the conversation was cut short", () =>
615 Effect.gen(function* () {
616 // Bitbucket that always names a next page: the walk has to end itself.
617 mockedRequest.mockReturnValue(
618 Effect.succeed(
619 response(
620 // @effect-diagnostics-next-line preferSchemaOverJson:off
621 JSON.stringify({
622 next: "https://api.bitbucket.org/2.0/comments?page=2",
623 values: [
624 {
625 id: 10,
626 content: { raw: "again" },
627 created_on: "2026-06-16T05:04:32+00:00",
628 },
629 ],
630 }),
631 ),
632 ),
633 );
634 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
635​
636 const { truncated } = yield* api.listComments({ repository: "acme/web", number: 7 });
637​
638 assert.strictEqual(mockedRequest.mock.calls.length, 10);
639 assert.isTrue(truncated);
640 }),
641 );
642​
643 it.effect("reassembles a thread from the flat comment list, replies included", () =>
644 Effect.gen(function* () {
645 mockedRequest.mockReturnValueOnce(
646 Effect.succeed(
647 response(
648 // @effect-diagnostics-next-line preferSchemaOverJson:off
649 JSON.stringify({
650 values: [
651 {
652 id: 10,
653 content: { raw: "rename this" },
654 user: { nickname: "bilal" },
655 created_on: "2026-06-16T05:04:32+00:00",
656 inline: { path: "src/a.ts", to: 12, from: null },
657 resolution: { type: "pullrequest_comment_resolution" },
658 },
659 {
660 id: 11,
661 content: { raw: "done" },
662 user: { nickname: "julius" },
663 created_on: "2026-06-16T06:04:32+00:00",
664 parent: { id: 10 },
665 },
666 // A reply to a reply still belongs to the thread its root opened.
667 {
668 id: 12,
669 content: { raw: "thanks" },
670 user: { nickname: "bilal" },
671 created_on: "2026-06-16T07:04:32+00:00",
672 parent: { id: 11 },
673 },
674 {
675 id: 13,
676 content: { raw: "ship it" },
677 user: { nickname: "bilal" },
678 created_on: "2026-06-16T08:04:32+00:00",
679 },
680 ],
681 }),
682 ),
683 ),
684 );
685 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
686​
687 const { threads } = yield* api.listComments({ repository: "acme/web", number: 7 });
688​
689 assert.strictEqual(threads.length, 1);
690 expect(threads[0]).toMatchObject({
691 id: "10",
692 path: "src/a.ts",
693 line: 12,
694 side: "right",
695 isResolved: true,
696 });
697 expect(threads[0]?.comments.map((comment) => comment.id)).toEqual(["10", "11", "12"]);
698 }),
699 );
700​
701 it.effect("writes a review's line comments, its summary, then its verdict", () =>
702 Effect.gen(function* () {
703 mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
704 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
705​
706 yield* api.submitReview({
707 repository: "acme/web",
708 number: 7,
709 verdict: "request-changes",
710 body: "Two things.",
711 comments: [{ path: "src/a.ts", line: 12, side: "left", body: "why remove?" }],
712 });
713​
714 expect(callAt(0).url).toContain("/pullrequests/7/comments");
715 // @effect-diagnostics-next-line preferSchemaOverJson:off
716 expect(JSON.parse(callAt(0).body ?? "")).toEqual({
717 content: { raw: "why remove?" },
718 inline: { path: "src/a.ts", from: 12 },
719 });
720 expect(callAt(1).url).toContain("/pullrequests/7/comments");
721 // The verdict goes last, so a review that failed part-way is never a rejection either.
722 expect(callAt(2).url).toContain("/pullrequests/7/request-changes");
723 }),
724 );
725​
726 it.effect("resolves by creating the sub-resource and unresolves by deleting it", () =>
727 Effect.gen(function* () {
728 mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
729 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
730​
731 yield* api.setCommentResolution({
732 repository: "acme/web",
733 number: 7,
734 commentId: "10",
735 resolved: true,
736 });
737 yield* api.setCommentResolution({
738 repository: "acme/web",
739 number: 7,
740 commentId: "10",
741 resolved: false,
742 });
743​
744 assert.strictEqual(callAt(0).method, "POST");
745 assert.strictEqual(callAt(1).method, "DELETE");
746 expect(callAt(0).url).toContain("/comments/10/resolve");
747 }),
748 );
749​
750 it.effect("replies by naming the comment it answers", () =>
751 Effect.gen(function* () {
752 mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
753 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
754​
755 yield* api.replyToComment({
756 repository: "acme/web",
757 number: 7,
758 commentId: "10",
759 body: "Fixed.",
760 });
761​
762 // @effect-diagnostics-next-line preferSchemaOverJson:off
763 expect(JSON.parse(callAt(0).body ?? "")).toEqual({
764 content: { raw: "Fixed." },
765 parent: { id: 10 },
766 });
767 }),
768 );
769​
770 it.effect("asks for the credentials' permission on this repository, and nobody else's", () =>
771 Effect.gen(function* () {
772 mockedRequest.mockReturnValue(
773 Effect.succeed(
774 response(
775 // @effect-diagnostics-next-line preferSchemaOverJson:off
776 JSON.stringify({ values: [{ type: "repository_permission", permission: "read" }] }),
777 ),
778 ),
779 );
780 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
781​
782 assert.isFalse(yield* api.getRepositoryPermission({ repository: "acme/web" }));
783​
784 expect(callAt(0).url).toContain("/user/permissions/repositories");
785 assert.strictEqual(filterOfCall(0), 'repository.full_name="acme/web"');
786 }),
787 );
788​
789 it.effect("escapes a repository name before it goes inside a filter literal", () =>
790 Effect.gen(function* () {
791 // @effect-diagnostics-next-line preferSchemaOverJson:off
792 mockedRequest.mockReturnValue(Effect.succeed(response(JSON.stringify({ values: [] }))));
793 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
794​
795 yield* api.getRepositoryPermission({ repository: 'acme/we"b' });
796​
797 // A quote would otherwise end the literal and leave the rest standing as filter syntax.
798 assert.strictEqual(filterOfCall(0), 'repository.full_name="acme/we\\"b"');
799 }),
800 );
801​
802 it.effect("reads the workspace's people and marks whoever is already a reviewer", () =>
803 Effect.gen(function* () {
804 mockedRequest
805 .mockReturnValueOnce(Effect.succeed(response(pullRequestJson({ reviewers: [octocat] }))))
806 .mockReturnValueOnce(
807 Effect.succeed(
808 response(
809 // @effect-diagnostics-next-line preferSchemaOverJson:off
810 JSON.stringify({ values: [{ user: bilal }, { user: octocat }, { user: hubot }] }),
811 ),
812 ),
813 );
814 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
815​
816 const list = yield* api.listReviewerCandidates({ repository: "acme/web", number: 7 });
817​
818 // The people live on the workspace: nothing on a repository lists who may review it.
819 expect(callAt(1).url).toBe("/workspaces/acme/members?pagelen=50");
820 expect(list.candidates.map((candidate) => [candidate.id, candidate.isRequested])).toEqual([
821 ["{octocat}", true],
822 ["{hubot}", false],
823 ]);
824 assert.isFalse(list.truncated);
825 }),
826 );
827​
828 it.effect("writes the reviewer set back with the one being asked added to it", () =>
829 Effect.gen(function* () {
830 mockedRequest
831 .mockReturnValueOnce(Effect.succeed(response(pullRequestJson({ reviewers: [octocat] }))))
832 .mockReturnValueOnce(Effect.succeed(response("{}")));
833 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
834​
835 yield* api.setReviewerRequest({
836 repository: "acme/web",
837 number: 7,
838 reviewers: [{ id: "{hubot}" }],
839 requested: true,
840 });
841​
842 // Bitbucket writes `reviewers` whole, so the one already on the pull request travels with
843 // the new one or the request would take them off it.
844 const call = callAt(1);
845 expect(call.method).toBe("PUT");
846 expect(call.url).toBe("/repositories/acme/web/pullrequests/7");
847 // @effect-diagnostics-next-line preferSchemaOverJson:off
848 expect(JSON.parse(call.body ?? "")).toEqual({
849 reviewers: [{ uuid: "{octocat}" }, { uuid: "{hubot}" }],
850 });
851 }),
852 );
853​
854 it.effect("takes a reviewer out of the set rather than clearing it", () =>
855 Effect.gen(function* () {
856 mockedRequest
857 .mockReturnValueOnce(
858 Effect.succeed(response(pullRequestJson({ reviewers: [octocat, hubot] }))),
859 )
860 .mockReturnValueOnce(Effect.succeed(response("{}")));
861 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
862​
863 yield* api.setReviewerRequest({
864 repository: "acme/web",
865 number: 7,
866 reviewers: [{ id: "{hubot}" }],
867 requested: false,
868 });
869​
870 // @effect-diagnostics-next-line preferSchemaOverJson:off
871 expect(JSON.parse(callAt(1).body ?? "")).toEqual({ reviewers: [{ uuid: "{octocat}" }] });
872 }),
873 );
874});