Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 0 additions & 24 deletions tests/blog-share-image.test.ts

This file was deleted.

44 changes: 3 additions & 41 deletions tests/codex-stats.test.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,6 @@
import { describe, expect, test } from "bun:test";

import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";

import {
activityThresholds,
CodexActivity,
} from "../src/components/codex-activity.tsx";
import { CodexTotals, CodexUsageLimit } from "../src/components/codex-stats";
import type { CodexAccountSnapshot } from "../src/lib/codex/stats";
import { activityThresholds } from "../src/components/codex-activity.tsx";
import {
buildPublicCodexStats,
createCodexAccountSnapshot,
Expand Down Expand Up @@ -91,7 +83,7 @@ const requireStats = <T>(stats: T | null): T => {
};

describe("public Codex statistics", () => {
test("daily totals use provider dates and reset timestamps display in IST", () => {
test("daily totals use provider dates across IST and UTC midnight", () => {
const snapshot = createCodexAccountSnapshot(
profile(120, [{ start_date: "2026-09-28", tokens: 120 }]),
{
Expand Down Expand Up @@ -121,15 +113,6 @@ describe("public Codex statistics", () => {
});
expect(stats.totals.last7Days.value).toBe(120);
expect(stats.totals.todayTokens.value).toBe(expectedToday);
const html = renderToStaticMarkup(createElement(CodexTotals, { stats }));
expect(html).toContain("Last 7 days");
expect(html).toContain(">Today</dt>");
expect(html).not.toContain("UTC");
const limits = renderToStaticMarkup(
createElement(CodexUsageLimit, { stats })
);
expect(limits).toContain("Sep 29, 2026");
expect(limits).not.toContain("UTC");
}
});

Expand All @@ -143,26 +126,6 @@ describe("public Codex statistics", () => {
expect(activityThresholds([10, 10, 10])).toEqual([10, 10, 10]);
});

test("keeps zero-activity calendar cells out of the tab order", () => {
const series = {
partial: false,
values: [
{ day: "2026-01-01", tokens: 0 },
{ day: "2026-01-02", tokens: 1000 },
],
};
const html = renderToStaticMarkup(
createElement(CodexActivity, {
cumulative: series,
daily: series,
weekly: series,
})
);

expect(html).not.toContain(": 0 tokens");
expect(html).toContain("1,000 tokens");
});

test("whitelists upstream data and combines accounts", () => {
const first = createCodexAccountSnapshot(
profile(80, [
Expand Down Expand Up @@ -301,7 +264,6 @@ describe("public Codex statistics", () => {
resetAt: null,
},
]);
expect(JSON.stringify(stats)).not.toContain("Spark");

const partial = requireStats(
buildPublicCodexStats(
Expand Down Expand Up @@ -525,7 +487,7 @@ test("snapshot saves keep profile history when upstream shortens or omits it", a
dailyUsageBuckets: [{ startDate: "2020-01-01", tokens: 10 }],
cumulativeDailyUsageBuckets: [{ startDate: "2020-01-01", tokens: 10 }],
primaryLimit: null,
summary: {} as CodexAccountSnapshot["summary"],
summary: createCodexAccountSnapshot(profile(0, []), usage()).summary,
topInvocations: null,
};
const next = {
Expand Down
205 changes: 205 additions & 0 deletions tests/cron-publication.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
import { afterEach, expect, spyOn, test } from "bun:test";

import * as nextCache from "next/cache";
import * as nextServer from "next/server";

import { POST as syncTokens } from "../src/app/api/cron/codex-stats/route";
import { POST as summarizeWork } from "../src/app/api/cron/github-summary/route";
import { POST as syncWork } from "../src/app/api/cron/github-worker/route";
import * as tokenViews from "../src/lib/codex/public-stats";
import * as tokenSync from "../src/lib/codex/sync";
import * as workViews from "../src/lib/github-activity-feed";
import * as workWorker from "../src/lib/github-activity-worker";
import * as summaryWorker from "../src/lib/github-work-unit-summary-worker";
import { env } from "./helpers";

const secret = "test-cron-secret-with-at-least-32-characters";
const originalSecret = env.CRON_SECRET;

afterEach(() => {
env.CRON_SECRET = originalSecret;
});

const request = (path: string) =>
new Request(`https://example.com/api/cron/${path}`, {
method: "POST",
headers: { authorization: `Bearer ${secret}` },
});

test("cron authentication rejects missing, wrong and unconfigured secrets before doing work", async () => {
const unexpected = new Error("An unauthenticated request reached a worker");
const sync = spyOn(tokenSync, "syncCodexAccounts").mockRejectedValue(
unexpected
);
const worker = spyOn(workWorker, "runGitHubActivityWorker").mockRejectedValue(
unexpected
);
const summary = spyOn(
summaryWorker,
"runGitHubWorkUnitSummaryWorker"
).mockRejectedValue(unexpected);
try {
for (const [configured, authorization] of [
[secret, undefined],
[secret, `Bearer wrong-${secret}`],
[secret, `bearer ${secret}`],
[undefined, `Bearer ${secret}`],
["short", "Bearer short"],
]) {
env.CRON_SECRET = configured;
for (const handler of [syncTokens, syncWork, summarizeWork]) {
const response = await handler(
new Request("https://example.com/api/cron/test", {
method: "POST",
headers: authorization === undefined ? {} : { authorization },
})
);
expect(response.status).toBe(401);
}
}
expect(sync).not.toHaveBeenCalled();
expect(worker).not.toHaveBeenCalled();
expect(summary).not.toHaveBeenCalled();
} finally {
sync.mockRestore();
worker.mockRestore();
summary.mockRestore();
}
});

test("Codex publication warms only after a successful sync changes data", async () => {
env.CRON_SECRET = secret;
const sync = spyOn(tokenSync, "syncCodexAccounts");
const invalidate = spyOn(nextCache, "revalidateTag").mockImplementation(
() => {}
);
const after = spyOn(nextServer, "after").mockImplementation(() => {});
const warm = spyOn(tokenViews, "getPublicCodexStats").mockResolvedValue(null);
try {
sync.mockResolvedValue({ updated: 0 });
expect((await syncTokens(request("codex-stats"))).status).toBe(200);
expect(invalidate).not.toHaveBeenCalled();
expect(after).not.toHaveBeenCalled();

sync.mockRejectedValue(new Error("private upstream details"));
const failure = await syncTokens(request("codex-stats"));
expect(failure.status).toBe(503);
expect(await failure.json()).toEqual({ ok: false, error: "Error" });
expect(invalidate).not.toHaveBeenCalled();
expect(after).not.toHaveBeenCalled();

sync.mockResolvedValue({ updated: 1 });
expect((await syncTokens(request("codex-stats"))).status).toBe(200);
expect(invalidate.mock.calls).toEqual([["public-codex-stats", "max"]]);
expect(after).toHaveBeenCalledTimes(1);
expect(warm).not.toHaveBeenCalled();
const [[warmAfterResponse]] = after.mock.calls;
expect(typeof warmAfterResponse).toBe("function");
if (typeof warmAfterResponse === "function") {
await warmAfterResponse();
}
expect(warm).toHaveBeenCalledTimes(1);
} finally {
sync.mockRestore();
invalidate.mockRestore();
after.mockRestore();
warm.mockRestore();
}
});

test("GitHub rejects invalid requests and warms only a changed public feed", async () => {
env.CRON_SECRET = secret;
const stage = {
claimed: 0,
completed: 0,
deferred: 0,
failed: 0,
unavailable: 0,
};
const result: workWorker.GitHubActivityWorkerResult = {
commits: stage,
deadlineReached: false,
observations: stage,
projection: null,
pullRequests: stage,
pullRequestDiscovery: stage,
pullRequestSignals: stage,
refs: stage,
};
const worker = spyOn(workWorker, "runGitHubActivityWorker").mockResolvedValue(
result
);
const invalidate = spyOn(nextCache, "revalidateTag").mockImplementation(
() => {}
);
const after = spyOn(nextServer, "after").mockImplementation(() => {});
const warm = spyOn(workViews, "getInitialGitHubActivity").mockResolvedValue(
null
);
try {
expect((await syncWork(request("github-worker?batch=bad"))).status).toBe(
400
);
expect(worker).not.toHaveBeenCalled();
worker.mockRejectedValueOnce(new Error("private upstream details"));
const failure = await syncWork(request("github-worker"));
expect(failure.status).toBe(503);
expect(await failure.json()).toEqual({ ok: false, error: "Error" });
expect(invalidate).not.toHaveBeenCalled();
expect(after).not.toHaveBeenCalled();
expect((await syncWork(request("github-worker"))).status).toBe(200);
expect(invalidate).not.toHaveBeenCalled();
expect(after).not.toHaveBeenCalled();

result.projection = {
changed: true,
deletedUnits: 0,
exclusionReasonCounts: {
merged_pr_landing: 0,
canonical_branch_unknown: 0,
head_generation_incomplete: 0,
no_current_owner: 0,
pull_request_coverage_incomplete: 0,
repository_visibility_unknown: 0,
},
feedRevisionChanged: false,
insertedUnits: 0,
orderingRevisionChanged: true,
summaryAttemptsQueued: 0,
summaryEvaluationsPending: 0,
summaryEvaluationsSettled: 0,
summaryInputsFailed: 0,
summaryInputsSet: 0,
updatedUnits: 1,
};
expect((await syncWork(request("github-worker"))).status).toBe(200);
expect(invalidate).not.toHaveBeenCalled();
expect(after).not.toHaveBeenCalled();

result.projection.feedRevisionChanged = true;
expect((await syncWork(request("github-worker?batch=2"))).status).toBe(200);
expect(worker).toHaveBeenLastCalledWith(
expect.objectContaining({
includeProjection: true,
commitLimit: 2,
refLimit: 1,
})
);
expect(invalidate.mock.calls).toEqual([
["public-github-activity", { expire: 0 }],
]);
expect(after).toHaveBeenCalledTimes(1);
expect(warm).not.toHaveBeenCalled();
const [[warmAfterResponse]] = after.mock.calls;
expect(typeof warmAfterResponse).toBe("function");
if (typeof warmAfterResponse === "function") {
await warmAfterResponse();
}
expect(warm).toHaveBeenCalledTimes(1);
} finally {
worker.mockRestore();
invalidate.mockRestore();
after.mockRestore();
warm.mockRestore();
}
});
18 changes: 0 additions & 18 deletions tests/favicons.test.ts

This file was deleted.

Loading
Loading