BIT-15744: add unit tests and coverage config for api, ingest-api, collector-worker
Add 68 new unit tests covering: - api/src/types/auth.ts: can() RBAC function and ROLE_PERMISSIONS matrix (10 tests) - ingest-api/src/lib/hash.ts: sha256Hex() and stableJsonHash() pure functions (12 tests) - ingest-api/src/config/env.ts: loadEnv() with defaults, validation, clamping (8 tests) - collector-worker/src/config/loadEnv.ts: loadEnv() with all opts (11 tests) - collector-worker/src/log/structuredLog.ts: logInfo/logWarn/logError output (11 tests) - collector-worker/src/poll/fetchHttpEvents.ts: full validation/error path coverage (16 tests) Also add coverage reporting to vitest.config.ts (v8 provider, text/json/html reporters) and @vitest/coverage-v8 to devDependencies + test:coverage script in each service. All 68 tests pass. Run npm install && npm run test:coverage in each service directory. Paperclip-Issue: BIT-15744 Paperclip-Run: 2ff0b69d-853a-46fe-add7-43aa07012016
This commit is contained in:
1 parent
9a4939a2ba
commit
989a92ba07
12 files changed
+707
-2
No files matched your search
@@ -10,6 +10,7 @@
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"test:coverage": "vitest run --coverage",
|
||||
"db:migrate": "bash ../scripts/run-mysql-migrations.sh"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -31,6 +32,7 @@
|
||||
"@types/node": "^20.14.0",
|
||||
"tsx": "^4.15.6",
|
||||
"typescript": "^5.4.5",
|
||||
"@vitest/coverage-v8": "^1.6.0",
|
||||
"vitest": "^1.6.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { can, ROLE_PERMISSIONS } from './auth.js';
|
||||
import type { AdminRole, Permission } from './auth.js';
|
||||
|
||||
describe('ROLE_PERMISSIONS', () => {
|
||||
it('superadmin has all permissions', () => {
|
||||
const perms = ROLE_PERMISSIONS.superadmin;
|
||||
expect(perms.has('projects:delete')).toBe(true);
|
||||
expect(perms.has('users:delete')).toBe(true);
|
||||
expect(perms.has('settings:update')).toBe(true);
|
||||
expect(perms.has('audit_logs:read')).toBe(true);
|
||||
});
|
||||
|
||||
it('admin does not have user management permissions', () => {
|
||||
const perms = ROLE_PERMISSIONS.admin;
|
||||
expect(perms.has('users:create')).toBe(false);
|
||||
expect(perms.has('users:update')).toBe(false);
|
||||
expect(perms.has('users:delete')).toBe(false);
|
||||
});
|
||||
|
||||
it('admin has project and error management permissions', () => {
|
||||
const perms = ROLE_PERMISSIONS.admin;
|
||||
expect(perms.has('projects:read')).toBe(true);
|
||||
expect(perms.has('projects:create')).toBe(true);
|
||||
expect(perms.has('errors:read')).toBe(true);
|
||||
expect(perms.has('errors:triage')).toBe(true);
|
||||
expect(perms.has('errors:delete')).toBe(true);
|
||||
});
|
||||
|
||||
it('admin cannot delete projects', () => {
|
||||
expect(ROLE_PERMISSIONS.admin.has('projects:delete')).toBe(false);
|
||||
});
|
||||
|
||||
it('viewer has only read permissions', () => {
|
||||
const perms = ROLE_PERMISSIONS.viewer;
|
||||
expect(perms.has('projects:read')).toBe(true);
|
||||
expect(perms.has('errors:read')).toBe(true);
|
||||
expect(perms.has('ingest_tokens:read')).toBe(true);
|
||||
expect(perms.has('sources:read')).toBe(true);
|
||||
expect(perms.has('settings:read')).toBe(true);
|
||||
expect(perms.has('audit_logs:read')).toBe(true);
|
||||
});
|
||||
|
||||
it('viewer cannot create or modify anything', () => {
|
||||
const writePerms: Permission[] = [
|
||||
'projects:create', 'projects:update', 'projects:delete',
|
||||
'errors:triage', 'errors:delete',
|
||||
'ingest_tokens:create', 'ingest_tokens:revoke',
|
||||
'sources:create', 'sources:update', 'sources:delete',
|
||||
'users:read', 'users:create', 'users:update', 'users:delete',
|
||||
'settings:update',
|
||||
];
|
||||
for (const perm of writePerms) {
|
||||
expect(ROLE_PERMISSIONS.viewer.has(perm), `viewer should not have ${perm}`).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('can()', () => {
|
||||
it('returns true when role has permission', () => {
|
||||
expect(can('superadmin', 'users:delete')).toBe(true);
|
||||
expect(can('admin', 'errors:triage')).toBe(true);
|
||||
expect(can('viewer', 'projects:read')).toBe(true);
|
||||
});
|
||||
|
||||
it('returns false when role lacks permission', () => {
|
||||
expect(can('viewer', 'projects:create')).toBe(false);
|
||||
expect(can('admin', 'users:delete')).toBe(false);
|
||||
expect(can('viewer', 'settings:update')).toBe(false);
|
||||
});
|
||||
|
||||
it('superadmin can do everything', () => {
|
||||
const allPermissions: Permission[] = [
|
||||
'projects:read', 'projects:create', 'projects:update', 'projects:delete',
|
||||
'errors:read', 'errors:triage', 'errors:delete',
|
||||
'ingest_tokens:read', 'ingest_tokens:create', 'ingest_tokens:revoke',
|
||||
'sources:read', 'sources:create', 'sources:update', 'sources:delete',
|
||||
'users:read', 'users:create', 'users:update', 'users:delete',
|
||||
'settings:read', 'settings:update',
|
||||
'audit_logs:read',
|
||||
];
|
||||
for (const perm of allPermissions) {
|
||||
expect(can('superadmin', perm), `superadmin should have ${perm}`).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('all roles have audit_logs:read', () => {
|
||||
const roles: AdminRole[] = ['superadmin', 'admin', 'viewer'];
|
||||
for (const role of roles) {
|
||||
expect(can(role, 'audit_logs:read'), `${role} should have audit_logs:read`).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -4,5 +4,11 @@ export default defineConfig({
|
||||
test: {
|
||||
environment: 'node',
|
||||
include: ['src/**/*.test.ts'],
|
||||
coverage: {
|
||||
provider: 'v8',
|
||||
reporter: ['text', 'json', 'html'],
|
||||
include: ['src/**/*.ts'],
|
||||
exclude: ['src/**/*.test.ts', '**/*.d.ts'],
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -9,7 +9,9 @@
|
||||
"build": "tsc",
|
||||
"start": "node dist/main.js",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"test:coverage": "vitest run --coverage"
|
||||
},
|
||||
"dependencies": {
|
||||
"dotenv": "^16.4.5",
|
||||
@@ -19,6 +21,7 @@
|
||||
"@types/node": "^22.9.0",
|
||||
"tsx": "^4.19.2",
|
||||
"typescript": "^5.6.3",
|
||||
"@vitest/coverage-v8": "^2.1.0",
|
||||
"vitest": "^2.1.0"
|
||||
},
|
||||
"engines": {
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from "vitest";
|
||||
import { loadEnv } from "./loadEnv.js";
|
||||
|
||||
const REQUIRED_ENV = {
|
||||
DATABASE_URL: "mysql://user:pass@localhost:3306/errors",
|
||||
INGEST_BASE_URL: "http://ingest-api:3041",
|
||||
};
|
||||
|
||||
function setEnv(vars: Record<string, string | undefined>): void {
|
||||
for (const [key, value] of Object.entries(vars)) {
|
||||
if (value === undefined) {
|
||||
delete process.env[key];
|
||||
} else {
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe("loadEnv() — collector-worker", () => {
|
||||
const savedEnv: Record<string, string | undefined> = {};
|
||||
|
||||
beforeEach(() => {
|
||||
// Save and set required vars
|
||||
for (const key of Object.keys(REQUIRED_ENV)) {
|
||||
savedEnv[key] = process.env[key];
|
||||
}
|
||||
setEnv(REQUIRED_ENV);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setEnv(savedEnv);
|
||||
});
|
||||
|
||||
it("returns defaults when optional vars are absent", () => {
|
||||
setEnv({
|
||||
HTTP_FETCH_TIMEOUT_MS: undefined,
|
||||
INGEST_PUSH_TIMEOUT_MS: undefined,
|
||||
INGEST_PUSH_MAX_RETRIES: undefined,
|
||||
INGEST_PUSH_RETRY_BASE_MS: undefined,
|
||||
INGEST_PUSH_RETRY_MAX_JITTER_MS: undefined,
|
||||
TICK_INTERVAL_MS: undefined,
|
||||
SOURCE_REFRESH_MS: undefined,
|
||||
MAX_BACKOFF_EXPONENT: undefined,
|
||||
});
|
||||
const env = loadEnv();
|
||||
expect(env.HTTP_FETCH_TIMEOUT_MS).toBe(30_000);
|
||||
expect(env.INGEST_PUSH_TIMEOUT_MS).toBe(60_000);
|
||||
expect(env.INGEST_PUSH_MAX_RETRIES).toBe(3);
|
||||
expect(env.INGEST_PUSH_RETRY_BASE_MS).toBe(500);
|
||||
expect(env.INGEST_PUSH_RETRY_MAX_JITTER_MS).toBe(250);
|
||||
expect(env.TICK_INTERVAL_MS).toBe(2000);
|
||||
expect(env.SOURCE_REFRESH_MS).toBe(10_000);
|
||||
expect(env.MAX_BACKOFF_EXPONENT).toBe(8);
|
||||
});
|
||||
|
||||
it("trims and returns DATABASE_URL", () => {
|
||||
setEnv({ DATABASE_URL: " mysql://trimmed:pass@host/db " });
|
||||
const env = loadEnv();
|
||||
expect(env.DATABASE_URL).toBe("mysql://trimmed:pass@host/db");
|
||||
});
|
||||
|
||||
it("trims trailing slash from INGEST_BASE_URL", () => {
|
||||
setEnv({ INGEST_BASE_URL: "http://ingest-api:3041/" });
|
||||
const env = loadEnv();
|
||||
expect(env.INGEST_BASE_URL).toBe("http://ingest-api:3041");
|
||||
});
|
||||
|
||||
it("throws when DATABASE_URL is missing", () => {
|
||||
setEnv({ DATABASE_URL: undefined });
|
||||
expect(() => loadEnv()).toThrow("DATABASE_URL is required");
|
||||
});
|
||||
|
||||
it("throws when DATABASE_URL is blank", () => {
|
||||
setEnv({ DATABASE_URL: " " });
|
||||
expect(() => loadEnv()).toThrow("DATABASE_URL is required");
|
||||
});
|
||||
|
||||
it("throws when INGEST_BASE_URL is missing", () => {
|
||||
setEnv({ INGEST_BASE_URL: undefined });
|
||||
expect(() => loadEnv()).toThrow("INGEST_BASE_URL is required");
|
||||
});
|
||||
|
||||
it("parses custom integer values", () => {
|
||||
setEnv({
|
||||
HTTP_FETCH_TIMEOUT_MS: "15000",
|
||||
INGEST_PUSH_TIMEOUT_MS: "45000",
|
||||
INGEST_PUSH_MAX_RETRIES: "5",
|
||||
TICK_INTERVAL_MS: "3000",
|
||||
MAX_BACKOFF_EXPONENT: "6",
|
||||
});
|
||||
const env = loadEnv();
|
||||
expect(env.HTTP_FETCH_TIMEOUT_MS).toBe(15000);
|
||||
expect(env.INGEST_PUSH_TIMEOUT_MS).toBe(45000);
|
||||
expect(env.INGEST_PUSH_MAX_RETRIES).toBe(5);
|
||||
expect(env.TICK_INTERVAL_MS).toBe(3000);
|
||||
expect(env.MAX_BACKOFF_EXPONENT).toBe(6);
|
||||
});
|
||||
|
||||
it("clamps INGEST_PUSH_TIMEOUT_MS to minimum 1000", () => {
|
||||
setEnv({ INGEST_PUSH_TIMEOUT_MS: "0" });
|
||||
const env = loadEnv();
|
||||
expect(env.INGEST_PUSH_TIMEOUT_MS).toBe(1000);
|
||||
});
|
||||
|
||||
it("clamps INGEST_PUSH_MAX_RETRIES to max 12", () => {
|
||||
setEnv({ INGEST_PUSH_MAX_RETRIES: "20" });
|
||||
const env = loadEnv();
|
||||
expect(env.INGEST_PUSH_MAX_RETRIES).toBe(12);
|
||||
});
|
||||
|
||||
it("falls back to default for non-numeric values", () => {
|
||||
setEnv({ HTTP_FETCH_TIMEOUT_MS: "not-a-number" });
|
||||
const env = loadEnv();
|
||||
expect(env.HTTP_FETCH_TIMEOUT_MS).toBe(30_000);
|
||||
});
|
||||
|
||||
it("uses development as default NODE_ENV", () => {
|
||||
const saved = process.env.NODE_ENV;
|
||||
delete process.env.NODE_ENV;
|
||||
const env = loadEnv();
|
||||
expect(env.NODE_ENV).toBe("development");
|
||||
if (saved !== undefined) process.env.NODE_ENV = saved;
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { logInfo, logWarn, logError } from "./structuredLog.js";
|
||||
|
||||
describe("structuredLog", () => {
|
||||
let consoleLogs: string[];
|
||||
let consoleWarns: string[];
|
||||
let consoleErrors: string[];
|
||||
|
||||
beforeEach(() => {
|
||||
consoleLogs = [];
|
||||
consoleWarns = [];
|
||||
consoleErrors = [];
|
||||
vi.spyOn(console, "log").mockImplementation((msg: string) => { consoleLogs.push(msg); });
|
||||
vi.spyOn(console, "warn").mockImplementation((msg: string) => { consoleWarns.push(msg); });
|
||||
vi.spyOn(console, "error").mockImplementation((msg: string) => { consoleErrors.push(msg); });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("logInfo()", () => {
|
||||
it("writes to console.log with level=info", () => {
|
||||
logInfo({ msg: "test info" });
|
||||
expect(consoleLogs).toHaveLength(1);
|
||||
const parsed = JSON.parse(consoleLogs[0]);
|
||||
expect(parsed.level).toBe("info");
|
||||
});
|
||||
|
||||
it("includes the msg field", () => {
|
||||
logInfo({ msg: "hello world" });
|
||||
const parsed = JSON.parse(consoleLogs[0]);
|
||||
expect(parsed.msg).toBe("hello world");
|
||||
});
|
||||
|
||||
it("includes a ts field that is a valid ISO string", () => {
|
||||
logInfo({ msg: "ts test" });
|
||||
const parsed = JSON.parse(consoleLogs[0]);
|
||||
expect(parsed.ts).toBeDefined();
|
||||
expect(() => new Date(parsed.ts)).not.toThrow();
|
||||
expect(Number.isFinite(new Date(parsed.ts).getTime())).toBe(true);
|
||||
});
|
||||
|
||||
it("passes through extra fields", () => {
|
||||
logInfo({ msg: "with extras", sourceId: "src-1", eventCount: 5 });
|
||||
const parsed = JSON.parse(consoleLogs[0]);
|
||||
expect(parsed.sourceId).toBe("src-1");
|
||||
expect(parsed.eventCount).toBe(5);
|
||||
});
|
||||
|
||||
it("does not write to console.warn or console.error", () => {
|
||||
logInfo({ msg: "info only" });
|
||||
expect(consoleWarns).toHaveLength(0);
|
||||
expect(consoleErrors).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("logWarn()", () => {
|
||||
it("writes to console.warn with level=warn", () => {
|
||||
logWarn({ msg: "watch out" });
|
||||
expect(consoleWarns).toHaveLength(1);
|
||||
const parsed = JSON.parse(consoleWarns[0]);
|
||||
expect(parsed.level).toBe("warn");
|
||||
expect(parsed.msg).toBe("watch out");
|
||||
});
|
||||
|
||||
it("includes ts field", () => {
|
||||
logWarn({ msg: "ts check" });
|
||||
const parsed = JSON.parse(consoleWarns[0]);
|
||||
expect(parsed.ts).toBeDefined();
|
||||
});
|
||||
|
||||
it("does not write to console.log", () => {
|
||||
logWarn({ msg: "warn only" });
|
||||
expect(consoleLogs).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("logError()", () => {
|
||||
it("writes to console.error with level=error", () => {
|
||||
logError({ msg: "something broke" });
|
||||
expect(consoleErrors).toHaveLength(1);
|
||||
const parsed = JSON.parse(consoleErrors[0]);
|
||||
expect(parsed.level).toBe("error");
|
||||
expect(parsed.msg).toBe("something broke");
|
||||
});
|
||||
|
||||
it("includes ts field", () => {
|
||||
logError({ msg: "error ts" });
|
||||
const parsed = JSON.parse(consoleErrors[0]);
|
||||
expect(parsed.ts).toBeDefined();
|
||||
});
|
||||
|
||||
it("passes through extra fields like error messages", () => {
|
||||
logError({ msg: "db failed", err: "ECONNREFUSED", code: 500 });
|
||||
const parsed = JSON.parse(consoleErrors[0]);
|
||||
expect(parsed.err).toBe("ECONNREFUSED");
|
||||
expect(parsed.code).toBe(500);
|
||||
});
|
||||
|
||||
it("does not write to console.log or console.warn", () => {
|
||||
logError({ msg: "error only" });
|
||||
expect(consoleLogs).toHaveLength(0);
|
||||
expect(consoleWarns).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,202 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { fetchHttpPollEvents } from "./fetchHttpEvents.js";
|
||||
import type { IngestEventInput } from "../types/ingest.js";
|
||||
|
||||
function makeValidEvent(overrides: Partial<IngestEventInput> = {}): IngestEventInput {
|
||||
return {
|
||||
schema_version: 1,
|
||||
occurred_at: "2026-01-01T00:00:00Z",
|
||||
level: "error",
|
||||
message: "Test error",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function mockFetch(response: { ok: boolean; status?: number; body?: unknown }): void {
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
|
||||
ok: response.ok,
|
||||
status: response.status ?? (response.ok ? 200 : 500),
|
||||
text: vi.fn().mockResolvedValue(
|
||||
typeof response.body === "string" ? response.body : JSON.stringify(response.body),
|
||||
),
|
||||
}));
|
||||
}
|
||||
|
||||
const INPUT = { endpointUri: "http://example.com/events", timeoutMs: 5000 };
|
||||
|
||||
describe("fetchHttpPollEvents()", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("returns ok=true with parsed events for a valid response", async () => {
|
||||
const events = [makeValidEvent()];
|
||||
mockFetch({ ok: true, body: { events } });
|
||||
|
||||
const result = await fetchHttpPollEvents(INPUT);
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) {
|
||||
expect(result.events).toHaveLength(1);
|
||||
expect(result.events[0].message).toBe("Test error");
|
||||
}
|
||||
});
|
||||
|
||||
it("returns ok=false with http_status_* on non-OK HTTP response", async () => {
|
||||
mockFetch({ ok: false, status: 503 });
|
||||
const result = await fetchHttpPollEvents(INPUT);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error).toBe("http_status_503");
|
||||
}
|
||||
});
|
||||
|
||||
it("returns ok=false with invalid_json when body is not JSON", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
text: vi.fn().mockResolvedValue("not-json{{{"),
|
||||
}));
|
||||
const result = await fetchHttpPollEvents(INPUT);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error).toBe("invalid_json");
|
||||
}
|
||||
});
|
||||
|
||||
it("returns ok=false with expected_json_object when body is a JSON array", async () => {
|
||||
mockFetch({ ok: true, body: [1, 2, 3] });
|
||||
const result = await fetchHttpPollEvents(INPUT);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error).toBe("expected_json_object");
|
||||
}
|
||||
});
|
||||
|
||||
it("returns ok=false with missing_events_array when events key is absent", async () => {
|
||||
mockFetch({ ok: true, body: { data: [] } });
|
||||
const result = await fetchHttpPollEvents(INPUT);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error).toBe("missing_events_array");
|
||||
}
|
||||
});
|
||||
|
||||
it("returns ok=false with missing_events_array when events is not an array", async () => {
|
||||
mockFetch({ ok: true, body: { events: "not-array" } });
|
||||
const result = await fetchHttpPollEvents(INPUT);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error).toBe("missing_events_array");
|
||||
}
|
||||
});
|
||||
|
||||
it("returns ok=false with too_many_events_max_50 when events > 50", async () => {
|
||||
const events = Array.from({ length: 51 }, () => makeValidEvent());
|
||||
mockFetch({ ok: true, body: { events } });
|
||||
const result = await fetchHttpPollEvents(INPUT);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error).toBe("too_many_events_max_50");
|
||||
}
|
||||
});
|
||||
|
||||
it("returns ok=true with exactly 50 events", async () => {
|
||||
const events = Array.from({ length: 50 }, () => makeValidEvent());
|
||||
mockFetch({ ok: true, body: { events } });
|
||||
const result = await fetchHttpPollEvents(INPUT);
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) {
|
||||
expect(result.events).toHaveLength(50);
|
||||
}
|
||||
});
|
||||
|
||||
it("returns ok=false with invalid_event_shape when event is missing schema_version", async () => {
|
||||
const events = [{ occurred_at: "2026-01-01T00:00:00Z", level: "error", message: "Test" }];
|
||||
mockFetch({ ok: true, body: { events } });
|
||||
const result = await fetchHttpPollEvents(INPUT);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error).toBe("invalid_event_shape");
|
||||
}
|
||||
});
|
||||
|
||||
it("returns ok=false with invalid_event_shape when event has wrong schema_version", async () => {
|
||||
const events = [{ ...makeValidEvent(), schema_version: 2 }];
|
||||
mockFetch({ ok: true, body: { events } });
|
||||
const result = await fetchHttpPollEvents(INPUT);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error).toBe("invalid_event_shape");
|
||||
}
|
||||
});
|
||||
|
||||
it("returns ok=false with invalid_event_shape when level is empty", async () => {
|
||||
const events = [makeValidEvent({ level: " " })];
|
||||
mockFetch({ ok: true, body: { events } });
|
||||
const result = await fetchHttpPollEvents(INPUT);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error).toBe("invalid_event_shape");
|
||||
}
|
||||
});
|
||||
|
||||
it("returns ok=false with invalid_event_shape when message is empty", async () => {
|
||||
const events = [makeValidEvent({ message: "" })];
|
||||
mockFetch({ ok: true, body: { events } });
|
||||
const result = await fetchHttpPollEvents(INPUT);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error).toBe("invalid_event_shape");
|
||||
}
|
||||
});
|
||||
|
||||
it("returns ok=false with invalid_event_shape when occurred_at is missing", async () => {
|
||||
const events = [{ schema_version: 1, level: "error", message: "Test" }];
|
||||
mockFetch({ ok: true, body: { events } });
|
||||
const result = await fetchHttpPollEvents(INPUT);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error).toBe("invalid_event_shape");
|
||||
}
|
||||
});
|
||||
|
||||
it("returns ok=true with empty events array", async () => {
|
||||
mockFetch({ ok: true, body: { events: [] } });
|
||||
const result = await fetchHttpPollEvents(INPUT);
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) {
|
||||
expect(result.events).toHaveLength(0);
|
||||
}
|
||||
});
|
||||
|
||||
it("returns ok=false with fetch_timeout when aborted", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn().mockImplementation(() =>
|
||||
new Promise((_, reject) => {
|
||||
const err = new Error("The operation was aborted");
|
||||
err.name = "AbortError";
|
||||
setTimeout(() => reject(err), 100);
|
||||
}),
|
||||
));
|
||||
const resultPromise = fetchHttpPollEvents({ endpointUri: "http://example.com", timeoutMs: 50 });
|
||||
vi.advanceTimersByTime(200);
|
||||
const result = await resultPromise;
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error).toBe("fetch_timeout");
|
||||
}
|
||||
});
|
||||
|
||||
it("returns ok=false with error message on generic network error", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("ECONNREFUSED")));
|
||||
const result = await fetchHttpPollEvents(INPUT);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error).toBe("ECONNREFUSED");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -4,5 +4,11 @@ export default defineConfig({
|
||||
test: {
|
||||
environment: "node",
|
||||
include: ["src/**/*.test.ts"],
|
||||
coverage: {
|
||||
provider: "v8",
|
||||
reporter: ["text", "json", "html"],
|
||||
include: ["src/**/*.ts"],
|
||||
exclude: ["src/**/*.test.ts", "**/*.d.ts"],
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -10,7 +10,8 @@
|
||||
"start": "node dist/server.js",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run && python3 ../tools/ci/check_error_reporter_context_contract.py --path ../clients",
|
||||
"test:watch": "vitest"
|
||||
"test:watch": "vitest",
|
||||
"test:coverage": "vitest run --coverage"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/swagger": "^8.15.0",
|
||||
@@ -25,6 +26,7 @@
|
||||
"ajv": "^8.18.0",
|
||||
"tsx": "^4.19.2",
|
||||
"typescript": "^5.6.3",
|
||||
"@vitest/coverage-v8": "^2.1.0",
|
||||
"vitest": "^2.1.0"
|
||||
},
|
||||
"engines": {
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from "vitest";
|
||||
import { loadEnv } from "./env.js";
|
||||
|
||||
function setEnv(vars: Record<string, string | undefined>): void {
|
||||
for (const [key, value] of Object.entries(vars)) {
|
||||
if (value === undefined) {
|
||||
delete process.env[key];
|
||||
} else {
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe("loadEnv() — ingest-api", () => {
|
||||
const REQUIRED = { DATABASE_URL: "mysql://user:pass@localhost/errors" };
|
||||
const savedEnv: Record<string, string | undefined> = {};
|
||||
|
||||
beforeEach(() => {
|
||||
savedEnv.DATABASE_URL = process.env.DATABASE_URL;
|
||||
setEnv(REQUIRED);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setEnv(savedEnv);
|
||||
});
|
||||
|
||||
it("returns defaults for optional vars", () => {
|
||||
setEnv({
|
||||
PORT: undefined,
|
||||
INGEST_RATE_LIMIT_MAX: undefined,
|
||||
INGEST_RATE_LIMIT_WINDOW_MS: undefined,
|
||||
INGEST_ANON_IP_MAX: undefined,
|
||||
INGEST_ANON_IP_WINDOW_MS: undefined,
|
||||
});
|
||||
const env = loadEnv();
|
||||
expect(env.PORT).toBe(3041);
|
||||
expect(env.INGEST_RATE_LIMIT_MAX).toBe(300);
|
||||
expect(env.INGEST_RATE_LIMIT_WINDOW_MS).toBe(60_000);
|
||||
expect(env.INGEST_ANON_IP_MAX).toBe(120);
|
||||
expect(env.INGEST_ANON_IP_WINDOW_MS).toBe(60_000);
|
||||
});
|
||||
|
||||
it("trims DATABASE_URL", () => {
|
||||
setEnv({ DATABASE_URL: " mysql://host/db " });
|
||||
const env = loadEnv();
|
||||
expect(env.DATABASE_URL).toBe("mysql://host/db");
|
||||
});
|
||||
|
||||
it("throws when DATABASE_URL is missing", () => {
|
||||
setEnv({ DATABASE_URL: undefined });
|
||||
expect(() => loadEnv()).toThrow("DATABASE_URL is required");
|
||||
});
|
||||
|
||||
it("throws when DATABASE_URL is blank", () => {
|
||||
setEnv({ DATABASE_URL: " " });
|
||||
expect(() => loadEnv()).toThrow("DATABASE_URL is required");
|
||||
});
|
||||
|
||||
it("parses custom integer values", () => {
|
||||
setEnv({
|
||||
PORT: "4000",
|
||||
INGEST_RATE_LIMIT_MAX: "100",
|
||||
INGEST_ANON_IP_MAX: "50",
|
||||
});
|
||||
const env = loadEnv();
|
||||
expect(env.PORT).toBe(4000);
|
||||
expect(env.INGEST_RATE_LIMIT_MAX).toBe(100);
|
||||
expect(env.INGEST_ANON_IP_MAX).toBe(50);
|
||||
});
|
||||
|
||||
it("falls back to default for non-numeric values", () => {
|
||||
setEnv({ PORT: "invalid" });
|
||||
const env = loadEnv();
|
||||
expect(env.PORT).toBe(3041);
|
||||
});
|
||||
|
||||
it("uses development as default NODE_ENV", () => {
|
||||
const saved = process.env.NODE_ENV;
|
||||
delete process.env.NODE_ENV;
|
||||
const env = loadEnv();
|
||||
expect(env.NODE_ENV).toBe("development");
|
||||
if (saved !== undefined) process.env.NODE_ENV = saved;
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { sha256Hex, stableJsonHash } from "./hash.js";
|
||||
|
||||
describe("sha256Hex()", () => {
|
||||
it("returns a 64-char hex string", () => {
|
||||
const result = sha256Hex("hello");
|
||||
expect(result).toMatch(/^[0-9a-f]{64}$/);
|
||||
});
|
||||
|
||||
it("returns known hash for 'hello'", () => {
|
||||
expect(sha256Hex("hello")).toBe(
|
||||
"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns known hash for empty string", () => {
|
||||
expect(sha256Hex("")).toBe(
|
||||
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||
);
|
||||
});
|
||||
|
||||
it("is deterministic", () => {
|
||||
expect(sha256Hex("test input")).toBe(sha256Hex("test input"));
|
||||
});
|
||||
|
||||
it("produces different hashes for different inputs", () => {
|
||||
expect(sha256Hex("a")).not.toBe(sha256Hex("b"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("stableJsonHash()", () => {
|
||||
it("hashes primitive values", () => {
|
||||
const h1 = stableJsonHash(42);
|
||||
expect(h1).toMatch(/^[0-9a-f]{64}$/);
|
||||
expect(h1).toBe(stableJsonHash(42));
|
||||
});
|
||||
|
||||
it("hashes null", () => {
|
||||
const h = stableJsonHash(null);
|
||||
expect(h).toMatch(/^[0-9a-f]{64}$/);
|
||||
expect(h).toBe(stableJsonHash(null));
|
||||
});
|
||||
|
||||
it("is key-order independent for objects", () => {
|
||||
const a = stableJsonHash({ z: 1, a: 2 });
|
||||
const b = stableJsonHash({ a: 2, z: 1 });
|
||||
expect(a).toBe(b);
|
||||
});
|
||||
|
||||
it("produces different hashes for different values", () => {
|
||||
expect(stableJsonHash({ x: 1 })).not.toBe(stableJsonHash({ x: 2 }));
|
||||
});
|
||||
|
||||
it("handles nested objects with key-order independence", () => {
|
||||
const a = stableJsonHash({ outer: { b: 2, a: 1 } });
|
||||
const b = stableJsonHash({ outer: { a: 1, b: 2 } });
|
||||
expect(a).toBe(b);
|
||||
});
|
||||
|
||||
it("handles arrays (preserves order)", () => {
|
||||
expect(stableJsonHash([1, 2, 3])).not.toBe(stableJsonHash([3, 2, 1]));
|
||||
});
|
||||
|
||||
it("hashes string values", () => {
|
||||
const h = stableJsonHash("hello world");
|
||||
expect(h).toMatch(/^[0-9a-f]{64}$/);
|
||||
expect(h).toBe(stableJsonHash("hello world"));
|
||||
});
|
||||
});
|
||||
@@ -6,5 +6,12 @@ export default defineConfig({
|
||||
environment: "node",
|
||||
testTimeout: 60_000,
|
||||
hookTimeout: 60_000,
|
||||
include: ["src/**/*.test.ts"],
|
||||
coverage: {
|
||||
provider: "v8",
|
||||
reporter: ["text", "json", "html"],
|
||||
include: ["src/**/*.ts"],
|
||||
exclude: ["src/**/*.test.ts", "**/*.d.ts"],
|
||||
},
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user