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

BitbucketPullRequestApi.test.ts

521 lines17.5 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 "./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​
20function response(body: string) {
21 return { body, truncated: false };
23​
24function page(count: number, firstNumber: number, next?: string): string {
25 return JSON.stringify({
26 pagelen: 50,
27 size: count,
28 values: Array.from({ length: count }, (_, index) => ({
29 id: firstNumber + index,
30 title: `Pull request ${firstNumber + index}`,
31 state: "OPEN",
32 created_on: "2026-06-16T05:04:32+00:00",
33 updated_on: "2026-06-16T05:04:33+00:00",
34 source: { branch: { name: "feat/page" } },
35 destination: { branch: { name: "master" } },
36 links: { html: { href: `https://bitbucket.org/acme/web/pull-requests/${firstNumber}` } },
37 })),
38 ...(next === undefined ? {} : { next }),
39 });
41​
42function valuePage(values: ReadonlyArray<unknown>, next?: string): string {
43 return JSON.stringify({ values, ...(next === undefined ? {} : { next }) });
45​
46const bilal = { uuid: "{bilal}", nickname: "bilal" };
47const octocat = { uuid: "{octocat}", nickname: "octocat" };
48const hubot = { uuid: "{hubot}", nickname: "hubot" };
49​
50function pullRequestJson(overrides: Record<string, unknown>): string {
51 return JSON.stringify({
52 id: 7,
53 title: "Pull request 7",
54 state: "OPEN",
55 author: bilal,
56 created_on: "2026-06-16T05:04:32+00:00",
57 updated_on: "2026-06-16T05:04:33+00:00",
58 source: { branch: { name: "feat/page" } },
59 destination: { branch: { name: "master" } },
60 links: { html: { href: "https://bitbucket.org/acme/web/pull-requests/7" } },
61 ...overrides,
62 });
64​
65function callAt(index: number) {
66 const call = mockedRequest.mock.calls[index];
67 assert.isDefined(call);
68 return call[0];
70​
71function filterOfCall(index: number): string | null {
72 const url = callAt(index).url;
73 return new URLSearchParams(url.slice(url.indexOf("?") + 1)).get("q");
75​
76afterEach(() => {
77 mockedRequest.mockReset();
78});
79​
80layer("BitbucketPullRequestApi.layer", (it) => {
81 it.effect("follows the cursor Bitbucket sends rather than counting offsets", () =>
82 Effect.gen(function* () {
83 const next = "https://api.bitbucket.org/2.0/repositories/acme/web/pullrequests?page=2";
84 mockedRequest
85 .mockReturnValueOnce(Effect.succeed(response(page(50, 1, next))))
86 .mockReturnValueOnce(Effect.succeed(response(page(50, 51))));
87 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
88​
89 const batch = yield* api.listPullRequests({
90 repository: "acme/web",
91 state: "open",
92 limit: 100,
93 });
94​
95 assert.strictEqual(batch.items.length, 100);
96 assert.isFalse(batch.truncated);
97 assert.strictEqual(callAt(1).url, next);
98 }),
99 );
100​
101 it.effect("counts the rows it walked past as more to come", () =>
102 Effect.gen(function* () {
103 // Bitbucket pages in fifties whatever was asked for, so a request for ninety-nine reads a
104 // hundred and drops one.
105 const next = "https://api.bitbucket.org/2.0/repositories/acme/web/pullrequests?page=2";
106 mockedRequest
107 .mockReturnValueOnce(Effect.succeed(response(page(50, 1, next))))
108 .mockReturnValueOnce(Effect.succeed(response(page(50, 51))));
109 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
110​
111 const batch = yield* api.listPullRequests({
112 repository: "acme/web",
113 state: "open",
114 limit: 99,
115 });
116​
117 assert.strictEqual(batch.items.length, 99);
118 assert.isTrue(batch.truncated);
119 }),
120 );
121​
122 it.effect("escapes a quote and a backslash, so a search cannot reshape the filter", () =>
123 Effect.gen(function* () {
124 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
125 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
126​
127 yield* api.listPullRequests({
128 repository: "acme/web",
129 state: "open",
130 limit: 50,
131 query: String.raw`a\" OR state = "MERGED"`,
132 });
133​
134 const literal = String.raw`a\\\" OR state = \"MERGED\"`;
135 expect(filterOfCall(0)).toBe(`(title ~ "${literal}" OR description ~ "${literal}")`);
136 }),
137 );
138​
139 it.effect("narrows by the reader's words and by where it left off at once", () =>
140 Effect.gen(function* () {
141 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
142 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
143​
144 yield* api.listPullRequests({
145 repository: "acme/web",
146 state: "open",
147 limit: 50,
148 query: "page",
149 cursor: { updatedBefore: "2026-07-02T00:00:00+00:00", delivered: 50 },
150 });
151​
152 // Bitbucket takes one `q`, so the two narrowings are joined rather than one replacing the
153 // other — and the search keeps its brackets, which is what keeps the AND out of its OR.
154 expect(filterOfCall(0)).toBe(
155 '(title ~ "page" OR description ~ "page") AND updated_on <= 2026-07-02T00:00:00+00:00',
156 );
157 }),
158 );
159​
160 it.effect("refuses a repository that is not workspace and slug", () =>
161 Effect.gen(function* () {
162 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
163​
164 const error = yield* Effect.flip(
165 api.listPullRequests({ repository: "acme/team/web", state: "open", limit: 50 }),
166 );
167​
168 assert.strictEqual(error._tag, "BitbucketRepositoryUnsupportedError");
169 assert.strictEqual(mockedRequest.mock.calls.length, 0);
170 }),
171 );
172​
173 it.effect("refuses a commit that is not a sha rather than reading it into a URL", () =>
174 Effect.gen(function* () {
175 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
176​
177 const error = yield* Effect.flip(
178 api.getPullRequestDiff({
179 repository: "acme/web",
180 number: 7,
181 commit: "../../acme/other/diff/deadbeef",
182 }),
183 );
184​
185 assert.strictEqual(error._tag, "BitbucketDiffCommitError");
186 assert.strictEqual(mockedRequest.mock.calls.length, 0);
187 }),
188 );
189​
190 it.effect("reads every file version the patch states, not only the paths asked about", () =>
191 Effect.gen(function* () {
192 mockedRequest.mockReturnValueOnce(
193 Effect.succeed(
194 response(
195 [
196 "diff --git a/a.ts b/a.ts",
197 "index 1111111..2222222 100644",
198 "--- a/a.ts",
199 "+++ b/a.ts",
200 "@@ -1 +1 @@",
201 "-a",
202 "+b",
203 "diff --git a/b.ts b/b.ts",
204 "index 3333333..4444444 100644",
205 "--- a/b.ts",
206 "+++ b/b.ts",
207 "@@ -1 +1 @@",
208 "-c",
209 "+d",
210 "",
211 ].join("\n"),
212 ),
213 ),
214 );
215 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
216​
217 const revisions = yield* api.getFileRevisions({
218 repository: "acme/web",
219 number: 71,
220 paths: ["a.ts", "missing.ts"],
221 });
222​
223 assert.deepStrictEqual(
224 [...revisions.revisions],
225 [
226 ["a.ts", "2222222"],
227 ["b.ts", "4444444"],
228 ["missing.ts", ""],
229 ],
230 );
231 assert.strictEqual(revisions.complete, true);
232 expect(callAt(0)).toMatchObject({ url: "/repositories/acme/web/pullrequests/71/diff" });
233 }),
234 );
235​
236 it.effect("says nothing about the files past the end of a patch it could not read whole", () =>
237 Effect.gen(function* () {
238 mockedRequest.mockReturnValueOnce(
239 Effect.succeed({
240 body: "diff --git a/a.ts b/a.ts\nindex 1111111..2222222 100644\n@@ -1 +1 @@\n",
241 truncated: true,
242 }),
243 );
244 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
245​
246 const revisions = yield* api.getFileRevisions({
247 repository: "acme/web",
248 number: 72,
249 paths: ["a.ts", "past-the-cut.ts"],
250 });
251​
252 assert.deepStrictEqual([...revisions.revisions], [["a.ts", "2222222"]]);
253 assert.strictEqual(revisions.complete, false);
254 }),
255 );
256​
257 it.effect("returns the complete commit timeline oldest first across pages", () =>
258 Effect.gen(function* () {
259 const next = "https://api.bitbucket.org/2.0/commits?page=2";
260 mockedRequest
261 .mockReturnValueOnce(
262 Effect.succeed(
263 response(
264 valuePage(
265 [
266 { hash: "ddd", message: "fourth", date: "2026-07-04T00:00:00Z" },
267 { hash: "ccc", message: "third", date: "2026-07-03T00:00:00Z" },
268 ],
269 next,
270 ),
271 ),
272 ),
273 )
274 .mockReturnValueOnce(
275 Effect.succeed(
276 response(
277 valuePage([
278 { hash: "bbb", message: "second", date: "2026-07-02T00:00:00Z" },
279 { hash: "aaa", message: "first", date: "2026-07-01T00:00:00Z" },
280 ]),
281 ),
282 ),
283 );
284 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
285​
286 const commits = yield* api.listCommits({ repository: "acme/web", number: 7 });
287​
288 expect(commits.map((commit) => commit.oid)).toEqual(["aaa", "bbb", "ccc", "ddd"]);
289 expect(callAt(1).url).toBe(next);
290 }),
291 );
292​
293 it.effect("posts a comment as a JSON document, so the body stays text", () =>
294 Effect.gen(function* () {
295 mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
296 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
297​
298 yield* api.comment({ repository: "acme/web", number: 7, body: "true" });
299​
300 expect(callAt(0)).toMatchObject({
301 method: "POST",
302 url: "/repositories/acme/web/pullrequests/7/comments",
303 body: '{"content":{"raw":"true"}}',
304 });
305 }),
306 );
307​
308 it.effect("asks for the time a pull request closed, which Bitbucket leaves out by default", () =>
309 Effect.gen(function* () {
310 mockedRequest.mockReturnValueOnce(
311 Effect.succeed(
312 response(
313 pullRequestJson({ state: "MERGED", closed_on: "2025-06-16T23:40:46.222238+00:00" }),
314 ),
315 ),
316 );
317 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
318​
319 const pullRequest = yield* api.getPullRequest({ repository: "acme/web", number: 7 });
320​
321 expect(callAt(0).url).toBe("/repositories/acme/web/pullrequests/7?fields=%2Bclosed_on");
322 assert.strictEqual(pullRequest.closedAt, "2025-06-16T23:40:46.222Z");
323 }),
324 );
325​
326 it.effect("stops the comment walk at its bound and says the conversation was cut short", () =>
327 Effect.gen(function* () {
328 mockedRequest.mockReturnValue(
329 Effect.succeed(
330 response(
331 JSON.stringify({
332 next: "https://api.bitbucket.org/2.0/comments?page=2",
333 values: [
334 {
335 id: 10,
336 content: { raw: "again" },
337 created_on: "2026-06-16T05:04:32+00:00",
338 },
339 ],
340 }),
341 ),
342 ),
343 );
344 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
345​
346 const { truncated } = yield* api.listComments({ repository: "acme/web", number: 7 });
347​
348 assert.strictEqual(mockedRequest.mock.calls.length, 10);
349 assert.isTrue(truncated);
350 }),
351 );
352​
353 it.effect("reassembles a thread from the flat comment list, replies included", () =>
354 Effect.gen(function* () {
355 mockedRequest.mockReturnValueOnce(
356 Effect.succeed(
357 response(
358 JSON.stringify({
359 values: [
360 {
361 id: 10,
362 content: { raw: "rename this" },
363 user: { nickname: "bilal" },
364 created_on: "2026-06-16T05:04:32+00:00",
365 inline: { path: "src/a.ts", to: 12, from: null },
366 resolution: { type: "pullrequest_comment_resolution" },
367 },
368 {
369 id: 11,
370 content: { raw: "done" },
371 user: { nickname: "julius" },
372 created_on: "2026-06-16T06:04:32+00:00",
373 parent: { id: 10 },
374 },
375 {
376 id: 12,
377 content: { raw: "thanks" },
378 user: { nickname: "bilal" },
379 created_on: "2026-06-16T07:04:32+00:00",
380 parent: { id: 11 },
381 },
382 {
383 id: 13,
384 content: { raw: "ship it" },
385 user: { nickname: "bilal" },
386 created_on: "2026-06-16T08:04:32+00:00",
387 },
388 ],
389 }),
390 ),
391 ),
392 );
393 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
394​
395 const { threads } = yield* api.listComments({ repository: "acme/web", number: 7 });
396​
397 assert.strictEqual(threads.length, 1);
398 expect(threads[0]).toMatchObject({
399 id: "10",
400 path: "src/a.ts",
401 line: 12,
402 side: "right",
403 isResolved: true,
404 });
405 expect(threads[0]?.comments.map((comment) => comment.id)).toEqual(["10", "11", "12"]);
406 }),
407 );
408​
409 it.effect("asks for the credentials' permission on this repository, and nobody else's", () =>
410 Effect.gen(function* () {
411 mockedRequest.mockReturnValue(
412 Effect.succeed(
413 response(
414 JSON.stringify({ values: [{ type: "repository_permission", permission: "read" }] }),
415 ),
416 ),
417 );
418 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
419​
420 assert.isFalse(yield* api.getRepositoryPermission({ repository: "acme/web" }));
421​
422 expect(new URL(callAt(0).url, "https://api.bitbucket.org").pathname).toBe(
423 "/user/workspaces/acme/permissions/repositories",
424 );
425 assert.strictEqual(filterOfCall(0), 'repository.full_name="acme/web"');
426 }),
427 );
428​
429 it.effect("escapes a repository name before it goes inside a filter literal", () =>
430 Effect.gen(function* () {
431 mockedRequest.mockReturnValue(Effect.succeed(response(JSON.stringify({ values: [] }))));
432 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
433​
434 yield* api.getRepositoryPermission({ repository: 'acme/we"b' });
435​
436 assert.strictEqual(filterOfCall(0), 'repository.full_name="acme/we\\"b"');
437 }),
438 );
439​
440 const permissionFailure = (status: number) =>
441 Effect.fail(
442 new BitbucketApi.BitbucketResponseError({
443 operation: "request",
444 status,
445 responseBodyLength: 0,
446 }),
447 );
448​
449 it.effect.each([403, 404, 410])(
450 "reads HTTP %s from the permissions endpoint as an unknown permission",
451 (status) =>
452 Effect.gen(function* () {
453 mockedRequest.mockReturnValue(permissionFailure(status));
454 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
455​
456 assert.isTrue(yield* api.getRepositoryPermission({ repository: "acme/web" }));
457 }),
458 );
459​
460 it.effect.each([401, 500])("still fails the permission read on HTTP %s", (status) =>
461 Effect.gen(function* () {
462 mockedRequest.mockReturnValue(permissionFailure(status));
463 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
464​
465 const error = yield* Effect.flip(api.getRepositoryPermission({ repository: "acme/web" }));
466 assert.strictEqual(error._tag, "BitbucketResponseError");
467 if (error._tag === "BitbucketResponseError") {
468 assert.strictEqual(error.status, status);
469 }
470 }),
471 );
472​
473 it.effect("reads the workspace's people and marks whoever is already a reviewer", () =>
474 Effect.gen(function* () {
475 mockedRequest
476 .mockReturnValueOnce(Effect.succeed(response(pullRequestJson({ reviewers: [octocat] }))))
477 .mockReturnValueOnce(
478 Effect.succeed(
479 response(
480 JSON.stringify({ values: [{ user: bilal }, { user: octocat }, { user: hubot }] }),
481 ),
482 ),
483 );
484 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
485​
486 const list = yield* api.listReviewerCandidates({ repository: "acme/web", number: 7 });
487​
488 expect(callAt(1).url).toBe("/workspaces/acme/members?pagelen=50");
489 expect(list.candidates.map((candidate) => [candidate.id, candidate.isRequested])).toEqual([
490 ["{octocat}", true],
491 ["{hubot}", false],
492 ]);
493 assert.isFalse(list.truncated);
494 }),
495 );
496​
497 it.effect("writes the reviewer set back with the one being asked added to it", () =>
498 Effect.gen(function* () {
499 mockedRequest
500 .mockReturnValueOnce(Effect.succeed(response(pullRequestJson({ reviewers: [octocat] }))))
501 .mockReturnValueOnce(Effect.succeed(response("{}")));
502 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
503​
504 yield* api.setReviewerRequest({
505 repository: "acme/web",
506 number: 7,
507 reviewers: [{ id: "{hubot}" }],
508 requested: true,
509 });
510​
511 // Bitbucket writes `reviewers` whole, so the one already on the pull request travels with
512 // the new one or the request would take them off it.
513 const call = callAt(1);
514 expect(call.method).toBe("PUT");
515 expect(call.url).toBe("/repositories/acme/web/pullrequests/7");
516 expect(JSON.parse(call.body ?? "")).toEqual({
517 reviewers: [{ uuid: "{octocat}" }, { uuid: "{hubot}" }],
518 });
519 }),
520 );
521});