62 lines
2.2 KiB
JavaScript
62 lines
2.2 KiB
JavaScript
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import { safeFetch, safeFetchText, getFetchMetrics, inferFetchSource } from '../apis/utils/fetch.mjs';
|
|
|
|
test('safeFetch reports HTML as degraded JSON response', async () => {
|
|
const originalFetch = globalThis.fetch;
|
|
globalThis.fetch = async () => ({
|
|
ok: true,
|
|
status: 200,
|
|
headers: { get: () => 'text/html' },
|
|
text: async () => '<html>not json</html>',
|
|
});
|
|
try {
|
|
const data = await safeFetch('https://example.test/json', { retries: 0, source: 'unit' });
|
|
assert.match(data.error, /Expected JSON/);
|
|
assert.ok(getFetchMetrics().bySource.unit.requests >= 1);
|
|
} finally {
|
|
globalThis.fetch = originalFetch;
|
|
}
|
|
});
|
|
|
|
test('safeFetchText returns text and byte count', async () => {
|
|
const originalFetch = globalThis.fetch;
|
|
globalThis.fetch = async () => ({
|
|
ok: true,
|
|
status: 200,
|
|
text: async () => 'hello',
|
|
});
|
|
try {
|
|
const data = await safeFetchText('https://example.test/rss', { retries: 0, source: 'rss-unit' });
|
|
assert.equal(data.text, 'hello');
|
|
assert.equal(data.bytes, 5);
|
|
} finally {
|
|
globalThis.fetch = originalFetch;
|
|
}
|
|
});
|
|
|
|
test('safeFetch attributes unlabelled requests to a stable provider source', async () => {
|
|
const originalFetch = globalThis.fetch;
|
|
globalThis.fetch = async () => ({
|
|
ok: true,
|
|
status: 200,
|
|
headers: { get: () => 'application/json' },
|
|
text: async () => '{"observations":[]}',
|
|
});
|
|
try {
|
|
const data = await safeFetch('https://api.fred.stlouisfed.org/fred/series/observations?series_id=VIXCLS', { retries: 0 });
|
|
assert.deepEqual(data, { observations: [] });
|
|
const bucket = getFetchMetrics().bySource.FRED;
|
|
assert.ok(bucket.requests >= 1);
|
|
assert.equal(bucket.lastStatus, 200);
|
|
} finally {
|
|
globalThis.fetch = originalFetch;
|
|
}
|
|
});
|
|
|
|
test('inferFetchSource returns provider names and host fallback', () => {
|
|
assert.equal(inferFetchSource('https://api.bls.gov/publicAPI/v2/timeseries/data/CPI'), 'BLS');
|
|
assert.equal(inferFetchSource('https://query1.finance.yahoo.com/v8/finance/chart/%5EGSPC'), 'YahooFinance');
|
|
assert.equal(inferFetchSource('https://unknown.example.test/path'), 'unknown.example.test');
|
|
});
|