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]>
This commit is contained in:
David SantosandPaperclip committed 2026-05-03 07:24:38 +00:00
1 parent 989a92ba07
commit 3d4444eb21
33 files changed
+6374 -24

No files matched your search

+257
View File
@@ -0,0 +1,257 @@
/**
* Tests for admin auth routes.
* Exercises login, refresh, logout, and /me without a live database.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import Fastify, { type FastifyInstance } from 'fastify';
import cookie from '@fastify/cookie';
import jwt from '@fastify/jwt';
import type { RowDataPacket } from 'mysql2';
import adminAuthRoutes from './auth.js';
vi.mock('bcrypt', () => ({
default: {
compare: vi.fn().mockResolvedValue(false),
hash: vi.fn(),
},
}));
vi.mock('../../plugins/audit.js', () => ({
auditLog: vi.fn().mockResolvedValue(undefined),
}));
import bcrypt from 'bcrypt';
const mockBcrypt = vi.mocked(bcrypt);
function makePool(executeFn?: (...args: unknown[]) => Promise<unknown>) {
return {
execute: executeFn ?? vi.fn().mockResolvedValue([[] as RowDataPacket[]]),
getConnection: vi.fn(),
};
}
async function buildApp(pool?: ReturnType<typeof makePool>): Promise<FastifyInstance> {
const app = Fastify({ logger: false });
await app.register(cookie, { secret: 'test-cookie-secret' });
await app.register(jwt, {
secret: 'test-jwt-secret',
cookie: { cookieName: '__Host-access', signed: false },
});
const p = pool ?? makePool();
app.decorate('db', p as unknown as FastifyInstance['db']);
app.decorate('rateLimits', {
login: { max: 10, timeWindow: 300_000 },
ingest: { max: 1000, timeWindow: 60_000 },
global: { max: 500, timeWindow: 60_000 },
mutation: { max: 100, timeWindow: 60_000 },
});
app.decorate('authenticate', async function (req: Parameters<FastifyInstance['authenticate']>[0]) {
(req as { auth: unknown }).auth = { user_id: 'u1', email: '[email protected]', role: 'admin' };
});
await app.register(adminAuthRoutes);
return app;
}
describe('POST /admin/auth/login', () => {
beforeEach(() => {
vi.mocked(mockBcrypt.compare).mockResolvedValue(false as never);
});
it('returns 400 for missing email field', async () => {
const app = await buildApp();
const res = await app.inject({
method: 'POST',
url: '/admin/auth/login',
payload: { password: 'secret' },
});
expect(res.statusCode).toBe(400);
});
it('returns 400 for invalid email format', async () => {
const app = await buildApp();
const res = await app.inject({
method: 'POST',
url: '/admin/auth/login',
payload: { email: 'not-an-email', password: 'secret' },
});
expect(res.statusCode).toBe(400);
});
it('returns 401 when user not found', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({
method: 'POST',
url: '/admin/auth/login',
payload: { email: '[email protected]', password: 'pass' },
});
expect(res.statusCode).toBe(401);
expect(res.json()).toMatchObject({ error: 'Invalid credentials' });
});
it('returns 401 when password is wrong', async () => {
const rows = [{ id: 'u1', email: '[email protected]', role: 'admin', password_hash: '$2b$hash', is_active: 1 }];
const pool = makePool(vi.fn().mockResolvedValue([rows as unknown as RowDataPacket[]]));
vi.mocked(mockBcrypt.compare).mockResolvedValue(false as never);
const app = await buildApp(pool);
const res = await app.inject({
method: 'POST',
url: '/admin/auth/login',
payload: { email: '[email protected]', password: 'wrongpass' },
});
expect(res.statusCode).toBe(401);
});
it('returns 401 when user is inactive', async () => {
const rows = [{ id: 'u1', email: '[email protected]', role: 'admin', password_hash: '$2b$hash', is_active: 0 }];
const pool = makePool(vi.fn().mockResolvedValue([rows as unknown as RowDataPacket[]]));
vi.mocked(mockBcrypt.compare).mockResolvedValue(true as never);
const app = await buildApp(pool);
const res = await app.inject({
method: 'POST',
url: '/admin/auth/login',
payload: { email: '[email protected]', password: 'pass' },
});
expect(res.statusCode).toBe(401);
});
it('returns 200 with user info on successful login', async () => {
const rows = [{ id: 'u1', email: '[email protected]', role: 'admin', password_hash: '$2b$hash', is_active: 1 }];
const pool = makePool(vi.fn().mockResolvedValue([rows as unknown as RowDataPacket[]]));
vi.mocked(mockBcrypt.compare).mockResolvedValue(true as never);
const app = await buildApp(pool);
const res = await app.inject({
method: 'POST',
url: '/admin/auth/login',
payload: { email: '[email protected]', password: 'correct' },
});
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ user: { id: 'u1', email: '[email protected]', role: 'admin' } });
});
});
describe('POST /admin/auth/refresh', () => {
it('returns 401 when no refresh token cookie present', async () => {
const app = await buildApp();
const res = await app.inject({ method: 'POST', url: '/admin/auth/refresh' });
expect(res.statusCode).toBe(401);
expect(res.json()).toMatchObject({ error: 'No refresh token' });
});
it('returns 401 when token hash not found in db', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({
method: 'POST',
url: '/admin/auth/refresh',
headers: { cookie: '__Host-refresh=sometoken' },
});
expect(res.statusCode).toBe(401);
expect(res.json()).toMatchObject({ error: 'Refresh token invalid or expired' });
});
it('returns 401 when token is revoked', async () => {
const tokenRow = [{
id: 't1',
user_id: 'u1',
expires_at: new Date(Date.now() + 1_000_000),
revoked_at: new Date(),
}];
const pool = makePool(vi.fn().mockResolvedValue([tokenRow as unknown as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({
method: 'POST',
url: '/admin/auth/refresh',
headers: { cookie: '__Host-refresh=sometoken' },
});
expect(res.statusCode).toBe(401);
});
it('returns 401 when token is expired', async () => {
const tokenRow = [{
id: 't1',
user_id: 'u1',
expires_at: new Date(Date.now() - 1_000),
revoked_at: null,
}];
const pool = makePool(vi.fn().mockResolvedValue([tokenRow as unknown as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({
method: 'POST',
url: '/admin/auth/refresh',
headers: { cookie: '__Host-refresh=sometoken' },
});
expect(res.statusCode).toBe(401);
});
it('returns 401 when user no longer active after valid token', async () => {
const tokenRow = [{ id: 't1', user_id: 'u1', expires_at: new Date(Date.now() + 1_000_000), revoked_at: null }];
const user: RowDataPacket[] = [];
const execute = vi.fn()
.mockResolvedValueOnce([tokenRow])
.mockResolvedValueOnce([[]])
.mockResolvedValue([user]);
const pool = makePool(execute);
const app = await buildApp(pool);
const res = await app.inject({
method: 'POST',
url: '/admin/auth/refresh',
headers: { cookie: '__Host-refresh=sometoken' },
});
expect(res.statusCode).toBe(401);
expect(res.json()).toMatchObject({ error: 'User no longer active' });
});
it('returns 200 with ok:true on valid refresh', async () => {
const tokenRow = [{ id: 't1', user_id: 'u1', expires_at: new Date(Date.now() + 1_000_000), revoked_at: null }];
const userRow = [{ id: 'u1', email: '[email protected]', role: 'admin', is_active: 1 }];
const execute = vi.fn()
.mockResolvedValueOnce([tokenRow])
.mockResolvedValueOnce([[]])
.mockResolvedValueOnce([userRow])
.mockResolvedValue([[]]);
const pool = makePool(execute);
const app = await buildApp(pool);
const res = await app.inject({
method: 'POST',
url: '/admin/auth/refresh',
headers: { cookie: '__Host-refresh=sometoken' },
});
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ ok: true });
});
});
describe('POST /admin/auth/logout', () => {
it('returns 200 and clears cookies', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({
method: 'POST',
url: '/admin/auth/logout',
headers: { cookie: '__Host-refresh=sometoken' },
});
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ ok: true });
});
it('returns 200 even without refresh cookie', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'POST', url: '/admin/auth/logout' });
expect(res.statusCode).toBe(200);
});
});
describe('GET /admin/auth/me', () => {
it('returns current user info from auth context', async () => {
const app = await buildApp();
const res = await app.inject({ method: 'GET', url: '/admin/auth/me' });
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({
user: { id: 'u1', email: '[email protected]', role: 'admin' },
});
});
});
+192
View File
@@ -0,0 +1,192 @@
/**
* Tests for admin incident routes.
* Uses mock DB and bypassed auth decorators — no live database required.
*/
import { describe, it, expect, vi } from 'vitest';
import Fastify, { type FastifyInstance } from 'fastify';
import type { RowDataPacket } from 'mysql2';
import adminIncidentsRoutes from './incidents.js';
function makePool(executeFn?: (...args: unknown[]) => Promise<unknown>) {
return {
execute: executeFn ?? vi.fn().mockResolvedValue([[] as RowDataPacket[]]),
getConnection: vi.fn(),
};
}
async function buildApp(pool?: ReturnType<typeof makePool>): Promise<FastifyInstance> {
const app = Fastify({ logger: false });
const p = pool ?? makePool();
app.decorate('db', p as unknown as FastifyInstance['db']);
app.decorate('authenticate', async function (req: Parameters<FastifyInstance['authenticate']>[0]) {
(req as { auth: unknown }).auth = { user_id: 'u1', email: '[email protected]', role: 'admin' };
});
app.decorate('requirePermission', (_perm: string) => async (_req: unknown, _reply: unknown) => {
// passthrough — permission already granted by mock authenticate
});
await app.register(adminIncidentsRoutes);
return app;
}
const baseIncident = {
id: '42',
projectSlug: 'wdmi-store',
fingerprint: 'abc123',
title: 'Test error',
severity: 'high',
currentState: 'open',
firstSeenAt: '2026-01-01T00:00:00.000Z',
lastSeenAt: '2026-01-02T00:00:00.000Z',
occurrencesCount: 5,
};
describe('GET /v1/incidents', () => {
it('returns empty list when no incidents', async () => {
const app = await buildApp();
const res = await app.inject({ method: 'GET', url: '/v1/incidents' });
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ incidents: [] });
});
it('returns mapped incident list', async () => {
const row = {
id: '42',
projectSlug: 'wdmi-store',
fingerprint: 'abc123',
title: 'Test error',
severity: 'high',
currentState: 'open',
firstSeenAt: '2026-01-01T00:00:00.000Z',
lastSeenAt: '2026-01-02T00:00:00.000Z',
occurrencesCount: 5,
};
const pool = makePool(vi.fn().mockResolvedValue([[row as unknown as RowDataPacket]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/incidents' });
expect(res.statusCode).toBe(200);
const body = res.json() as { incidents: typeof baseIncident[] };
expect(body.incidents).toHaveLength(1);
expect(body.incidents[0]).toMatchObject({ id: '42', severity: 'high', currentState: 'open' });
});
it('accepts valid state filter', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/incidents?state=resolved' });
expect(res.statusCode).toBe(200);
});
it('accepts valid severity filter', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/incidents?severity=critical' });
expect(res.statusCode).toBe(200);
});
it('accepts project slug filter', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/incidents?project=myproject' });
expect(res.statusCode).toBe(200);
});
it('accepts search query filter', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/incidents?q=TypeError' });
expect(res.statusCode).toBe(200);
});
it('accepts combined filters', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/incidents?state=open&severity=high&project=proj&q=crash' });
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ incidents: [] });
});
});
describe('GET /v1/incidents/:id', () => {
it('returns 404 for non-numeric id', async () => {
const app = await buildApp();
const res = await app.inject({ method: 'GET', url: '/v1/incidents/abc-not-numeric' });
expect(res.statusCode).toBe(404);
});
it('returns 404 when incident not found in db', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/incidents/9999' });
expect(res.statusCode).toBe(404);
});
it('returns incident with occurrences on found', async () => {
const incidentRow = {
id: '42',
projectSlug: 'wdmi-store',
fingerprint: 'abc123',
title: 'Test error',
severity: 'high',
currentState: 'open',
firstSeenAt: '2026-01-01T00:00:00.000Z',
lastSeenAt: '2026-01-02T00:00:00.000Z',
occurrencesCount: 1,
metadataJson: null,
ingestKeyLabel: 'prod-key',
};
const occurrenceRow = {
id: '1',
occurredAt: '2026-01-01T00:00:00.000Z',
levelRaw: 'error',
severity: 'high',
message: 'Something failed',
stacktrace: null,
contextJson: '{"env":"production"}',
};
const execute = vi.fn()
.mockResolvedValueOnce([[incidentRow as unknown as RowDataPacket]])
.mockResolvedValue([[occurrenceRow as unknown as RowDataPacket]]);
const pool = makePool(execute);
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/incidents/42' });
expect(res.statusCode).toBe(200);
const body = res.json() as { incident: { id: string; occurrences: unknown[] } };
expect(body.incident.id).toBe('42');
expect(body.incident.occurrences).toHaveLength(1);
});
it('handles occurrence with null stacktrace and contextJson', async () => {
const incidentRow = {
id: '1',
projectSlug: 'proj',
fingerprint: 'fp',
title: 'err',
severity: 'low',
currentState: 'open',
firstSeenAt: '2026-01-01T00:00:00.000Z',
lastSeenAt: '2026-01-01T00:00:00.000Z',
occurrencesCount: 1,
metadataJson: '{"key":"val"}',
ingestKeyLabel: null,
};
const occurrenceRow = {
id: '2',
occurredAt: '2026-01-01T00:00:00.000Z',
levelRaw: 'warn',
severity: 'low',
message: 'warn',
stacktrace: null,
contextJson: null,
};
const execute = vi.fn()
.mockResolvedValueOnce([[incidentRow as unknown as RowDataPacket]])
.mockResolvedValue([[occurrenceRow as unknown as RowDataPacket]]);
const pool = makePool(execute);
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/incidents/1' });
expect(res.statusCode).toBe(200);
const body = res.json() as { incident: { metadataJson: unknown; ingestKeyLabel: unknown } };
expect(body.incident.metadataJson).toMatchObject({ key: 'val' });
expect(body.incident.ingestKeyLabel).toBeNull();
});
});
+245
View File
@@ -0,0 +1,245 @@
/**
* Tests for admin stats routes.
* Uses mock DB and bypassed auth decorators — no live database required.
*/
import { describe, it, expect, vi } from 'vitest';
import Fastify, { type FastifyInstance } from 'fastify';
import type { RowDataPacket } from 'mysql2';
import adminStatsRoutes from './stats.js';
function makePool(executeFn?: (...args: unknown[]) => Promise<unknown>) {
return {
execute: executeFn ?? vi.fn().mockResolvedValue([[] as RowDataPacket[]]),
getConnection: vi.fn(),
};
}
async function buildApp(pool?: ReturnType<typeof makePool>): Promise<FastifyInstance> {
const app = Fastify({ logger: false });
const p = pool ?? makePool();
app.decorate('db', p as unknown as FastifyInstance['db']);
app.decorate('authenticate', async function (req: Parameters<FastifyInstance['authenticate']>[0]) {
(req as { auth: unknown }).auth = { user_id: 'u1', email: '[email protected]', role: 'admin' };
});
app.decorate('requirePermission', (_perm: string) => async (_req: unknown, _reply: unknown) => {
// passthrough
});
await app.register(adminStatsRoutes);
return app;
}
describe('GET /v1/stats/trend', () => {
it('returns day granularity by default with empty series', async () => {
const app = await buildApp();
const res = await app.inject({ method: 'GET', url: '/v1/stats/trend' });
expect(res.statusCode).toBe(200);
const body = res.json() as { granularity: string; dates: string[]; series: Record<string, number[]> };
expect(body.granularity).toBe('day');
expect(Array.isArray(body.dates)).toBe(true);
expect(body.dates.length).toBeGreaterThan(0);
expect(body.series).toHaveProperty('critical');
expect(body.series).toHaveProperty('high');
expect(body.series).toHaveProperty('low');
expect(body.series).toHaveProperty('info');
});
it('returns hour granularity when requested', async () => {
const app = await buildApp();
const res = await app.inject({ method: 'GET', url: '/v1/stats/trend?granularity=hour&hours=5' });
expect(res.statusCode).toBe(200);
const body = res.json() as { granularity: string; hours: string[] };
expect(body.granularity).toBe('hour');
expect(body.hours).toHaveLength(5);
});
it('returns 404 when project slug not found for day granularity', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/trend?project=nonexistent' });
expect(res.statusCode).toBe(404);
});
it('returns 404 when project slug not found for hour granularity', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/trend?granularity=hour&project=nonexistent' });
expect(res.statusCode).toBe(404);
});
it('maps DB aggregate rows into series data for day granularity', async () => {
const today = new Date();
const dateStr = today.toISOString().slice(0, 10);
const aggRow = { d: dateStr, severity: 'critical', c: 7 };
const pool = makePool(vi.fn().mockResolvedValue([[aggRow as unknown as RowDataPacket]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/trend?days=3' });
expect(res.statusCode).toBe(200);
const body = res.json() as { series: Record<string, number[]> };
const criticalSeries = body.series['critical'] ?? [];
expect(criticalSeries.some((v) => v === 7)).toBe(true);
});
it('maps DB aggregate rows into series data for hour granularity', async () => {
const now = new Date();
now.setUTCMinutes(0, 0, 0);
now.setUTCMilliseconds(0);
const y = now.getUTCFullYear();
const mo = String(now.getUTCMonth() + 1).padStart(2, '0');
const day = String(now.getUTCDate()).padStart(2, '0');
const h = String(now.getUTCHours()).padStart(2, '0');
const bucketLabel = `${y}-${mo}-${day} ${h}:00:00`;
const aggRow = { b: bucketLabel, severity: 'high', c: 3 };
const pool = makePool(vi.fn().mockResolvedValue([[aggRow as unknown as RowDataPacket]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/trend?granularity=hour&hours=3' });
expect(res.statusCode).toBe(200);
const body = res.json() as { series: Record<string, number[]> };
expect(body.series['high']?.some((v) => v === 3)).toBe(true);
});
it('ignores unknown severity in aggregate rows', async () => {
const aggRow = { d: new Date().toISOString().slice(0, 10), severity: 'unknown-severity', c: 10 };
const pool = makePool(vi.fn().mockResolvedValue([[aggRow as unknown as RowDataPacket]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/trend?days=1' });
expect(res.statusCode).toBe(200);
const body = res.json() as { series: Record<string, number[]> };
expect(body.series['critical']?.every((v) => v === 0)).toBe(true);
});
it('accepts days parameter for day granularity', async () => {
const app = await buildApp();
const res = await app.inject({ method: 'GET', url: '/v1/stats/trend?days=7' });
expect(res.statusCode).toBe(200);
const body = res.json() as { dates: string[] };
expect(body.dates).toHaveLength(7);
});
});
describe('GET /v1/stats/summary', () => {
const defaultExecute = vi.fn()
.mockResolvedValueOnce([[{ slug: 'proj', total_incidents: 5, open_cnt: 2, investigating_cnt: 0, resolved_cnt: 3, ignored_cnt: 0, critical_cnt: 1 } as unknown as RowDataPacket]])
.mockResolvedValueOnce([[{ severity: 'critical', c: 1 } as unknown as RowDataPacket]])
.mockResolvedValueOnce([[{ c: 2 } as unknown as RowDataPacket]])
.mockResolvedValue([[{ c: 10 } as unknown as RowDataPacket]]);
it('returns byProject, bySeverity, resolvedLast24h, totalLast24h', async () => {
const execute = vi.fn()
.mockResolvedValueOnce([[{ slug: 'proj', total_incidents: 5, open_cnt: 2, investigating_cnt: 0, resolved_cnt: 3, ignored_cnt: 0, critical_cnt: 1 } as unknown as RowDataPacket]])
.mockResolvedValueOnce([[{ severity: 'high', c: 4 } as unknown as RowDataPacket]])
.mockResolvedValueOnce([[{ c: 2 } as unknown as RowDataPacket]])
.mockResolvedValue([[{ c: 10 } as unknown as RowDataPacket]]);
const pool = makePool(execute);
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/summary' });
expect(res.statusCode).toBe(200);
const body = res.json() as { byProject: unknown[]; bySeverity: Record<string, number>; resolvedLast24h: number; totalLast24h: number };
expect(body.byProject).toHaveLength(1);
expect(body.bySeverity.high).toBe(4);
expect(body.resolvedLast24h).toBe(2);
expect(body.totalLast24h).toBe(10);
});
it('returns 404 when project slug not found', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/summary?project=nonexistent' });
expect(res.statusCode).toBe(404);
});
it('handles empty results gracefully', async () => {
const execute = vi.fn().mockResolvedValue([[] as RowDataPacket[]]);
const pool = makePool(execute);
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/summary' });
expect(res.statusCode).toBe(200);
const body = res.json() as { byProject: unknown[]; bySeverity: Record<string, number>; resolvedLast24h: number; totalLast24h: number };
expect(body.byProject).toHaveLength(0);
expect(body.resolvedLast24h).toBe(0);
expect(body.totalLast24h).toBe(0);
});
it('skips unknown severity values from summary rows', async () => {
const execute = vi.fn()
.mockResolvedValueOnce([[]])
.mockResolvedValueOnce([[{ severity: 'badvalue', c: 99 } as unknown as RowDataPacket]])
.mockResolvedValueOnce([[{ c: 0 } as unknown as RowDataPacket]])
.mockResolvedValue([[{ c: 0 } as unknown as RowDataPacket]]);
const pool = makePool(execute);
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/summary' });
expect(res.statusCode).toBe(200);
const body = res.json() as { bySeverity: Record<string, number> };
expect(body.bySeverity.critical).toBe(0);
});
it('accepts valid project filter when project exists', async () => {
const execute = vi.fn()
.mockResolvedValueOnce([[{ ok: 1 } as unknown as RowDataPacket]])
.mockResolvedValueOnce([[]])
.mockResolvedValueOnce([[]])
.mockResolvedValueOnce([[{ c: 0 } as unknown as RowDataPacket]])
.mockResolvedValue([[{ c: 0 } as unknown as RowDataPacket]]);
const pool = makePool(execute);
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/summary?project=myproject' });
expect(res.statusCode).toBe(200);
});
});
describe('GET /v1/stats/recurrence', () => {
it('returns empty top list when no occurrences', async () => {
const app = await buildApp();
const res = await app.inject({ method: 'GET', url: '/v1/stats/recurrence' });
expect(res.statusCode).toBe(200);
const body = res.json() as { top: unknown[]; windowDays: number };
expect(body.top).toHaveLength(0);
expect(body.windowDays).toBe(7);
});
it('maps top incidents correctly', async () => {
const row = {
id: '1',
project_slug: 'proj',
fingerprint: 'fp1',
title: 'Crash in module',
severity: 'critical',
current_state: 'open',
hits_in_window: 42,
lifetime_occurrences: 100,
};
const pool = makePool(vi.fn().mockResolvedValue([[row as unknown as RowDataPacket]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/recurrence?days=14&limit=5' });
expect(res.statusCode).toBe(200);
const body = res.json() as { top: Array<{ hitsInWindow: number; lifetimeOccurrences: number }> };
expect(body.top[0]?.hitsInWindow).toBe(42);
expect(body.top[0]?.lifetimeOccurrences).toBe(100);
});
it('returns 404 when project slug not found', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/recurrence?project=nonexistent' });
expect(res.statusCode).toBe(404);
});
it('accepts valid project when it exists', async () => {
const execute = vi.fn()
.mockResolvedValueOnce([[{ ok: 1 } as unknown as RowDataPacket]])
.mockResolvedValue([[] as RowDataPacket[]]);
const pool = makePool(execute);
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/recurrence?project=validproject' });
expect(res.statusCode).toBe(200);
});
it('uses default days=7 and limit=15 when not specified', async () => {
const pool = makePool(vi.fn().mockResolvedValue([[] as RowDataPacket[]]));
const app = await buildApp(pool);
const res = await app.inject({ method: 'GET', url: '/v1/stats/recurrence' });
expect(res.statusCode).toBe(200);
const body = res.json() as { windowDays: number };
expect(body.windowDays).toBe(7);
});
});
@@ -0,0 +1,230 @@
/**
* Tests for GET /api/error-monitoring/stats
* Uses the same in-process Fastify injection pattern as other route tests.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import Fastify, { type FastifyInstance } from 'fastify';
import type { RowDataPacket } from 'mysql2';
import errorMonitoringStatsRoutes from './errorMonitoringStats.js';
vi.mock('../../plugins/prometheus.js', () => ({
metricsGauges: {
occurrences24hGauge: { set: vi.fn() },
resolved24hGauge: { set: vi.fn() },
incidentsBySeverityGauge: { labels: vi.fn().mockReturnValue({ set: vi.fn() }) },
incidentsTotalGauge: { labels: vi.fn().mockReturnValue({ set: vi.fn() }) },
projectIncidentsGauge: {
reset: vi.fn(),
labels: vi.fn().mockReturnValue({ set: vi.fn() }),
},
projectResolutionRateGauge: {
reset: vi.fn(),
labels: vi.fn().mockReturnValue({ set: vi.fn() }),
},
},
}));
function makeExecute(responses: unknown[][]) {
let call = 0;
return vi.fn().mockImplementation(() => Promise.resolve([responses[call++] ?? []]));
}
async function buildApp(execute: ReturnType<typeof vi.fn>): Promise<FastifyInstance> {
const app = Fastify({ logger: false });
app.decorate('db', { execute } as unknown as FastifyInstance['db']);
await app.register(errorMonitoringStatsRoutes);
return app;
}
const PREV_KEY = process.env.ERROR_RESOLVE_API_KEY;
beforeEach(() => {
process.env.ERROR_RESOLVE_API_KEY = 'test-stats-key';
});
afterEach(() => {
if (PREV_KEY === undefined) {
delete process.env.ERROR_RESOLVE_API_KEY;
} else {
process.env.ERROR_RESOLVE_API_KEY = PREV_KEY;
}
});
describe('GET /api/error-monitoring/stats', () => {
function makeDefaultExecute() {
return makeExecute([
// sevRows
[
{ severity: 'critical', c: 5 } as RowDataPacket,
{ severity: 'high', c: 10 } as RowDataPacket,
{ severity: 'unknown_sev', c: 1 } as RowDataPacket,
],
// stateRows
[
{ state: 'open', c: 8 } as RowDataPacket,
{ state: 'resolved', c: 7 } as RowDataPacket,
],
// vol24h
[{ c: 42 } as RowDataPacket],
// res24h
[{ c: 3 } as RowDataPacket],
// hourlyRows
[
{ hour_bucket: '2026-01-01 00:00:00', severity: 'high', cnt: 2 } as RowDataPacket,
{ hour_bucket: '2026-01-01 00:00:00', severity: 'bad_sev', cnt: 1 } as RowDataPacket,
],
// projRows
[
{
slug: 'wdmi',
total: 10,
open_cnt: 3,
investigating_cnt: 2,
resolved_cnt: 4,
ignored_cnt: 1,
critical_cnt: 2,
} as RowDataPacket,
],
]);
}
it('returns 401 without a valid api_key', async () => {
const execute = makeExecute([]);
const app = await buildApp(execute);
const res = await app.inject({ method: 'GET', url: '/api/error-monitoring/stats' });
expect(res.statusCode).toBe(401);
});
it('returns 200 with api_key query param', async () => {
const execute = makeDefaultExecute();
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/stats?api_key=test-stats-key',
});
expect(res.statusCode).toBe(200);
});
it('returns correct bySeverity counts', async () => {
const execute = makeDefaultExecute();
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/stats?api_key=test-stats-key',
});
const body = res.json<{ bySeverity: Record<string, number> }>();
expect(body.bySeverity.critical).toBe(5);
expect(body.bySeverity.high).toBe(10);
expect(body.bySeverity.medium).toBe(0);
expect(body.bySeverity.low).toBe(0);
expect(body.bySeverity.info).toBe(0);
});
it('returns correct byState counts', async () => {
const execute = makeDefaultExecute();
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/stats?api_key=test-stats-key',
});
const body = res.json<{ byState: Record<string, number> }>();
expect(body.byState.open).toBe(8);
expect(body.byState.resolved).toBe(7);
});
it('returns correct 24h ingestion volume', async () => {
const execute = makeDefaultExecute();
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/stats?api_key=test-stats-key',
});
const body = res.json<{ ingestion: { last24h: number; resolvedLast24h: number } }>();
expect(body.ingestion.last24h).toBe(42);
expect(body.ingestion.resolvedLast24h).toBe(3);
});
it('returns 24-entry hourlyTrend array (zero-filled)', async () => {
const execute = makeDefaultExecute();
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/stats?api_key=test-stats-key',
});
const body = res.json<{ ingestion: { hourlyTrend: unknown[] } }>();
expect(body.ingestion.hourlyTrend).toHaveLength(24);
});
it('returns correct per-project metrics with resolutionRate', async () => {
const execute = makeDefaultExecute();
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/stats?api_key=test-stats-key',
});
const body = res.json<{
projects: Array<{ slug: string; total: number; resolved: number; resolutionRate: number }>;
}>();
expect(body.projects).toHaveLength(1);
const proj = body.projects[0];
expect(proj.slug).toBe('wdmi');
expect(proj.total).toBe(10);
expect(proj.resolved).toBe(4);
expect(proj.resolutionRate).toBe(0.4);
});
it('returns resolutionRate of 0 when total is 0', async () => {
const execute = makeExecute([
[],
[],
[{ c: 0 } as RowDataPacket],
[{ c: 0 } as RowDataPacket],
[],
[
{
slug: 'empty-proj',
total: 0,
open_cnt: 0,
investigating_cnt: 0,
resolved_cnt: 0,
ignored_cnt: 0,
critical_cnt: 0,
} as RowDataPacket,
],
]);
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/stats?api_key=test-stats-key',
});
const body = res.json<{ projects: Array<{ resolutionRate: number }> }>();
expect(body.projects[0].resolutionRate).toBe(0);
});
it('returns 401 with wrong api_key', async () => {
const execute = makeExecute([]);
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/stats?api_key=wrong-key',
});
expect(res.statusCode).toBe(401);
});
it('accepts view_errors query param when DEBUG_VIEW_ERRORS_KEY is set', async () => {
const prevViewKey = process.env.DEBUG_VIEW_ERRORS_KEY;
process.env.DEBUG_VIEW_ERRORS_KEY = 'view-only-key';
try {
const execute = makeDefaultExecute();
const app = await buildApp(execute);
const res = await app.inject({
method: 'GET',
url: '/api/error-monitoring/stats?view_errors=view-only-key',
});
expect(res.statusCode).toBe(200);
} finally {
if (prevViewKey === undefined) delete process.env.DEBUG_VIEW_ERRORS_KEY;
else process.env.DEBUG_VIEW_ERRORS_KEY = prevViewKey;
}
});
});