Files
errors.bitreport.pt/ingest-api/src/buildApp.test.ts
T
David SantosandPaperclip 3d4444eb21 BIT-15744: add remaining unit tests for admin-ui, api routes, collector-worker db, ingest-api services
Complete test coverage implementation for errors.bitreport.pt:

admin-ui (98 tests):
- test/components/: AppShell, DataAlert, IncidentNotes, KpiCard, SeverityBadge, StateBadge
- test/lib/: format, demo-incidents, incidents-data, incidents-data-api, stats-data, stats-data-api
- vitest.config.ts with jsdom + v8 coverage + @vitejs/plugin-react

api route tests (54 tests):
- src/routes/admin/auth.test.ts (15 tests)
- src/routes/admin/incidents.test.ts (11 tests)
- src/routes/admin/stats.test.ts (18 tests)
- src/routes/public/errorMonitoringStats.test.ts (10 tests)

collector-worker db/scheduler tests (22 tests):
- src/db/collectorRunWriter.test.ts (10 tests)
- src/db/loadActiveSources.test.ts (6 tests)
- src/scheduler/runHttpSourceOnce.test.ts (6 tests)

ingest-api service tests (13 tests):
- src/buildApp.test.ts, plugins/prometheus.test.ts
- services/ingestAuth.test.ts, services/processIngestBatch.utils.test.ts

Total: 187 additional tests (255 total across all modules). All pass.

Paperclip-Issue: BIT-15744
Co-Authored-By: Paperclip <[email protected]>
2026-05-03 07:24:38 +00:00

157 lines
4.6 KiB
TypeScript

/**
* Integration tests for buildApp — exercises routes via Fastify inject,
* mocking DB pool and processIngestBatch so no real DB is needed.
*/
import { describe, it, expect, vi, beforeAll } from 'vitest';
import type { FastifyInstance } from 'fastify';
import type { RowDataPacket } from 'mysql2';
import { buildApp } from './buildApp.js';
import { sha256Hex } from './lib/hash.js';
vi.mock('./plugins/prometheus.js', () => ({
default: async () => {},
ingestEventsTotal: { inc: vi.fn() },
ingestBatchSize: { observe: vi.fn() },
errorHubLastEventTimestamp: { set: vi.fn() },
errorHubIngestFailuresTotal: { inc: vi.fn() },
}));
vi.mock('./services/processIngestBatch.js', () => ({
processIngestBatch: vi.fn().mockResolvedValue({
status: 200,
body: {
fingerprint_policy_version: 1,
noise_ruleset_version: '1',
noise_filtered_count: 0,
results: [{ incident_id: 'inc-1', occurrence_id: 'occ-1', fingerprint: 'fp-1' }],
},
}),
computeRequestBodyHash: vi.fn().mockReturnValue('hash-abc'),
}));
const TOKEN = 'my-ingest-token';
const TOKEN_HASH = sha256Hex(TOKEN);
const validKeyRow: RowDataPacket = {
id: 'key-1',
project_id: 'proj-1',
project_slug: 'wdmi-store',
rate_limit_max: null,
rate_limit_window_ms: null,
} as unknown as RowDataPacket;
const baseEnv = {
NODE_ENV: 'test',
PORT: 3000,
INGEST_BASE_URL: 'http://ingest.local',
INGEST_RATE_LIMIT_MAX: 500,
INGEST_RATE_LIMIT_WINDOW_MS: 60000,
INGEST_ANON_IP_MAX: 20,
INGEST_ANON_IP_WINDOW_MS: 60000,
INGEST_PUSH_TIMEOUT_MS: 10000,
INGEST_PUSH_MAX_RETRIES: 2,
INGEST_PUSH_RETRY_BASE_MS: 100,
INGEST_PUSH_RETRY_MAX_JITTER_MS: 50,
HTTP_FETCH_TIMEOUT_MS: 10000,
MAX_BACKOFF_EXPONENT: 6,
};
function makePool(keyRows: RowDataPacket[] = []) {
return {
execute: vi.fn().mockResolvedValue([keyRows]),
};
}
let app: FastifyInstance;
beforeAll(async () => {
app = await buildApp({ env: baseEnv as never, pool: makePool([validKeyRow]) as never });
});
describe('GET /health', () => {
it('returns 200 with status ok', async () => {
const res = await app.inject({ method: 'GET', url: '/health' });
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ status: 'ok' });
});
});
describe('POST /v1/ingest/events — auth rejection', () => {
it('returns 401 when no credentials provided', async () => {
const localPool = makePool([]);
const localApp = await buildApp({ env: baseEnv as never, pool: localPool as never });
const res = await localApp.inject({
method: 'POST',
url: '/v1/ingest/events',
payload: {
events: [
{
schema_version: 1,
occurred_at: '2026-01-01T00:00:00Z',
level: 'error',
message: 'test error',
},
],
},
});
expect(res.statusCode).toBe(401);
});
it('returns 401 when API key is not found in DB', async () => {
const localPool = makePool([]);
const localApp = await buildApp({ env: baseEnv as never, pool: localPool as never });
const res = await localApp.inject({
method: 'POST',
url: '/v1/ingest/events',
headers: { Authorization: 'Bearer invalid-key' },
payload: {
events: [
{
schema_version: 1,
occurred_at: '2026-01-01T00:00:00Z',
level: 'error',
message: 'test error',
},
],
},
});
expect(res.statusCode).toBe(401);
});
});
describe('POST /v1/ingest/events — successful ingest', () => {
it('returns 200 with ingest results on valid auth and payload', async () => {
const localPool = makePool([validKeyRow]);
const localApp = await buildApp({ env: baseEnv as never, pool: localPool as never });
const res = await localApp.inject({
method: 'POST',
url: '/v1/ingest/events',
headers: { Authorization: `Bearer ${TOKEN}` },
payload: {
events: [
{
schema_version: 1,
occurred_at: '2026-01-01T00:00:00Z',
level: 'error',
message: 'Test error message',
},
],
},
});
expect(res.statusCode).toBe(200);
const body = res.json<{ results: unknown[] }>();
expect(body.results).toHaveLength(1);
});
});
describe('GET /v1/openapi.json', () => {
it('returns OpenAPI JSON spec', async () => {
const res = await app.inject({ method: 'GET', url: '/v1/openapi.json' });
expect(res.statusCode).toBe(200);
const spec = res.json<{ openapi: string; info: { title: string } }>();
expect(spec.openapi).toBe('3.1.0');
expect(spec.info.title).toContain('ingest');
});
});