RotNot / src /lib /sources /__tests__ /verify.test.ts
deploy
Deploy RotNot
9580dce
Raw History Blame Contribute Delete
10.8 kB
import { describe, it, expect, vi, beforeEach } from "vitest";
// Mock prisma
const mockFindMany = vi.fn();
const mockUpdate = vi.fn();
const mockDelete = vi.fn();
const mockDeleteMany = vi.fn();
const mockCount = vi.fn();
const mockGroupBy = vi.fn();
vi.mock("@/lib/db", () => ({
prisma: {
topicSource: {
findMany: (...args: unknown[]) => mockFindMany(...args),
update: (...args: unknown[]) => mockUpdate(...args),
delete: (...args: unknown[]) => mockDelete(...args),
count: (...args: unknown[]) => mockCount(...args),
groupBy: (...args: unknown[]) => mockGroupBy(...args),
},
teachingCache: {
deleteMany: (...args: unknown[]) => mockDeleteMany(...args),
count: (...args: unknown[]) => mockCount(...args),
},
},
}));
// Mock verifyWikipediaUrl (the underlying HEAD check)
const mockVerify = vi.fn();
vi.mock("../wikipedia", () => ({
verifyWikipediaUrl: (...args: unknown[]) => mockVerify(...args),
}));
// Mock curate module for MIN_SOURCES
vi.mock("../curate", () => ({
MIN_SOURCES: 2,
}));
import {
getStaleSources,
verifySourceUrl,
runVerification,
getSourceHealthSummary,
STALE_THRESHOLD_MS,
MAX_VERIFY_BATCH,
} from "../verify";
beforeEach(() => {
vi.clearAllMocks();
});
describe("constants", () => {
it("STALE_THRESHOLD_MS is 7 days", () => {
expect(STALE_THRESHOLD_MS).toBe(7 * 24 * 60 * 60 * 1000);
});
it("MAX_VERIFY_BATCH defaults to 50", () => {
expect(MAX_VERIFY_BATCH).toBe(50);
});
});
describe("getStaleSources", () => {
it("queries sources with null or stale verifiedAt", async () => {
mockFindMany.mockResolvedValueOnce([]);
const result = await getStaleSources();
expect(mockFindMany).toHaveBeenCalledOnce();
const args = mockFindMany.mock.calls[0][0];
expect(args.where.OR).toHaveLength(2);
expect(args.where.OR[0]).toEqual({ verifiedAt: null });
expect(args.where.OR[1].verifiedAt.lt).toBeInstanceOf(Date);
expect(args.take).toBe(MAX_VERIFY_BATCH);
expect(result).toEqual([]);
});
it("respects custom limit", async () => {
mockFindMany.mockResolvedValueOnce([]);
await getStaleSources(10);
const args = mockFindMany.mock.calls[0][0];
expect(args.take).toBe(10);
});
it("orders by verifiedAt ascending (nulls first)", async () => {
mockFindMany.mockResolvedValueOnce([]);
await getStaleSources();
const args = mockFindMany.mock.calls[0][0];
expect(args.orderBy).toEqual([{ verifiedAt: "asc" }]);
});
it("uses stale date threshold correctly", async () => {
const before = Date.now() - STALE_THRESHOLD_MS;
mockFindMany.mockResolvedValueOnce([]);
await getStaleSources();
const staleDate = mockFindMany.mock.calls[0][0].where.OR[1].verifiedAt.lt;
const after = Date.now() - STALE_THRESHOLD_MS;
expect(staleDate.getTime()).toBeGreaterThanOrEqual(before);
expect(staleDate.getTime()).toBeLessThanOrEqual(after);
});
});
describe("verifySourceUrl", () => {
it("delegates to verifyWikipediaUrl", async () => {
mockVerify.mockResolvedValueOnce(true);
const result = await verifySourceUrl("https://en.wikipedia.org/wiki/Test");
expect(mockVerify).toHaveBeenCalledWith("https://en.wikipedia.org/wiki/Test");
expect(result).toBe(true);
});
it("returns false for dead URLs", async () => {
mockVerify.mockResolvedValueOnce(false);
const result = await verifySourceUrl("https://example.com/dead");
expect(result).toBe(false);
});
});
describe("runVerification", () => {
const makeStaleSources = (ids: number[], topicIds: string[]) =>
ids.map((id, i) => ({
id,
topicId: topicIds[i],
url: `https://example.com/${id}`,
title: `Source ${id}`,
excerpt: "excerpt",
domain: "wikipedia",
license: "CC BY-SA 4.0",
confidence: "high",
verifiedAt: null,
createdAt: new Date(),
}));
it("returns zero counts when no stale sources", async () => {
mockFindMany.mockResolvedValueOnce([]);
const result = await runVerification();
expect(result.checked).toBe(0);
expect(result.live).toBe(0);
expect(result.removed).toBe(0);
expect(result.cachesInvalidated).toBe(0);
expect(result.invalidatedTopics).toEqual([]);
expect(result.durationMs).toBeGreaterThanOrEqual(0);
});
it("updates verifiedAt for live sources", async () => {
const sources = makeStaleSources([1, 2], ["topic-a", "topic-b"]);
mockFindMany.mockResolvedValueOnce(sources);
mockVerify.mockResolvedValue(true);
mockUpdate.mockResolvedValue({});
const result = await runVerification();
expect(result.checked).toBe(2);
expect(result.live).toBe(2);
expect(result.removed).toBe(0);
expect(mockUpdate).toHaveBeenCalledTimes(2);
// Check that verifiedAt is updated to a recent date
const updateCall = mockUpdate.mock.calls[0][0];
expect(updateCall.where.id).toBe(1);
expect(updateCall.data.verifiedAt).toBeInstanceOf(Date);
});
it("deletes dead sources and tracks affected topics", async () => {
const sources = makeStaleSources([1, 2], ["topic-a", "topic-a"]);
mockFindMany.mockResolvedValueOnce(sources);
mockVerify.mockResolvedValue(false);
mockDelete.mockResolvedValue({});
// After deletion, remaining count for topic-a
mockCount.mockResolvedValueOnce(0);
// deleteMany for teaching cache
mockDeleteMany.mockResolvedValueOnce({ count: 1 });
const result = await runVerification();
expect(result.checked).toBe(2);
expect(result.live).toBe(0);
expect(result.removed).toBe(2);
expect(mockDelete).toHaveBeenCalledTimes(2);
});
it("invalidates teaching cache when topic drops below threshold", async () => {
const sources = makeStaleSources([1], ["topic-x"]);
mockFindMany.mockResolvedValueOnce(sources);
mockVerify.mockResolvedValueOnce(false);
mockDelete.mockResolvedValue({});
// remaining sources for topic-x: 1 (below MIN_SOURCES = 2)
mockCount.mockResolvedValueOnce(1);
mockDeleteMany.mockResolvedValueOnce({ count: 1 });
const result = await runVerification();
expect(result.cachesInvalidated).toBe(1);
expect(result.invalidatedTopics).toEqual(["topic-x"]);
expect(mockDeleteMany).toHaveBeenCalledWith({
where: { topicId: "topic-x" },
});
});
it("does not invalidate cache when topic stays above threshold", async () => {
const sources = makeStaleSources([1], ["topic-y"]);
mockFindMany.mockResolvedValueOnce(sources);
mockVerify.mockResolvedValueOnce(false);
mockDelete.mockResolvedValue({});
// remaining sources for topic-y: 3 (still above MIN_SOURCES)
mockCount.mockResolvedValueOnce(3);
const result = await runVerification();
expect(result.cachesInvalidated).toBe(0);
expect(result.invalidatedTopics).toEqual([]);
expect(mockDeleteMany).not.toHaveBeenCalled();
});
it("handles mixed live and dead sources", async () => {
const sources = makeStaleSources([1, 2, 3], ["topic-a", "topic-a", "topic-b"]);
mockFindMany.mockResolvedValueOnce(sources);
// Source 1: live, Source 2: dead, Source 3: live
mockVerify
.mockResolvedValueOnce(true)
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(true);
mockUpdate.mockResolvedValue({});
mockDelete.mockResolvedValue({});
// topic-a remaining count after deletion: 2 (still above threshold)
mockCount.mockResolvedValueOnce(2);
const result = await runVerification();
expect(result.checked).toBe(3);
expect(result.live).toBe(2);
expect(result.removed).toBe(1);
expect(result.cachesInvalidated).toBe(0);
expect(mockUpdate).toHaveBeenCalledTimes(2);
expect(mockDelete).toHaveBeenCalledTimes(1);
});
it("respects limit parameter", async () => {
mockFindMany.mockResolvedValueOnce([]);
await runVerification(5);
const args = mockFindMany.mock.calls[0][0];
expect(args.take).toBe(5);
});
it("deduplicates affected topics when multiple sources die for same topic", async () => {
const sources = makeStaleSources([1, 2, 3], ["topic-z", "topic-z", "topic-z"]);
mockFindMany.mockResolvedValueOnce(sources);
mockVerify.mockResolvedValue(false);
mockDelete.mockResolvedValue({});
// remaining count = 0
mockCount.mockResolvedValueOnce(0);
mockDeleteMany.mockResolvedValueOnce({ count: 1 });
const result = await runVerification();
expect(result.removed).toBe(3);
// Should only check/invalidate once despite 3 deleted sources
expect(mockCount).toHaveBeenCalledTimes(1);
expect(result.cachesInvalidated).toBe(1);
});
it("tracks durationMs", async () => {
mockFindMany.mockResolvedValueOnce([]);
const result = await runVerification();
expect(typeof result.durationMs).toBe("number");
expect(result.durationMs).toBeGreaterThanOrEqual(0);
});
});
describe("getSourceHealthSummary", () => {
it("returns comprehensive health metrics", async () => {
// total sources, stale sources, never verified, total caches
mockCount
.mockResolvedValueOnce(100) // totalSources
.mockResolvedValueOnce(10) // stale (older than threshold)
.mockResolvedValueOnce(5) // never verified
.mockResolvedValueOnce(20); // total caches
// groupBy for topics with sources
mockGroupBy
.mockResolvedValueOnce([
{ topicId: "a" },
{ topicId: "b" },
{ topicId: "c" },
])
// groupBy for topic source counts
.mockResolvedValueOnce([
{ topicId: "a", _count: { id: 3 } },
{ topicId: "b", _count: { id: 1 } }, // below threshold
{ topicId: "c", _count: { id: 2 } },
]);
const summary = await getSourceHealthSummary();
expect(summary.totalSources).toBe(100);
expect(summary.staleSources).toBe(15); // 10 stale + 5 never verified
expect(summary.neverVerified).toBe(5);
expect(summary.freshSources).toBe(85); // 100 - 10 - 5
expect(summary.totalCaches).toBe(20);
expect(summary.topicsWithSources).toBe(3);
expect(summary.topicsAboveThreshold).toBe(2); // a (3) and c (2), not b (1)
expect(summary.minSourcesRequired).toBe(2);
expect(summary.staleThresholdDays).toBe(7);
});
it("handles empty database", async () => {
mockCount
.mockResolvedValueOnce(0)
.mockResolvedValueOnce(0)
.mockResolvedValueOnce(0)
.mockResolvedValueOnce(0);
mockGroupBy
.mockResolvedValueOnce([])
.mockResolvedValueOnce([]);
const summary = await getSourceHealthSummary();
expect(summary.totalSources).toBe(0);
expect(summary.staleSources).toBe(0);
expect(summary.freshSources).toBe(0);
expect(summary.topicsWithSources).toBe(0);
expect(summary.topicsAboveThreshold).toBe(0);
});
});