Add API integration test suite with Postgres and ClickHouse coverage

This commit is contained in:
Mike Cao committed 2026-09-06 16:42:53 -07:00
1 parent 950ae63f87
commit e18769e8cf
59 files changed
+8971 -28

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
import type { ApiClient } from '../client';
export interface Credentials {
username: string;
password: string;
}
export async function login(api: ApiClient, { username, password }: Credentials) {
const response = await api.post('/api/auth/login', { username, password });
if (response.status !== 200 || !response.body?.token) {
throw new Error(`Login failed for ${username} (${response.status}): ${response.text}`);
}
return response.body.token as string;
}
+45
View File
@@ -0,0 +1,45 @@
/**
* Constants mirrored from src/lib/constants.ts. The API suite deliberately does
* not import from src/ (server-only modules, path aliases), so keep these in
* sync by hand — they change rarely.
*/
/** Created by prisma/migrations/01_init on first boot. */
export const ADMIN_USER = {
id: '41e2b680-648e-4b09-bcd7-3e2b10c06264',
username: 'admin',
password: 'umami',
role: 'admin',
} as const;
export const ROLES = {
admin: 'admin',
user: 'user',
viewOnly: 'view-only',
teamOwner: 'team-owner',
teamManager: 'team-manager',
teamMember: 'team-member',
teamViewOnly: 'team-view-only',
} as const;
export const EVENT_TYPE = {
pageView: 1,
customEvent: 2,
linkEvent: 3,
pixelEvent: 4,
performance: 5,
} as const;
export const ENTITY_TYPE = {
website: 1,
link: 2,
pixel: 3,
board: 4,
} as const;
export const SHARE_TOKEN_HEADER = 'x-umami-share-token';
export const SHARE_CONTEXT_HEADER = 'x-umami-share-context';
export const CACHE_HEADER = 'x-umami-cache';
/** A syntactically valid v4 UUID that never exists in the database. */
export const UNKNOWN_UUID = '00000000-0000-4000-8000-000000000000';
+16
View File
@@ -0,0 +1,16 @@
import type { SeedState } from '../seed/state';
export const TIMEZONE = 'UTC';
/** `startAt`/`endAt` (ms) query params spanning the whole seeded dataset. */
export function dateRange(seed: SeedState, extra: Record<string, string | number> = {}) {
return { startAt: seed.range.startAt, endAt: Date.now(), ...extra };
}
/** `startDate`/`endDate` ISO strings used by report parameters. */
export function dateRangeIso(seed: SeedState) {
return {
startDate: new Date(seed.range.startAt).toISOString(),
endDate: new Date().toISOString(),
};
}
+102
View File
@@ -0,0 +1,102 @@
import { randomUUID } from 'node:crypto';
import type { ApiClient, ApiResponse } from '../client';
/**
* Helpers for creating throwaway entities. Every spec should create the
* mutable resources it needs (with unique names) and delete them in
* `afterAll`; the seeded entities are shared and must stay read-only.
*/
export function uniqueName(prefix: string) {
return `${prefix}-${randomUUID().slice(0, 8)}`;
}
/** Link/pixel slugs must be at least 8 characters. */
export function uniqueSlug(prefix: string) {
return `${prefix}${randomUUID().replace(/-/g, '').slice(0, 12)}`;
}
export function uniqueDomain() {
return `${uniqueName('site')}.test`;
}
export function assertStatus<T>(response: ApiResponse<T>, expected: number, label: string) {
if (response.status !== expected) {
throw new Error(
`${label}: expected HTTP ${expected}, got ${response.status}: ${response.text}`,
);
}
return response;
}
export async function createWebsite(client: ApiClient, overrides: Record<string, unknown> = {}) {
const response = await client.post('/api/websites', {
name: uniqueName('website'),
domain: uniqueDomain(),
...overrides,
});
return assertStatus(response, 200, 'create website').body;
}
export async function deleteWebsite(client: ApiClient, websiteId: string) {
await client.del(`/api/websites/${websiteId}`);
}
export async function createUser(admin: ApiClient, overrides: Record<string, unknown> = {}) {
const password = 'throwaway-password';
const response = await admin.post('/api/users', {
username: uniqueName('user'),
password,
role: 'user',
...overrides,
});
return { ...assertStatus(response, 200, 'create user').body, password };
}
export async function deleteUser(admin: ApiClient, userId: string) {
await admin.del(`/api/users/${userId}`);
}
/** POST /api/teams responds with `[team, teamUser]`. */
export async function createTeam(client: ApiClient, overrides: Record<string, unknown> = {}) {
const response = await client.post('/api/teams', { name: uniqueName('team'), ...overrides });
const [team, teamUser] = assertStatus(response, 200, 'create team').body;
return { ...team, teamUser };
}
export async function deleteTeam(client: ApiClient, teamId: string) {
await client.del(`/api/teams/${teamId}`);
}
export async function createLink(client: ApiClient, overrides: Record<string, unknown> = {}) {
const response = await client.post('/api/links', {
name: uniqueName('link'),
url: 'https://umami.is/',
slug: uniqueSlug('link'),
...overrides,
});
return assertStatus(response, 200, 'create link').body;
}
export async function deleteLink(client: ApiClient, linkId: string) {
await client.del(`/api/links/${linkId}`);
}
export async function createPixel(client: ApiClient, overrides: Record<string, unknown> = {}) {
const response = await client.post('/api/pixels', {
name: uniqueName('pixel'),
slug: uniqueSlug('pixel'),
...overrides,
});
return assertStatus(response, 200, 'create pixel').body;
}
export async function deletePixel(client: ApiClient, pixelId: string) {
await client.del(`/api/pixels/${pixelId}`);
}
+47
View File
@@ -0,0 +1,47 @@
import { generateSync } from 'otplib';
/** TOTP defaults used by the server (otplib v13): SHA-1, 6 digits, 30 s step, no drift window. */
const STEP_SECONDS = 30;
/** Codes generated this close to the end of a step may expire before the server verifies them. */
const SAFETY_MARGIN_SECONDS = 4;
function sleep(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function secondsUntilNextStep() {
return STEP_SECONDS - (Math.floor(Date.now() / 1000) % STEP_SECONDS);
}
/**
* Returns a TOTP code for `secret` (the Base32 `manualKey` from setup/initiate)
* that is safe to submit immediately. Every accepted code is single-use for
* 90 s, so pass the previously accepted code as `lastCode` to wait for a new
* time step when necessary.
*/
export async function nextCode(secret: string, lastCode?: string) {
for (;;) {
const remaining = secondsUntilNextStep();
if (remaining <= SAFETY_MARGIN_SECONDS) {
await sleep(remaining * 1000 + 250);
continue;
}
const code = generateSync({ secret });
if (code !== lastCode) {
return code;
}
await sleep(remaining * 1000 + 250);
}
}
/** A 6-digit code that is guaranteed not to be the one currently valid for `secret`. */
export function wrongCode(secret: string) {
const current = generateSync({ secret });
return current === '000000' ? '111111' : '000000';
}