Files
wikideck/tests/mock-wikipedia.mjs
2026-10-19 18:52:49 -04:00

41 lines
2.3 KiB
JavaScript
Executable File

// Deterministic upstream responses for the isolated HTTP integration test only.
let nextPageId = 700_000;
const nativeFetch = globalThis.fetch.bind(globalThis);
const json = (value) => new Response(JSON.stringify(value), {
headers: { 'Content-Type': 'application/json; charset=utf-8' },
});
globalThis.fetch = async (input, init) => {
const url = new URL(input instanceof Request ? input.url : String(input));
if (url.origin === 'https://en.wikipedia.org' && url.pathname === '/w/api.php') {
if (url.searchParams.get('generator') === 'random') {
const pageid = nextPageId++;
return json({ query: { pages: [{ pageid, ns: 0, title: `Test article ${pageid}`,
extract: `A deterministic mock Wikipedia extract for article ${pageid}, long enough to display on a card.`,
lastrevid: pageid + 1, thumbnail: { source: `https://upload.wikimedia.org/wikipedia/commons/${pageid}.jpg` },
categories: [{ title: 'Category:Science' }] }] } });
}
const pageid = Number(url.searchParams.get('pageids'));
if (pageid === 9_999_999_999) {
return json({ query: { pages: [{ pageid, ns: 0, title: 'Missing test page', missing: true }] } });
}
return json({ query: { pages: [{ pageid, ns: 0, title: `Test article ${pageid}`,
lastrevid: pageid + 1, length: 12_345, description: 'A mock article for integration testing.',
categories: [{ ns: 14, title: 'Category:Science' }], langlinks: [{ lang: 'fr', title: 'Article test' }] }] } });
}
if (url.origin === 'https://wikimedia.org' && url.pathname.includes('/metrics/pageviews/')) {
const parts = url.pathname.split('/');
const start = parts.at(-2);
const end = parts.at(-1);
const from = new Date(Date.UTC(Number(start.slice(0, 4)), Number(start.slice(4, 6)) - 1, 1));
const through = new Date(Date.UTC(Number(end.slice(0, 4)), Number(end.slice(4, 6)) - 1, 1));
const items = [];
for (const cursor = from; cursor <= through; cursor.setUTCMonth(cursor.getUTCMonth() + 1)) {
const timestamp = `${cursor.getUTCFullYear()}${String(cursor.getUTCMonth() + 1).padStart(2, '0')}0100`;
items.push({ timestamp, views: 100, project: 'en.wikipedia', access: 'all-access', agent: 'user', granularity: 'monthly' });
}
return json({ items });
}
return nativeFetch(input, init);
};