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

+412
View File
@@ -0,0 +1,412 @@
import { SEED_IDS } from './ids';
/**
* Deterministic analytics dataset ingested through the real collection
* endpoints (/api/send, /api/batch, /api/record). Works for both Postgres and
* ClickHouse. Backdated events use `timestamp` (seconds).
*
* IPs are private on purpose: the test image has no GeoLite database and
* src/lib/detect.ts throws on a non-local IP lookup.
*/
export interface SendPayload {
type: 'event' | 'identify' | 'performance';
payload: Record<string, unknown>;
}
export interface RecordPayload {
type: 'record' | 'heatmap';
payload: Record<string, unknown>;
}
/** Events sent sequentially, chained with the `x-umami-cache` token. */
export interface Visit {
events: SendPayload[];
}
export interface Dataset {
range: { startAt: number; endAt: number };
visits: Visit[];
batch: SendPayload[];
replay: { pageview: SendPayload; record: RecordPayload; heatmap: RecordPayload };
realtime: SendPayload[];
expected: { pageviews: number; website2Pageviews: number };
distinctIds: string[];
pages: string[];
eventNames: string[];
}
export interface Persona {
id: string;
ip: string;
userAgent: string;
screen: string;
language: string;
referrer: string;
utm?: boolean;
tag?: string;
}
export const HOSTNAME = 'example.test';
export const CURRENCY = 'USD';
export const DAYS = 7;
export const EVENT_NAMES = ['signup', 'purchase', 'download'];
export const UTM_QUERY = 'utm_source=newsletter&utm_medium=email&utm_campaign=launch&gclid=abc123';
/** The first N personas send `identify` calls and carry a distinct id. */
const IDENTIFIED_PERSONAS = 3;
const DAY = 86_400;
const HOUR = 3_600;
export const PAGES = [
{ url: '/', title: 'Home' },
{ url: '/pricing', title: 'Pricing' },
{ url: '/blog/hello-world', title: 'Hello World' },
{ url: '/docs', title: 'Documentation' },
{ url: '/signup', title: 'Sign up' },
];
export const PERSONAS: Persona[] = [
{
id: 'alice',
ip: '10.0.0.1',
userAgent:
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
screen: '1920x1080',
language: 'en-US',
referrer: 'https://www.google.com/',
utm: true,
},
{
id: 'bob',
ip: '10.0.0.2',
userAgent:
'Mozilla/5.0 (Macintosh; Intel Mac OS X 14_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Safari/605.1.15',
screen: '2560x1440',
language: 'en-GB',
referrer: 'https://t.co/abc123',
},
{
id: 'carol',
ip: '10.0.0.3',
userAgent: 'Mozilla/5.0 (X11; Linux x86_64; rv:125.0) Gecko/20100101 Firefox/125.0',
screen: '1440x900',
language: 'de-DE',
referrer: '',
tag: 'beta',
},
{
id: 'dave',
ip: '10.0.0.4',
userAgent:
'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Mobile Safari/537.36',
screen: '412x915',
language: 'fr-FR',
referrer: 'https://www.bing.com/search?q=umami',
utm: true,
},
{
id: 'erin',
ip: '10.0.0.5',
userAgent:
'Mozilla/5.0 (iPhone; CPU iPhone OS 17_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Mobile/15E148 Safari/604.1',
screen: '390x844',
language: 'es-ES',
referrer: '',
},
{
id: 'frank',
ip: '10.0.0.6',
userAgent:
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0',
screen: '1366x768',
language: 'en-US',
referrer: 'https://github.com/umami-software/umami',
},
];
export function getDistinctId(persona: Persona) {
return `user-${persona.id}`;
}
function client(persona: Persona) {
return {
hostname: HOSTNAME,
language: persona.language,
screen: persona.screen,
userAgent: persona.userAgent,
ip: persona.ip,
};
}
function identity(persona: Persona, index: number) {
return index < IDENTIFIED_PERSONAS ? { id: getDistinctId(persona) } : {};
}
function pageview(
website: string,
persona: Persona,
index: number,
page: { url: string; title: string },
extra: Record<string, unknown>,
): SendPayload {
return {
type: 'event',
payload: { website, ...client(persona), ...identity(persona, index), ...page, ...extra },
};
}
function customEvent(
website: string,
persona: Persona,
index: number,
name: string,
data: Record<string, unknown>,
timestamp: number,
): SendPayload {
return {
type: 'event',
payload: {
website,
...client(persona),
...identity(persona, index),
url: '/',
title: 'Home',
name,
data,
timestamp,
},
};
}
export function buildDataset(now = Date.now()): Dataset {
const nowSec = Math.floor(now / 1000);
const range = { startAt: (nowSec - DAYS * DAY) * 1000, endAt: now };
const visits: Visit[] = [];
const batch: SendPayload[] = [];
let pageviews = 0;
let website2Pageviews = 0;
// Backdated traffic: days 1..6 ago (today only receives the live events below).
for (let day = DAYS - 1; day >= 1; day--) {
PERSONAS.forEach((persona, index) => {
const start = nowSec - day * DAY - (index + 1) * HOUR;
const pageCount = 2 + ((day + index) % 3);
const pages = PAGES.slice(0, pageCount);
visits.push({
events: pages.map((page, step) =>
pageview(SEED_IDS.website, persona, index, page, {
url: step === 0 && persona.utm ? `${page.url}?${UTM_QUERY}` : page.url,
referrer: step === 0 && persona.referrer ? persona.referrer : undefined,
tag: persona.tag,
timestamp: start + step * 60,
}),
),
});
pageviews += pages.length;
const afterPages = start + pageCount * 60;
if (day === 2) {
batch.push(
customEvent(
SEED_IDS.website,
persona,
index,
'signup',
{ plan: index % 2 ? 'pro' : 'free', seats: 1 + index },
afterPages,
),
);
}
if (index < IDENTIFIED_PERSONAS && [1, 3, 5].includes(day)) {
batch.push(
customEvent(
SEED_IDS.website,
persona,
index,
'purchase',
{
revenue: 49.5 + index * 10,
currency: CURRENCY,
quantity: 2,
items: ['sku-1', 'sku-2'],
orderedAt: new Date(afterPages * 1000).toISOString(),
premium: index === 0,
},
afterPages + 30,
),
);
}
if (day === 4) {
batch.push(
customEvent(
SEED_IDS.website,
persona,
index,
'download',
{ file: 'guide.pdf' },
afterPages + 60,
),
);
}
if (index < IDENTIFIED_PERSONAS && day === DAYS - 1) {
batch.push({
type: 'identify',
payload: {
website: SEED_IDS.website,
...client(persona),
id: getDistinctId(persona),
data: {
plan: 'pro',
seats: 5 + index,
tags: ['early-adopter', 'newsletter'],
signedUpAt: new Date(afterPages * 1000).toISOString(),
active: true,
},
timestamp: afterPages + 90,
},
});
}
if (day % 2 === 0) {
batch.push({
type: 'performance',
payload: {
website: SEED_IDS.website,
...client(persona),
url: '/',
title: 'Home',
lcp: 1800 + index * 100,
inp: 120 + index * 10,
cls: 0.05,
fcp: 900 + index * 50,
ttfb: 250 + index * 20,
timestamp: start + 5,
},
});
}
});
}
// Secondary website (owned by the regular user): two personas, five days.
for (let day = 5; day >= 1; day--) {
PERSONAS.slice(0, 2).forEach((persona, index) => {
const timestamp = nowSec - day * DAY - (index + 1) * HOUR;
visits.push({
events: [
pageview(SEED_IDS.website2, persona, index, PAGES[day % PAGES.length], { timestamp }),
],
});
website2Pageviews += 1;
});
}
batch.push(
customEvent(
SEED_IDS.website2,
PERSONAS[0],
0,
'purchase',
{ revenue: 19.99, currency: CURRENCY, quantity: 1 },
nowSec - 2 * DAY,
),
);
// Link clicks and pixel hits (sessions are keyed by the link/pixel id).
PERSONAS.slice(0, 5).forEach((persona, index) => {
const timestamp = nowSec - (index + 1) * DAY - 30 * 60;
batch.push({
type: 'event',
payload: { link: SEED_IDS.link, ...client(persona), url: '/', timestamp },
});
batch.push({
type: 'event',
payload: { pixel: SEED_IDS.pixel, ...client(persona), url: '/', timestamp: timestamp + 60 },
});
});
// Live traffic (no timestamp): one recorded visit plus a few realtime pageviews.
const replayPersona = PERSONAS[0];
const replay = {
pageview: pageview(SEED_IDS.website, replayPersona, 0, PAGES[0], {}),
record: {
type: 'record' as const,
payload: {
website: SEED_IDS.website,
events: [
{
type: 4,
data: { href: `https://${HOSTNAME}/`, width: 1280, height: 800 },
timestamp: now,
},
{
type: 2,
data: { node: { type: 0, childNodes: [] }, initialOffset: { left: 0, top: 0 } },
timestamp: now + 10,
},
{
type: 3,
data: { source: 1, positions: [{ x: 10, y: 20, id: 1, timeOffset: 0 }] },
timestamp: now + 20,
},
],
},
},
heatmap: {
type: 'heatmap' as const,
payload: {
website: SEED_IDS.website,
events: [
{
type: 'click',
url: `https://${HOSTNAME}/`,
x: 100,
y: 200,
pageX: 100,
pageY: 200,
pageW: 1280,
pageH: 3000,
viewportW: 1280,
viewportH: 800,
timestamp: now + 30,
},
{
type: 'scroll',
url: `https://${HOSTNAME}/`,
scrollPct: 60,
pageW: 1280,
pageH: 3000,
viewportW: 1280,
viewportH: 800,
timestamp: now + 40,
},
],
},
},
};
pageviews += 1;
const realtime = PERSONAS.slice(1).map((persona, index) =>
pageview(SEED_IDS.website, persona, index + 1, PAGES[index % PAGES.length], {}),
);
pageviews += realtime.length;
return {
range,
visits,
batch,
replay,
realtime,
expected: { pageviews, website2Pageviews },
distinctIds: PERSONAS.slice(0, IDENTIFIED_PERSONAS).map(getDistinctId),
pages: PAGES.map(page => page.url),
eventNames: EVENT_NAMES,
};
}
+27
View File
@@ -0,0 +1,27 @@
/**
* Fixed identifiers for seeded entities. Using fixed UUIDs lets global setup
* find and recreate them on re-runs against a kept stack (`--keep`).
*/
export const SEED_IDS = {
website: '1e5a0000-0000-4000-8000-000000000001',
website2: '1e5a0000-0000-4000-8000-000000000002',
link: '1e5a0000-0000-4000-8000-000000000003',
pixel: '1e5a0000-0000-4000-8000-000000000004',
} as const;
export const SEED_USERS = {
/** Regular user; owns the secondary website. */
user: { username: 'api-user', password: 'api-user-password', role: 'user' },
/** View-only user that owns nothing — used for permission-denied cases. */
viewer: { username: 'api-viewer', password: 'api-viewer-password', role: 'view-only' },
} as const;
export const SEED_WEBSITES = {
primary: { name: 'API Test Website', domain: 'example.test' },
secondary: { name: 'API Test Website (user)', domain: 'user.example.test' },
} as const;
export const SEED_LINK = { name: 'API Test Link', url: 'https://umami.is/', slug: 'apitestlink' };
export const SEED_PIXEL = { name: 'API Test Pixel', slug: 'apitestpixel' };
export const SEED_TEAM = { name: 'API Test Team' };
export const SEED_SHARE = { name: 'API Test Share' };
+88
View File
@@ -0,0 +1,88 @@
import type { ApiClient } from '../client';
import { CACHE_HEADER } from '../helpers/constants';
import type { Dataset, RecordPayload, SendPayload } from './dataset';
export interface IngestResult {
replay: { sessionId: string; visitId: string };
}
const BATCH_LIMIT = 500;
function chunk<T>(items: T[], size: number) {
const chunks: T[][] = [];
for (let i = 0; i < items.length; i += size) {
chunks.push(items.slice(i, i + size));
}
return chunks;
}
async function send(api: ApiClient, event: SendPayload, cache?: string) {
const response = await api.post('/api/send', event, {
headers: cache ? { [CACHE_HEADER]: cache } : undefined,
});
if (response.status !== 200) {
throw new Error(`POST /api/send failed (${response.status}): ${response.text}`);
}
if (response.body?.beep) {
throw new Error(
'POST /api/send classified the request as a bot. Start the server with DISABLE_BOT_CHECK=1.',
);
}
if (!response.body?.cache) {
throw new Error(`POST /api/send returned no cache token: ${response.text}`);
}
return response.body as { cache: string; sessionId: string; visitId: string };
}
async function record(api: ApiClient, payload: RecordPayload, cache: string) {
const response = await api.post('/api/record', payload, { headers: { [CACHE_HEADER]: cache } });
if (response.status !== 200 || response.body?.ok !== true) {
throw new Error(
`POST /api/record (${payload.type}) failed (${response.status}): ${response.text}`,
);
}
}
export async function ingestDataset(api: ApiClient, dataset: Dataset): Promise<IngestResult> {
for (const visit of dataset.visits) {
let cache: string | undefined;
for (const event of visit.events) {
cache = (await send(api, event, cache)).cache;
}
}
for (const items of chunk(dataset.batch, BATCH_LIMIT)) {
const response = await api.post('/api/batch', items);
if (response.status !== 200) {
throw new Error(`POST /api/batch failed (${response.status}): ${response.text}`);
}
if (response.body?.errors) {
throw new Error(
`POST /api/batch reported ${response.body.errors} error(s): ${JSON.stringify(
response.body.details?.slice(0, 3),
)}`,
);
}
}
const live = await send(api, dataset.replay.pageview);
await record(api, dataset.replay.record, live.cache);
await record(api, dataset.replay.heatmap, live.cache);
for (const event of dataset.realtime) {
await send(api, event);
}
return { replay: { sessionId: live.sessionId, visitId: live.visitId } };
}
+262
View File
@@ -0,0 +1,262 @@
import type { ApiClient } from '../client';
import { login } from '../helpers/auth';
import { ADMIN_USER } from '../helpers/constants';
import { assertStatus } from '../helpers/entities';
import { buildDataset, CURRENCY, type Dataset, HOSTNAME } from './dataset';
import {
SEED_IDS,
SEED_LINK,
SEED_PIXEL,
SEED_SHARE,
SEED_TEAM,
SEED_USERS,
SEED_WEBSITES,
} from './ids';
import { type IngestResult, ingestDataset } from './ingest';
import type { SeedCredentials, SeedState } from './state';
const READINESS_TIMEOUT_MS = 60_000;
async function ensureUser(
admin: ApiClient,
credentials: { username: string; password: string; role: string },
): Promise<SeedCredentials> {
const created = await admin.post('/api/users', credentials);
if (created.status === 200) {
return { ...credentials, id: created.body.id };
}
if (created.status !== 400) {
throw new Error(
`Failed to create ${credentials.username} (${created.status}): ${created.text}`,
);
}
// Already exists (re-run against a kept stack): look it up.
const users = assertStatus(
await admin.get('/api/admin/users', { params: { search: credentials.username } }),
200,
'list users',
);
const user = users.body.data?.find((u: any) => u.username === credentials.username);
if (!user) {
throw new Error(`User ${credentials.username} exists but could not be found`);
}
return { ...credentials, id: user.id };
}
async function recreateWebsite(
client: ApiClient,
id: string,
data: { name: string; domain: string },
) {
const existing = await client.get(`/api/websites/${id}`);
// Admins bypass the permission check, so an unknown id yields 200 with a null body.
if (existing.status === 200 && existing.body?.id) {
assertStatus(await client.del(`/api/websites/${id}`), 200, `delete website ${id}`);
}
return assertStatus(await client.post('/api/websites', { id, ...data }), 200, 'create website')
.body;
}
async function ensureEntity(
client: ApiClient,
collection: 'links' | 'pixels',
id: string,
data: Record<string, unknown>,
) {
const existing = await client.get(`/api/${collection}/${id}`);
if (existing.status === 200 && existing.body?.id) {
return existing.body;
}
return assertStatus(
await client.post(`/api/${collection}`, { id, ...data }),
200,
`create ${collection}`,
).body;
}
async function ensureTeam(admin: ApiClient, memberId: string) {
const teams = assertStatus(await admin.get('/api/teams'), 200, 'list teams');
let team = teams.body.data?.find((t: any) => t.name === SEED_TEAM.name);
if (!team) {
const created = assertStatus(await admin.post('/api/teams', SEED_TEAM), 200, 'create team');
team = created.body[0];
}
const detail = assertStatus(await admin.get(`/api/teams/${team.id}`), 200, 'get team').body;
const member = await admin.post(`/api/teams/${team.id}/users`, {
userId: memberId,
role: 'team-member',
});
// 400 = already a member (re-run).
if (member.status !== 200 && member.status !== 400) {
throw new Error(`Failed to add team member (${member.status}): ${member.text}`);
}
return {
id: detail.id as string,
name: detail.name as string,
accessCode: detail.accessCode as string,
};
}
async function poll<T>(label: string, fn: () => Promise<T | undefined>, timeoutMs: number) {
const deadline = Date.now() + timeoutMs;
let last: string | undefined;
while (Date.now() < deadline) {
try {
const result = await fn();
if (result !== undefined) {
return result;
}
} catch (error) {
last = (error as Error).message;
}
await new Promise(resolve => setTimeout(resolve, 500));
}
throw new Error(`Timed out waiting for ${label}${last ? ` (${last})` : ''}`);
}
/**
* Waits until the analytics queries see the ingested data (ClickHouse
* materialized views are synchronous, but this guards against any lag) and
* harvests ids that specs need for path parameters.
*/
async function waitForAnalytics(admin: ApiClient, dataset: Dataset, ingested: IngestResult) {
const websiteId = SEED_IDS.website;
const range = () => ({ startAt: dataset.range.startAt, endAt: Date.now() });
await poll(
`${dataset.expected.pageviews} pageviews on ${websiteId}`,
async () => {
const response = await admin.get(`/api/websites/${websiteId}/stats`, { params: range() });
// /stats returns flat numbers (possibly as strings under Postgres bigint).
const pageviews = Number(response.body?.pageviews ?? 0);
return pageviews >= dataset.expected.pageviews ? pageviews : undefined;
},
READINESS_TIMEOUT_MS,
);
const sessionId = await poll(
'a session',
async () => {
const response = await admin.get(`/api/websites/${websiteId}/sessions`, {
params: { ...range(), pageSize: 1 },
});
return response.body?.data?.[0]?.id as string | undefined;
},
READINESS_TIMEOUT_MS,
);
const eventId = await poll(
'a custom event with data',
async () => {
const response = await admin.get(`/api/websites/${websiteId}/events`, {
params: { ...range(), pageSize: 50, eventType: 2 },
});
const event = response.body?.data?.find((e: any) => e.hasData);
return event?.id as string | undefined;
},
READINESS_TIMEOUT_MS,
);
await poll(
'the recorded replay',
async () => {
const response = await admin.get(`/api/websites/${websiteId}/replays`, {
params: range(),
});
return response.body?.data?.some((r: any) => r.id === ingested.replay.visitId)
? true
: undefined;
},
READINESS_TIMEOUT_MS,
);
return { sessionId, eventId };
}
export async function seedEnvironment(api: ApiClient): Promise<SeedState> {
const db = process.env.UMAMI_TEST_DB === 'clickhouse' ? 'clickhouse' : 'postgres';
const admin = api.bearer(await login(api, ADMIN_USER));
const user = await ensureUser(admin, SEED_USERS.user);
const viewer = await ensureUser(admin, SEED_USERS.viewer);
const userApi = api.bearer(await login(api, SEED_USERS.user));
const website = await recreateWebsite(admin, SEED_IDS.website, SEED_WEBSITES.primary);
const website2 = await recreateWebsite(userApi, SEED_IDS.website2, SEED_WEBSITES.secondary);
assertStatus(
await admin.post(`/api/websites/${website.id}`, {
replayConfig: {
replayEnabled: true,
heatmapEnabled: true,
sampleRate: 1,
heatmapSampleRate: 1,
},
}),
200,
'enable recorder',
);
const share = assertStatus(
await admin.post(`/api/websites/${website.id}/shares`, { ...SEED_SHARE, parameters: {} }),
200,
'create share',
).body;
const link = await ensureEntity(admin, 'links', SEED_IDS.link, SEED_LINK);
const pixel = await ensureEntity(admin, 'pixels', SEED_IDS.pixel, SEED_PIXEL);
const team = await ensureTeam(admin, user.id);
const dataset = buildDataset();
const ingested = await ingestDataset(api, dataset);
const { sessionId, eventId } = await waitForAnalytics(admin, dataset, ingested);
return {
db,
createdAt: new Date().toISOString(),
admin: { ...ADMIN_USER },
user,
viewer,
website: { id: website.id, name: website.name, domain: website.domain },
website2: { id: website2.id, name: website2.name, domain: website2.domain },
link: { id: link.id, name: link.name, url: link.url, slug: link.slug },
pixel: { id: pixel.id, name: pixel.name, slug: pixel.slug },
team,
share: { id: share.id, slug: share.slug },
range: dataset.range,
data: {
hostname: HOSTNAME,
currency: CURRENCY,
pages: dataset.pages,
eventNames: dataset.eventNames,
distinctIds: dataset.distinctIds,
expectedPageviews: dataset.expected.pageviews,
expectedWebsite2Pageviews: dataset.expected.website2Pageviews,
sessionId,
eventId,
replayVisitId: ingested.replay.visitId,
replaySessionId: ingested.replay.sessionId,
},
};
}
+49
View File
@@ -0,0 +1,49 @@
import { readFileSync } from 'node:fs';
import { SEED_FILE } from '../paths';
export interface SeedCredentials {
id: string;
username: string;
password: string;
role: string;
}
/** Written by global setup to tests/api/.runtime/seed.json and read by the fixtures. */
export interface SeedState {
db: 'postgres' | 'clickhouse';
createdAt: string;
admin: SeedCredentials;
user: SeedCredentials;
viewer: SeedCredentials;
/** Admin-owned website carrying the full analytics dataset. */
website: { id: string; name: string; domain: string };
/** Website owned by `user` with a small dataset. */
website2: { id: string; name: string; domain: string };
link: { id: string; name: string; url: string; slug: string };
pixel: { id: string; name: string; slug: string };
team: { id: string; name: string; accessCode: string };
/** Share for `website` granting every section. */
share: { id: string; slug: string };
/** Dataset window in ms. */
range: { startAt: number; endAt: number };
data: {
hostname: string;
currency: string;
pages: string[];
eventNames: string[];
distinctIds: string[];
expectedPageviews: number;
expectedWebsite2Pageviews: number;
/** A session id from `website` (used for /sessions/{sessionId} endpoints). */
sessionId: string;
/** A custom event id with event data (used for /event-data/{eventId}). */
eventId: string;
/** Visit id of the recorded replay (replay ids are visit ids). */
replayVisitId: string;
replaySessionId: string;
};
}
export function readSeedState(): SeedState {
return JSON.parse(readFileSync(SEED_FILE, 'utf8'));
}