Files
olehhapuk 98b2e0ce4b
CI / Lint, types, build, tests (push) Canceled after 0s
CI / Docker images build (push) Canceled after 0s
update
2026-12-03 10:53:09 +02:00

273 lines
8.5 KiB
TypeScript

import { randomUUID } from 'node:crypto';
import { INestApplication } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { getDrizzleToken } from '@nestjs/drizzle';
import { Test, type TestingModuleBuilder } from '@nestjs/testing';
import type {
AttachmentUpload,
ClientToServerEvents,
CreateAttachment,
ServerToClientEvents,
} from '@repo/contracts';
import { and, eq, inArray, isNull, like, notExists } from 'drizzle-orm';
import { io, type Socket } from 'socket.io-client';
import request from 'supertest';
import type { App } from 'supertest/types';
import { AppModule } from '../src/app.module';
import type { Env } from '../src/config/env';
import type { Database } from '../src/db/database';
import { setUpHttp } from '../src/setup';
import {
attachment,
conversation,
conversationMember,
user,
} from '../src/db/schema';
export type TestApp = INestApplication<App>;
export type Agent = ReturnType<typeof request.agent>;
export interface TestUser {
id: string;
name: string;
username: string;
/** Sends requests as this user. */
agent: Agent;
/** The session cookie, for clients that aren't supertest (sockets). */
cookie: string;
}
/**
* The whole app, as main.ts starts it. `adjust` can swap providers for
* stand-ins before it is put together.
*/
export async function createTestApp(
adjust: (builder: TestingModuleBuilder) => TestingModuleBuilder = (builder) =>
builder,
): Promise<TestApp> {
const moduleFixture = await adjust(
Test.createTestingModule({ imports: [AppModule] }),
).compile();
// Same option as main.ts: Better Auth reads the raw body itself.
const app = moduleFixture.createNestApplication<TestApp>({
bodyParser: false,
});
setUpHttp(app);
await app.init();
return app;
}
/**
* Creates accounts in the local database for one spec file. Each file passes
* its own email domain, and `cleanup()` deletes every account under it (and,
* through cascades, everything those accounts own), then the conversations
* that are left with no members.
*/
export class TestAccounts {
// Spec files run side by side and may start in the same millisecond, so
// the time alone wouldn't keep their usernames apart.
private readonly run =
Date.now().toString(36) + randomUUID().replaceAll('-', '').slice(0, 4);
private readonly password = randomUUID();
private readonly origin: string;
constructor(
private readonly app: TestApp,
private readonly emailDomain: string,
) {
[this.origin] = app
.get<ConfigService<Env, true>>(ConfigService)
.getOrThrow('TRUSTED_ORIGINS', { infer: true });
}
emailOf(name: string) {
return `${name.toLowerCase()}-${this.run}${this.emailDomain}`;
}
/** A username that is unique to this run, e.g. "alice_m1x2y3". */
usernameOf(name: string) {
return `${name.toLowerCase()}_${this.run}`;
}
/** The raw sign-up request, for asserting on refusals. */
requestSignUp(agent: Agent, name: string, username?: string) {
return agent
.post('/api/auth/sign-up/email')
.set('Origin', this.origin)
.send({
name,
email: this.emailOf(name),
password: this.password,
username,
});
}
async signUp(name: string): Promise<TestUser> {
const agent = request.agent(this.app.getHttpServer());
const username = this.usernameOf(name);
const response = await this.requestSignUp(agent, name, username).expect(
200,
);
const setCookie = response.get('Set-Cookie') ?? [];
return {
id: response.body.user.id,
name,
username,
agent,
cookie: setCookie.map((cookie) => cookie.split(';')[0]).join('; '),
};
}
signOut(account: TestUser) {
return account.agent
.post('/api/auth/sign-out')
.set('Origin', this.origin)
.send({});
}
async cleanup() {
const db = this.app.get<Database>(getDrizzleToken());
const accounts = db
.select({ id: user.id })
.from(user)
.where(like(user.email, `%${this.emailDomain}`));
// Attachments outlive their uploader (for a day, until the cleanup), so
// these go first, while they can still be told apart.
await db.delete(attachment).where(inArray(attachment.uploaderId, accounts));
await db.delete(user).where(like(user.email, `%${this.emailDomain}`));
// Deleting a user removes their memberships and messages, not the
// conversation row itself. Cauldrons never have members and go with
// their realm, so they are left alone (another spec may be using them).
await db
.delete(conversation)
.where(
and(
isNull(conversation.realmId),
notExists(
db
.select()
.from(conversationMember)
.where(eq(conversationMember.conversationId, conversation.id)),
),
),
);
}
}
/** Makes two accounts friends: one asks, the other accepts. */
export async function befriend(asker: TestUser, answerer: TestUser) {
await asker.agent
.post('/friends/requests')
.send({ username: answerer.username })
.expect(201);
await answerer.agent.post(`/friends/requests/${asker.id}/accept`).expect(204);
}
/** Asks for an upload the way the web app does, without sending the file. */
export async function requestUpload(
account: TestUser,
file: CreateAttachment,
): Promise<AttachmentUpload> {
return (await account.agent.post('/attachments').send(file).expect(201)).body;
}
/**
* Sends bytes to a signed upload address. No session goes along: the
* signature in the address is what lets the request in.
*/
export function putFile(
app: TestApp,
{ upload }: AttachmentUpload,
bytes: Buffer,
) {
const { pathname, search } = new URL(upload.url);
return (
request(app.getHttpServer())
.put(pathname + search)
.set(upload.headers)
// As they are: left alone, the client would rewrite the bytes of a file
// whose type is JSON.
.serialize(() => bytes as unknown as string)
.send(bytes)
);
}
/** Uploads a file in full; answers with the id to list in a message. */
export async function uploadFile(
app: TestApp,
account: TestUser,
file: Omit<CreateAttachment, 'size'>,
bytes: Buffer,
): Promise<string> {
const upload = await requestUpload(account, { ...file, size: bytes.length });
await putFile(app, upload, bytes).expect(200);
return upload.attachment.id;
}
export type ClientSocket = Socket<ServerToClientEvents, ClientToServerEvents>;
/** Starts the app on a free port and returns its address, for sockets. */
export async function listen(app: TestApp): Promise<string> {
await app.listen(0);
return (await app.getUrl()).replace('[::1]', '127.0.0.1');
}
/** Opens sockets to a listening test app and closes them all at the end. */
export class TestSockets {
private readonly sockets: ClientSocket[] = [];
constructor(private readonly url: string) {}
/** Opens a socket the way a browser would, with the session cookie. */
connect(cookie?: string, headers: Record<string, string> = {}): ClientSocket {
const socket: ClientSocket = io(this.url, {
transports: ['websocket'],
forceNew: true,
reconnection: false,
extraHeaders: { ...(cookie ? { cookie } : {}), ...headers },
});
this.sockets.push(socket);
return socket;
}
/** A socket for this account, once the API has let it in. */
async connectAs(account: TestUser): Promise<ClientSocket> {
const socket = this.connect(account.cookie);
await connected(socket);
return socket;
}
closeAll() {
for (const socket of this.sockets) socket.disconnect();
}
}
/** Resolves when the API accepts the socket; rejects when it refuses. */
export function connected(socket: ClientSocket) {
return new Promise<void>((resolve, reject) => {
socket.once('connect', resolve);
socket.once('connect_error', reject);
});
}
/** Resolves with the next event's first argument (undefined if none). */
export function nextEvent<Event extends keyof ServerToClientEvents>(
socket: ClientSocket,
event: Event,
) {
return new Promise<Parameters<ServerToClientEvents[Event]>[0]>(
(resolve, reject) => {
const timer = setTimeout(
() => reject(new Error(`No "${event}" event within 2s`)),
2000,
);
// The cast: TypeScript can't relate the listener of a generic event
// name to that event's own signature.
socket.once(event, ((payload?: unknown) => {
clearTimeout(timer);
resolve(payload as Parameters<ServerToClientEvents[Event]>[0]);
}) as never);
},
);
}