File size: 24,295 Bytes
9580dce | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 | /**
* Tests for supporting Feynman API route handlers:
*
* GET /api/feynman/calibrate
* - returns topics array with prereq enrichment
* - returns suggestions array
* - returns profile summary
* - domain filter passed through to getCalibratedTopics
* - count clamped: min 1, max 10
* - each topic includes prereqs.ready, met, unmet, chain
* - DB errors propagate as 500
*
* GET /api/feynman/review
* - default: returns dueCount + items array
* - summary=1: returns full summary (total, dueCount, dueItems, upcomingItems, retainedItems)
* - items include stageLabel and nextInterval from stageLabel()/intervalLabel()
* - userId param defaults to 1
* - DB errors propagate as 500
*
* POST /api/feynman/curate
* - 400 for invalid JSON body
* - 400 for missing topicId
* - 404 for unknown topicId
* - returns sources, sourceCount, sourceReady, minRequired
* - sourceReady true when sources.length >= MIN_SOURCES
* - sourceReady false when sources.length < MIN_SOURCES
* - grounded=false: no teaching content, no Claude guard
* - grounded=true + no API key: 503 (before curateSources)
* - grounded=true + sufficient sources: generates teaching content
* - grounded=true + insufficient sources: no teaching in response
* - DB errors propagate as 500
*
* POST /api/feynman/verify (and GET /api/feynman/verify)
* - GET: returns health summary without running verification
* - POST: runs verification and returns { verification, health }
* - POST: optional limit param respected (capped at 200)
* - POST: empty body is fine (uses defaults)
* - DB errors propagate as 500
*/
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { NextRequest } from "next/server";
// ---------------------------------------------------------------------------
// Mock dependencies for calibrate
// ---------------------------------------------------------------------------
const mockGetKnowledgeProfile = vi.fn();
const mockGetCalibratedTopics = vi.fn();
const mockCheckPrerequisites = vi.fn();
const mockGetSuggestedPrerequisites = vi.fn();
vi.mock("@/lib/feynman/knowledge-profile", () => ({
getKnowledgeProfile: (...args: unknown[]) => mockGetKnowledgeProfile(...args),
getCalibratedTopics: (...args: unknown[]) => mockGetCalibratedTopics(...args),
}));
vi.mock("@/lib/feynman/prerequisites", () => ({
checkPrerequisites: (...args: unknown[]) => mockCheckPrerequisites(...args),
getSuggestedPrerequisites: (...args: unknown[]) => mockGetSuggestedPrerequisites(...args),
}));
// ---------------------------------------------------------------------------
// Mock dependencies for review
// ---------------------------------------------------------------------------
const mockGetDueReviews = vi.fn();
const mockGetReviewSummary = vi.fn();
vi.mock("@/lib/spaced-repetition", () => ({
getDueReviews: (...args: unknown[]) => mockGetDueReviews(...args),
getReviewSummary: (...args: unknown[]) => mockGetReviewSummary(...args),
stageLabel: (stage: number) => `Stage ${stage}`,
intervalLabel: (stage: number) => `${stage + 1} days`,
}));
// ---------------------------------------------------------------------------
// Mock dependencies for curate
// ---------------------------------------------------------------------------
const mockCurateSources = vi.fn();
const mockGetGroundedTeaching = vi.fn();
vi.mock("@/lib/sources/curate", () => ({
curateSources: (...args: unknown[]) => mockCurateSources(...args),
getGroundedTeaching: (...args: unknown[]) => mockGetGroundedTeaching(...args),
MIN_SOURCES: 2,
}));
// ---------------------------------------------------------------------------
// Mock dependencies for verify
// ---------------------------------------------------------------------------
const mockRunVerification = vi.fn();
const mockGetSourceHealthSummary = vi.fn();
vi.mock("@/lib/sources/verify", () => ({
runVerification: (...args: unknown[]) => mockRunVerification(...args),
getSourceHealthSummary: (...args: unknown[]) => mockGetSourceHealthSummary(...args),
}));
// ---------------------------------------------------------------------------
// Import handlers after mocks
// ---------------------------------------------------------------------------
import { GET as getCalibrateRoute } from "../calibrate/route";
import { GET as getReviewRoute } from "../review/route";
import { POST as postCurateRoute } from "../curate/route";
import { POST as postVerifyRoute, GET as getVerifyRoute } from "../verify/route";
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
const originalEnv = { ...process.env };
function makeGet(path: string, params?: Record<string, string>): NextRequest {
const url = new URL(`http://localhost${path}`);
if (params) {
for (const [k, v] of Object.entries(params)) {
url.searchParams.set(k, v);
}
}
return new NextRequest(url);
}
function makePost(path: string, body?: unknown): NextRequest {
return new NextRequest(`http://localhost${path}`, {
method: "POST",
body: body !== undefined ? JSON.stringify(body) : undefined,
headers: { "Content-Type": "application/json" },
});
}
async function json(res: Response): Promise<unknown> {
return res.json();
}
// ---------------------------------------------------------------------------
// Fixtures
// ---------------------------------------------------------------------------
const baseProfile = {
totalAttempts: 5,
recommendedDifficulty: "intermediate" as const,
domains: new Map([
["Physics", { attempts: 3, avgScore: 0.7, masteredTopics: ["phys-001"] }],
]),
};
const baseTopic = {
id: "phys-002",
topic: "Quantum Entanglement",
domain: "Physics",
difficulty: "intermediate" as const,
};
const basePrereqInfo = {
ready: true,
met: [],
unmet: [],
chain: [],
};
// ---------------------------------------------------------------------------
// Tests — GET /api/feynman/calibrate
// ---------------------------------------------------------------------------
describe("GET /api/feynman/calibrate", () => {
beforeEach(() => {
vi.clearAllMocks();
process.env = { ...originalEnv };
mockGetKnowledgeProfile.mockResolvedValue(baseProfile);
mockGetCalibratedTopics.mockReturnValue([baseTopic]);
mockCheckPrerequisites.mockReturnValue(basePrereqInfo);
mockGetSuggestedPrerequisites.mockReturnValue([]);
});
afterEach(() => {
process.env = originalEnv;
});
it("returns 200 with topics, suggestions, and profile", async () => {
const res = await getCalibrateRoute(makeGet("/api/feynman/calibrate"));
expect(res.status).toBe(200);
const body = await json(res) as Record<string, unknown>;
expect(body).toHaveProperty("topics");
expect(body).toHaveProperty("suggestions");
expect(body).toHaveProperty("profile");
});
it("enriches each topic with prereqs object", async () => {
const res = await getCalibrateRoute(makeGet("/api/feynman/calibrate"));
const body = await json(res) as Record<string, unknown>;
const topics = body.topics as Array<Record<string, unknown>>;
expect(topics).toHaveLength(1);
const topic = topics[0];
expect(topic).toHaveProperty("prereqs");
const prereqs = topic.prereqs as Record<string, unknown>;
expect(prereqs).toHaveProperty("ready");
expect(prereqs).toHaveProperty("met");
expect(prereqs).toHaveProperty("unmet");
expect(prereqs).toHaveProperty("chain");
expect(prereqs.ready).toBe(true);
});
it("passes domain param to getCalibratedTopics", async () => {
await getCalibrateRoute(makeGet("/api/feynman/calibrate", { domain: "Physics" }));
expect(mockGetCalibratedTopics).toHaveBeenCalledWith(
expect.anything(),
"Physics",
expect.any(Number),
);
});
it("passes count param to getCalibratedTopics", async () => {
await getCalibrateRoute(makeGet("/api/feynman/calibrate", { count: "5" }));
const call = mockGetCalibratedTopics.mock.calls[0] as unknown[];
expect(call[2]).toBe(5);
});
it("clamps count to min 1 (negative value)", async () => {
await getCalibrateRoute(makeGet("/api/feynman/calibrate", { count: "-5" }));
const call = mockGetCalibratedTopics.mock.calls[0] as unknown[];
expect(call[2]).toBe(1);
});
it("clamps count to max 10", async () => {
await getCalibrateRoute(makeGet("/api/feynman/calibrate", { count: "99" }));
const call = mockGetCalibratedTopics.mock.calls[0] as unknown[];
expect(call[2]).toBe(10);
});
it("defaults count to 3 when not provided", async () => {
await getCalibrateRoute(makeGet("/api/feynman/calibrate"));
const call = mockGetCalibratedTopics.mock.calls[0] as unknown[];
expect(call[2]).toBe(3);
});
it("includes profile summary with totalAttempts and domains", async () => {
const res = await getCalibrateRoute(makeGet("/api/feynman/calibrate"));
const body = await json(res) as Record<string, unknown>;
const profile = body.profile as Record<string, unknown>;
expect(profile.totalAttempts).toBe(5);
expect(profile.recommendedDifficulty).toBe("intermediate");
expect(profile).toHaveProperty("domains");
});
it("maps mastered topics from profile domains to suggestions", async () => {
mockGetSuggestedPrerequisites.mockReturnValue([
{ id: "phys-001", topic: "Classical Mechanics", domain: "Physics", difficulty: "beginner" },
]);
const res = await getCalibrateRoute(makeGet("/api/feynman/calibrate"));
const body = await json(res) as Record<string, unknown>;
const suggestions = body.suggestions as Array<Record<string, unknown>>;
expect(suggestions).toHaveLength(1);
expect(suggestions[0]).toMatchObject({ id: "phys-001", topic: "Classical Mechanics" });
});
it("propagates errors as 500", async () => {
mockGetKnowledgeProfile.mockRejectedValue(new Error("DB error"));
const res = await getCalibrateRoute(makeGet("/api/feynman/calibrate"));
expect(res.status).toBe(500);
});
});
// ---------------------------------------------------------------------------
// Tests — GET /api/feynman/review
// ---------------------------------------------------------------------------
describe("GET /api/feynman/review", () => {
beforeEach(() => {
vi.clearAllMocks();
mockGetDueReviews.mockResolvedValue([]);
mockGetReviewSummary.mockResolvedValue({
total: 0,
dueCount: 0,
upcomingCount: 0,
retainedCount: 0,
dueItems: [],
upcomingItems: [],
retainedItems: [],
});
});
it("returns dueCount and items array by default", async () => {
mockGetDueReviews.mockResolvedValue([
{
id: 1,
topicId: "phys-002",
topic: "Quantum Entanglement",
domain: "Physics",
difficulty: "intermediate",
stage: 2,
lastScore: 0.8,
totalReviews: 3,
successCount: 2,
},
]);
const res = await getReviewRoute(makeGet("/api/feynman/review"));
expect(res.status).toBe(200);
const body = await json(res) as Record<string, unknown>;
expect(body).toHaveProperty("dueCount");
expect(body).toHaveProperty("items");
expect(body.dueCount).toBe(1);
const items = body.items as Array<Record<string, unknown>>;
expect(items[0]).toMatchObject({
id: 1,
topicId: "phys-002",
topic: "Quantum Entanglement",
domain: "Physics",
difficulty: "intermediate",
stage: 2,
lastScore: 0.8,
totalReviews: 3,
});
expect(items[0]).toHaveProperty("stageLabel");
expect(items[0]).toHaveProperty("nextInterval");
});
it("returns summary when summary=1", async () => {
mockGetReviewSummary.mockResolvedValue({
total: 10,
dueCount: 2,
upcomingCount: 5,
retainedCount: 3,
dueItems: [
{
id: 1,
topicId: "phys-002",
topic: "Quantum Entanglement",
domain: "Physics",
difficulty: "intermediate",
stage: 2,
lastScore: 0.8,
totalReviews: 3,
successCount: 2,
},
],
upcomingItems: [
{
id: 2,
topicId: "phys-001",
topic: "Classical Mechanics",
domain: "Physics",
stage: 3,
nextReviewAt: new Date("2026-03-30T00:00:00Z"),
},
],
retainedItems: [
{
id: 3,
topicId: "cs-001",
topic: "Recursion",
domain: "CS",
stage: 5,
totalReviews: 10,
successCount: 9,
},
],
});
const res = await getReviewRoute(makeGet("/api/feynman/review", { summary: "1" }));
const body = await json(res) as Record<string, unknown>;
expect(body.total).toBe(10);
expect(body.dueCount).toBe(2);
expect(body.upcomingCount).toBe(5);
expect(body.retainedCount).toBe(3);
const dueItems = body.dueItems as Array<Record<string, unknown>>;
expect(dueItems).toHaveLength(1);
expect(dueItems[0]).toHaveProperty("stageLabel");
expect(dueItems[0]).toHaveProperty("nextInterval");
const upcomingItems = body.upcomingItems as Array<Record<string, unknown>>;
expect(upcomingItems[0]).toHaveProperty("nextReviewAt");
expect(upcomingItems[0]).toHaveProperty("stageLabel");
const retainedItems = body.retainedItems as Array<Record<string, unknown>>;
expect(retainedItems[0]).toHaveProperty("stageLabel");
});
it("defaults userId to 1", async () => {
await getReviewRoute(makeGet("/api/feynman/review"));
expect(mockGetDueReviews).toHaveBeenCalledWith(1, expect.any(Date));
});
it("uses userId from query param", async () => {
await getReviewRoute(makeGet("/api/feynman/review", { userId: "42" }));
expect(mockGetDueReviews).toHaveBeenCalledWith(42, expect.any(Date));
});
it("returns empty items when no reviews due", async () => {
mockGetDueReviews.mockResolvedValue([]);
const res = await getReviewRoute(makeGet("/api/feynman/review"));
const body = await json(res) as Record<string, unknown>;
expect(body.dueCount).toBe(0);
expect(body.items).toEqual([]);
});
it("propagates errors as 500", async () => {
mockGetDueReviews.mockRejectedValue(new Error("DB error"));
const res = await getReviewRoute(makeGet("/api/feynman/review"));
expect(res.status).toBe(500);
});
});
// ---------------------------------------------------------------------------
// Tests — POST /api/feynman/curate
// ---------------------------------------------------------------------------
describe("POST /api/feynman/curate", () => {
beforeEach(() => {
vi.clearAllMocks();
process.env = { ...originalEnv, ANTHROPIC_API_KEY: "test-key" };
mockCurateSources.mockResolvedValue([
{ url: "https://en.wikipedia.org/wiki/Quantum_entanglement", title: "Quantum entanglement", excerpt: "...", domain: "physics", license: "CC BY-SA", confidence: 0.9 },
{ url: "https://en.wikipedia.org/wiki/Quantum_mechanics", title: "Quantum mechanics", excerpt: "...", domain: "physics", license: "CC BY-SA", confidence: 0.85 },
]);
mockGetGroundedTeaching.mockResolvedValue(null);
});
afterEach(() => {
process.env = originalEnv;
});
it("returns 400 for invalid JSON body", async () => {
const req = new NextRequest("http://localhost/api/feynman/curate", {
method: "POST",
body: "not-json{{{",
headers: { "Content-Type": "application/json" },
});
const res = await postCurateRoute(req);
expect(res.status).toBe(400);
});
it("returns 400 for missing topicId", async () => {
const res = await postCurateRoute(makePost("/api/feynman/curate", {}));
expect(res.status).toBe(400);
const body = await json(res) as Record<string, unknown>;
expect(body.error).toMatch(/topicId/i);
});
it("returns 404 for unknown topicId", async () => {
const res = await postCurateRoute(makePost("/api/feynman/curate", { topicId: "nonexistent-xyz" }));
expect(res.status).toBe(404);
});
it("returns sources, sourceCount, sourceReady, minRequired for known topic", async () => {
// Use a real topic ID from FEYNMAN_TOPICS
const { FEYNMAN_TOPICS } = await import("@/lib/feynman/topics");
const realTopicId = FEYNMAN_TOPICS[0].id;
const res = await postCurateRoute(makePost("/api/feynman/curate", { topicId: realTopicId }));
expect(res.status).toBe(200);
const body = await json(res) as Record<string, unknown>;
expect(body).toHaveProperty("sources");
expect(body).toHaveProperty("sourceCount");
expect(body).toHaveProperty("sourceReady");
expect(body).toHaveProperty("minRequired");
expect(body.topicId).toBe(realTopicId);
});
it("sourceReady is true when sources.length >= MIN_SOURCES (2)", async () => {
const { FEYNMAN_TOPICS } = await import("@/lib/feynman/topics");
const realTopicId = FEYNMAN_TOPICS[0].id;
mockCurateSources.mockResolvedValue([
{ url: "https://en.wikipedia.org/a", title: "A" },
{ url: "https://en.wikipedia.org/b", title: "B" },
]);
const res = await postCurateRoute(makePost("/api/feynman/curate", { topicId: realTopicId }));
const body = await json(res) as Record<string, unknown>;
expect(body.sourceReady).toBe(true);
expect(body.sourceCount).toBe(2);
});
it("sourceReady is false when sources.length < MIN_SOURCES (2)", async () => {
const { FEYNMAN_TOPICS } = await import("@/lib/feynman/topics");
const realTopicId = FEYNMAN_TOPICS[0].id;
mockCurateSources.mockResolvedValue([
{ url: "https://en.wikipedia.org/a", title: "A" },
]);
const res = await postCurateRoute(makePost("/api/feynman/curate", { topicId: realTopicId }));
const body = await json(res) as Record<string, unknown>;
expect(body.sourceReady).toBe(false);
});
it("does not include teaching content when grounded is false", async () => {
const { FEYNMAN_TOPICS } = await import("@/lib/feynman/topics");
const realTopicId = FEYNMAN_TOPICS[0].id;
const res = await postCurateRoute(makePost("/api/feynman/curate", { topicId: realTopicId, grounded: false }));
const body = await json(res) as Record<string, unknown>;
expect(body.teaching).toBeUndefined();
expect(mockGetGroundedTeaching).not.toHaveBeenCalled();
});
it("returns 503 when grounded=true and no API key", async () => {
delete process.env.ANTHROPIC_API_KEY;
const { FEYNMAN_TOPICS } = await import("@/lib/feynman/topics");
const realTopicId = FEYNMAN_TOPICS[0].id;
mockCurateSources.mockResolvedValue([
{ url: "https://en.wikipedia.org/a", title: "A" },
{ url: "https://en.wikipedia.org/b", title: "B" },
]);
const res = await postCurateRoute(makePost("/api/feynman/curate", { topicId: realTopicId, grounded: true }));
expect(res.status).toBe(503);
expect(mockGetGroundedTeaching).not.toHaveBeenCalled();
});
it("includes teaching content when grounded=true and sources sufficient", async () => {
const { FEYNMAN_TOPICS } = await import("@/lib/feynman/topics");
const realTopicId = FEYNMAN_TOPICS[0].id;
mockCurateSources.mockResolvedValue([
{ url: "https://en.wikipedia.org/a", title: "A" },
{ url: "https://en.wikipedia.org/b", title: "B" },
]);
mockGetGroundedTeaching.mockResolvedValue({ explanation: "Grounded explanation...", sources: [] });
const res = await postCurateRoute(makePost("/api/feynman/curate", { topicId: realTopicId, grounded: true }));
const body = await json(res) as Record<string, unknown>;
expect(body.teaching).toBeDefined();
expect(mockGetGroundedTeaching).toHaveBeenCalledOnce();
});
it("omits teaching content when grounded=true but insufficient sources", async () => {
const { FEYNMAN_TOPICS } = await import("@/lib/feynman/topics");
const realTopicId = FEYNMAN_TOPICS[0].id;
// Only 1 source — below MIN_SOURCES
mockCurateSources.mockResolvedValue([
{ url: "https://en.wikipedia.org/a", title: "A" },
]);
const res = await postCurateRoute(makePost("/api/feynman/curate", { topicId: realTopicId, grounded: true }));
const body = await json(res) as Record<string, unknown>;
expect(body.teaching).toBeUndefined();
expect(mockGetGroundedTeaching).not.toHaveBeenCalled();
});
it("propagates errors as 500", async () => {
const { FEYNMAN_TOPICS } = await import("@/lib/feynman/topics");
const realTopicId = FEYNMAN_TOPICS[0].id;
mockCurateSources.mockRejectedValue(new Error("Network error"));
const res = await postCurateRoute(makePost("/api/feynman/curate", { topicId: realTopicId }));
expect(res.status).toBe(500);
});
});
// ---------------------------------------------------------------------------
// Tests — GET + POST /api/feynman/verify
// ---------------------------------------------------------------------------
describe("GET /api/feynman/verify", () => {
beforeEach(() => {
vi.clearAllMocks();
mockGetSourceHealthSummary.mockResolvedValue({
totalSources: 10,
staleSources: 2,
freshSources: 8,
topicCoverage: 5,
totalCaches: 3,
validCaches: 2,
});
});
it("returns health summary", async () => {
const res = await getVerifyRoute(makeGet("/api/feynman/verify"));
expect(res.status).toBe(200);
const body = await json(res) as Record<string, unknown>;
expect(body).toHaveProperty("health");
expect(mockRunVerification).not.toHaveBeenCalled();
});
it("does not run verification", async () => {
await getVerifyRoute(makeGet("/api/feynman/verify"));
expect(mockRunVerification).not.toHaveBeenCalled();
});
it("propagates errors as 500", async () => {
mockGetSourceHealthSummary.mockRejectedValue(new Error("DB error"));
const res = await getVerifyRoute(makeGet("/api/feynman/verify"));
expect(res.status).toBe(500);
});
});
describe("POST /api/feynman/verify", () => {
beforeEach(() => {
vi.clearAllMocks();
mockRunVerification.mockResolvedValue({
checked: 10,
alive: 8,
dead: 2,
durationMs: 500,
});
mockGetSourceHealthSummary.mockResolvedValue({
totalSources: 8,
staleSources: 0,
freshSources: 8,
topicCoverage: 4,
totalCaches: 3,
validCaches: 3,
});
});
it("returns verification result and health summary", async () => {
const res = await postVerifyRoute(makePost("/api/feynman/verify", {}));
expect(res.status).toBe(200);
const body = await json(res) as Record<string, unknown>;
expect(body).toHaveProperty("verification");
expect(body).toHaveProperty("health");
});
it("verification result includes checked, alive, dead", async () => {
const res = await postVerifyRoute(makePost("/api/feynman/verify", {}));
const body = await json(res) as Record<string, unknown>;
const verification = body.verification as Record<string, unknown>;
expect(verification.checked).toBe(10);
expect(verification.alive).toBe(8);
expect(verification.dead).toBe(2);
});
it("passes limit param to runVerification", async () => {
await postVerifyRoute(makePost("/api/feynman/verify", { limit: 30 }));
expect(mockRunVerification).toHaveBeenCalledWith(30);
});
it("caps limit at 200", async () => {
await postVerifyRoute(makePost("/api/feynman/verify", { limit: 999 }));
expect(mockRunVerification).toHaveBeenCalledWith(200);
});
it("handles empty body gracefully", async () => {
const req = new NextRequest("http://localhost/api/feynman/verify", {
method: "POST",
// no body
});
const res = await postVerifyRoute(req);
expect(res.status).toBe(200);
expect(mockRunVerification).toHaveBeenCalledWith(undefined);
});
it("propagates errors as 500", async () => {
mockRunVerification.mockRejectedValue(new Error("Network error"));
const res = await postVerifyRoute(makePost("/api/feynman/verify", {}));
expect(res.status).toBe(500);
});
});
|