feat: make retry policy error-aware and expand unit coverage

- retry: retry only 5xx/429/transport errors; fail fast on 4xx
- checks/diff/r2/cacheStore: add direct unit tests (D-08, D-10 area)
- cacheStore: validate pullNumber in history object keys
- r2: export normalizeEndpoint for testability
This commit is contained in:
wdawdwa committed 2026-08-22 16:09:16 +08:00
1 parent b47302e2ff
commit 3f793d746e
9 files changed
+363 -12

No files matched your search

+48
View File
@@ -0,0 +1,48 @@
import assert from "node:assert/strict";
import test from "node:test";
import { collectValidNewLines, toDiffPosition } from "../src/github/diff.js";
function file(patch?: string) {
return { filename: "src/a.ts", patch, status: "modified", additions: 2, deletions: 1 };
}
const samplePatch = [
"@@ -1,3 +1,4 @@",
" context line",
"-removed line",
"+added line one",
"+added line two",
" more context"
].join("\n");
test("collectValidNewLines tracks added lines per file", () => {
const valid = collectValidNewLines([file(samplePatch)]);
assert.equal(valid.has("src/a.ts:2"), true);
assert.equal(valid.has("src/a.ts:3"), true);
assert.equal(valid.has("src/a.ts:1"), false);
assert.equal(valid.has("src/a.ts:4"), false);
});
test("files without patches contribute no valid lines", () => {
const valid = collectValidNewLines([file(undefined)]);
assert.equal(valid.size, 0);
});
test("toDiffPosition maps valid new lines and rejects stale ones", () => {
const valid = collectValidNewLines([file(samplePatch)]);
assert.deepEqual(toDiffPosition(file(), 2, valid), {
path: "src/a.ts",
line: 2,
side: "RIGHT"
});
assert.equal(toDiffPosition(file(), 99, valid), null);
});
test("hunk headers with ranges are parsed correctly", () => {
const valid = collectValidNewLines([
file("@@ -10,5 +20,3 @@\n+first\n+second\n+third")
]);
assert.equal(valid.has("src/a.ts:20"), true);
assert.equal(valid.has("src/a.ts:22"), true);
assert.equal(valid.has("src/a.ts:23"), false);
});
+44
View File
@@ -0,0 +1,44 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
normalizeObjectPrefix,
pullRequestReviewHistoryObjectKey,
pullRequestReviewObjectKey,
repositoryKnowledgeObjectKey
} from "../src/storage/cacheStore.js";
test("object keys are scoped by repository id, pull number, and optional prefix", () => {
assert.equal(
repositoryKnowledgeObjectKey("123"),
"repositories/123/knowledge/repository.md"
);
assert.equal(
pullRequestReviewObjectKey("123", 7),
"repositories/123/pulls/7/latest.json"
);
assert.equal(
pullRequestReviewObjectKey("123", 7, "forum-1"),
"forum-1/repositories/123/pulls/7/latest.json"
);
});
test("history keys pin the reviewed head sha in lowercase hex form", () => {
const sha = "A".repeat(40).toLowerCase();
assert.equal(
pullRequestReviewHistoryObjectKey("123", 9, sha.toUpperCase()),
`repositories/123/pulls/9/reviews/${sha}.json`
);
assert.throws(() => pullRequestReviewHistoryObjectKey("123", 9, "short"), /40-64 hexadecimal/);
assert.throws(
() => pullRequestReviewHistoryObjectKey("123", -1, sha),
/Pull request number must be a positive integer/
);
});
test("normalizeObjectPrefix validates each slash-separated segment", () => {
assert.equal(normalizeObjectPrefix(undefined), "");
assert.equal(normalizeObjectPrefix(""), "");
assert.equal(normalizeObjectPrefix("/a/b/"), "a/b");
assert.throws(() => normalizeObjectPrefix("bad/../segment"), /safe slash-separated/);
assert.throws(() => normalizeObjectPrefix(".hidden"), /safe slash-separated/);
});
+26
View File
@@ -0,0 +1,26 @@
import assert from "node:assert/strict";
import test from "node:test";
import { isR2Configured, normalizeEndpoint } from "../src/storage/r2.js";
test("normalizeEndpoint accepts credential-free https URLs and trims trailing slashes", () => {
assert.equal(
normalizeEndpoint("https://account.r2.cloudflarestorage.com"),
"https://account.r2.cloudflarestorage.com"
);
assert.equal(
normalizeEndpoint("https://account.r2.cloudflarestorage.com/"),
"https://account.r2.cloudflarestorage.com"
);
});
test("normalizeEndpoint rejects non-https, credentialed, or decorated URLs", () => {
assert.throws(() => normalizeEndpoint("http://insecure.example"), /credential-free HTTPS/);
assert.throws(() => normalizeEndpoint("https://user:pass@host"), /credential-free HTTPS/);
assert.throws(() => normalizeEndpoint("https://host/path?query=1"), /credential-free HTTPS/);
assert.throws(() => normalizeEndpoint("not a url"), /valid HTTPS URL/);
});
test("isR2Configured reflects ambient configuration without throwing", () => {
// The test environment has no R2_* env vars set; the helper must not throw.
assert.equal(typeof isR2Configured(), "boolean");
});
+84
View File
@@ -0,0 +1,84 @@
import assert from "node:assert/strict";
import test from "node:test";
import type { Octokit } from "@octokit/rest";
import { requiredChecksAreGreen } from "../src/github/checks.js";
type CheckRun = {
name: string;
status: string;
conclusion?: string | null;
};
function octokitWith(params: {
checkRuns: CheckRun[];
combinedStatus?: { state: string; statuses: unknown[] };
}): Octokit {
return {
rest: {
checks: {
listForRef: async () => ({
data: { check_runs: params.checkRuns }
})
},
repos: {
getCombinedStatusForRef: async () => ({
data: params.combinedStatus ?? { state: "success", statuses: [] }
})
}
}
} as unknown as Octokit;
}
test("all green checks and statuses pass", async () => {
const octokit = octokitWith({
checkRuns: [
{ name: "ci", status: "completed", conclusion: "success" },
{ name: "lint", status: "completed", conclusion: "neutral" },
{ name: "docs", status: "completed", conclusion: "skipped" }
]
});
const result = await requiredChecksAreGreen(octokit, { owner: "a", repo: "b", ref: "sha" });
assert.equal(result.ok, true);
});
test("pending or failed checks block the merge", async () => {
const pending = await requiredChecksAreGreen(
octokitWith({ checkRuns: [{ name: "ci", status: "in_progress" }] }),
{ owner: "a", repo: "b", ref: "sha" }
);
assert.equal(pending.ok, false);
assert.match(pending.reason ?? "", /in_progress\/pending/);
const failed = await requiredChecksAreGreen(
octokitWith({
checkRuns: [{ name: "ci", status: "completed", conclusion: "failure" }]
}),
{ owner: "a", repo: "b", ref: "sha" }
);
assert.equal(failed.ok, false);
assert.match(failed.reason ?? "", /failure/);
});
test("ghbot-owned check runs are ignored", async () => {
for (const ignoredName of ["ghbot review", "bot-review", "acme/ bot-review"]) {
const result = await requiredChecksAreGreen(
octokitWith({
checkRuns: [{ name: ignoredName, status: "completed", conclusion: "action_required" }]
}),
{ owner: "a", repo: "b", ref: "sha" }
);
assert.equal(result.ok, true, `${ignoredName} should be ignored`);
}
});
test("non-success commit statuses block when present", async () => {
const result = await requiredChecksAreGreen(
octokitWith({
checkRuns: [],
combinedStatus: { state: "failure", statuses: [{ state: "failure" }] }
}),
{ owner: "a", repo: "b", ref: "sha" }
);
assert.equal(result.ok, false);
assert.match(result.reason ?? "", /Commit status is failure/);
});
+112
View File
@@ -0,0 +1,112 @@
import assert from "node:assert/strict";
import test from "node:test";
import { isRetryableError, withRetry } from "../src/retry.js";
class HttpLikeError extends Error {
status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
}
}
test("returns immediately when the first attempt succeeds", async () => {
let attempts = 0;
const result = await withRetry(
"probe.first",
async () => {
attempts += 1;
return "ok";
},
{ baseDelayMs: 1 }
);
assert.equal(result, "ok");
assert.equal(attempts, 1);
});
test("retries transient failures and eventually succeeds", async () => {
let attempts = 0;
const result = await withRetry(
"probe.transient",
async () => {
attempts += 1;
if (attempts < 3) {
throw new HttpLikeError(502, "bad gateway");
}
return "done";
},
{ baseDelayMs: 1 }
);
assert.equal(result, "done");
assert.equal(attempts, 3);
});
test("throws the last error after exhausting attempts", async () => {
let attempts = 0;
await assert.rejects(
withRetry(
"probe.exhausted",
async () => {
attempts += 1;
throw new HttpLikeError(503, `boom ${attempts}`);
},
{ maxAttempts: 3, baseDelayMs: 1 }
),
/boom 3$/
);
assert.equal(attempts, 3);
});
test("4xx errors are not retried by default", async () => {
let attempts = 0;
await assert.rejects(
withRetry(
"probe.client-error",
async () => {
attempts += 1;
throw new HttpLikeError(404, "not found");
})
);
assert.equal(attempts, 1);
});
test("429 rate limits are retried by default", async () => {
let attempts = 0;
await assert.rejects(
withRetry(
"probe.rate-limit",
async () => {
attempts += 1;
throw new HttpLikeError(429, "slow down");
},
{ maxAttempts: 2, baseDelayMs: 1 }
)
);
assert.equal(attempts, 2);
});
test("network-shaped failures are retried", async () => {
let attempts = 0;
await assert.rejects(
withRetry(
"probe.network",
async () => {
attempts += 1;
throw Object.assign(new Error("socket hang up"), { code: "ECONNRESET" });
},
{ maxAttempts: 2, baseDelayMs: 1 }
)
);
assert.equal(attempts, 2);
});
test("isRetryableError classifies statuses and codes explicitly", () => {
assert.equal(isRetryableError(new HttpLikeError(500, "oops")), true);
assert.equal(isRetryableError(new HttpLikeError(503, "oops")), true);
assert.equal(isRetryableError(new HttpLikeError(429, "oops")), true);
assert.equal(isRetryableError(new HttpLikeError(404, "nope")), false);
assert.equal(isRetryableError(new HttpLikeError(401, "denied")), false);
assert.equal(isRetryableError(Object.assign(new Error("x"), { code: "ETIMEDOUT" })), true);
assert.equal(isRetryableError(Object.assign(new Error("x"), { code: "EAI_AGAIN" })), true);
assert.equal(isRetryableError(new Error("plain")), false);
});