Files
TREK/server/tests/helpers/factories/users.ts
T
Maurice 1bba65634c test(server): seed and read test data through ORM factories
The server suite seeds and reads its database through some 5,500 raw
better-sqlite3 statements on the sync handle. They restate the schema by
hand, skip the repositories the app goes through and run on SQLite only,
so nothing in the suite could ever exercise the dialect layer on another
engine.

tests/helpers/factories/ adds typed factories per domain (users, trips and
days, places, assignments, bookings, budget, packing, to-dos, files,
journeys, tours, collections, notifications, settings, plugins, tokens,
atlas, vacay, photos, collab) and generic readers (findRow, findRows,
countRows, updateRows, deleteRows) that go through MikroORM in a request
context of their own, against the app's ORM or a createTestOrm handle.
They refuse a write to a read-only foreign-key twin, which MikroORM would
otherwise drop without a word. The README there is the conversion guide.

The categories integration suite and the tags and calendar-feed e2e suites
are converted in full as worked examples; the tags suite also moves from
hand-rolled tables to the migrated snapshot.

lint:test-sql (scripts/test-sql-ratchet.mjs) holds the raw statements left
to a per-file baseline: growth and stale entries fail, files whose subject
is raw SQL are exempt with a reason, and a single statement can be allowed
with a test-sql-allow comment. CI runs it next to lint:boundaries.
2026-10-08 18:44:39 +02:00

96 lines
3.6 KiB
TypeScript

import type { EntityDTO } from '@mikro-orm/core';
import bcrypt from 'bcryptjs';
import { Users } from '../../../src/db/entities/Users.entity';
import { encrypt_api_key } from '../../../src/nest/common/crypto/apiKeyCrypto';
import { encryptMfaSecret } from '../../../src/nest/common/crypto/mfaCrypto';
import { nextSeq, type FactoryOrm } from './context';
import { createRow, findRow, updateRows } from './rows';
export type UserRow = EntityDTO<Users>;
export interface UserOverrides {
/** Pin the id, for suites whose session cookie is signed for a fixed user. */
id?: number;
username?: string;
email?: string;
password?: string;
role?: 'admin' | 'user';
password_version?: number;
is_guest?: number;
display_name?: string | null;
must_change_password?: number;
}
/**
* A user with a known password, stored as a bcrypt hash at cost 4 so tests
* stay fast. Defaults are unique per worker: `testuser<n>`,
* `user<n>@test.example.com`, `TestPass<n>!`.
*/
export async function makeUser(
orm: FactoryOrm,
overrides: UserOverrides = {},
): Promise<{ user: UserRow; password: string }> {
const n = nextSeq('user');
const password = overrides.password ?? `TestPass${n}!`;
const user = await createRow(orm, Users, {
...(overrides.id !== undefined ? { id: overrides.id } : {}),
username: overrides.username ?? `testuser${n}`,
email: overrides.email ?? `user${n}@test.example.com`,
password_hash: bcrypt.hashSync(password, 4),
role: overrides.role ?? 'user',
password_version: overrides.password_version ?? 0,
is_guest: overrides.is_guest ?? 0,
display_name: overrides.display_name ?? null,
must_change_password: overrides.must_change_password ?? 0,
});
return { user, password };
}
export function makeAdmin(
orm: FactoryOrm,
overrides: Omit<UserOverrides, 'role'> = {},
): Promise<{ user: UserRow; password: string }> {
return makeUser(orm, { ...overrides, role: 'admin' });
}
/** The fixed base32 TOTP secret `makeUserWithMfa` enables, so a test can compute valid codes. */
export const KNOWN_MFA_SECRET = 'JBSWY3DPEHPK3PXP';
/** A user with MFA already on, written directly so no rate-limited endpoint is involved. */
export async function makeUserWithMfa(
orm: FactoryOrm,
overrides: UserOverrides = {},
): Promise<{ user: UserRow; password: string; totpSecret: string }> {
const { user, password } = await makeUser(orm, overrides);
await updateRows(orm, Users, { id: user.id }, { mfa_enabled: 1, mfa_secret: encryptMfaSecret(KNOWN_MFA_SECRET) });
return { user: await readUser(orm, user.id), password, totpSecret: KNOWN_MFA_SECRET };
}
/** The user row as it is now; fails the test when it is gone. */
export async function readUser(orm: FactoryOrm, id: number): Promise<UserRow> {
const row = await findRow(orm, Users, { id });
if (!row) throw new Error(`readUser: no user ${id}`);
return row;
}
/** Immich credentials, with the API key encrypted the way the settings route stores it. */
export async function setImmichCredentials(orm: FactoryOrm, userId: number, url: string, apiKey: string): Promise<void> {
await updateRows(orm, Users, { id: userId }, { immich_url: url, immich_api_key: encrypt_api_key(apiKey) });
}
/** Synology credentials, with the password encrypted the way the settings route stores it. */
export async function setSynologyCredentials(
orm: FactoryOrm,
userId: number,
url: string,
username: string,
password: string,
): Promise<void> {
await updateRows(
orm,
Users,
{ id: userId },
{ synology_url: url, synology_username: username, synology_password: encrypt_api_key(password) },
);
}