testirovanie-robot/test/helpers.ts
Peppa f06fd50865
All checks were successful
peppa/lint lint: success за 0с
peppa/typecheck typecheck: success за 0с
peppa/test test: success за 1с
peppa/build build: success за 0с
ci / checks (pull_request) Successful in 9s
deploy / deploy (pull_request) Successful in 12s
TR-1: окно входа — страница входа, проверка логина и пароля, страница после входа
Каркас на Node.js + TypeScript, тексты на трёх языках, проверки и деплой.
OpenSpec change tr-1-login-window (в архиве).

Rebase на main с принятой TR-2: список пользователей (data/users.json, scrypt)
и блокировка 5 ошибок / 15 минут перенесены в src/users.ts и src/auth.ts,
единственная учётная запись из настроек и пробный вход убраны.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 11:14:49 +05:00

79 lines
2.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { type AppOptions, createApp } from "../src/app.ts";
import { createAuth } from "../src/auth.ts";
import { hashPassword, type User } from "../src/users.ts";
/** Список пользователей для тестов; хеши считаются один раз. */
export const testUsers: User[] = [
{ login: "anna", passwordHash: hashPassword("s3cret-pass") },
{ login: "boris", passwordHash: hashPassword("Boris-pass-2026") },
];
export interface TestApp {
/** Сдвинуть часы приложения вперёд. */
advance(ms: number): void;
get(path: string, headers?: Record<string, string>): Promise<Response>;
post(
path: string,
form: Record<string, string>,
headers?: Record<string, string>,
): Promise<Response>;
/** Войти и вернуть cookie с отметкой о входе. */
signIn(login: string, password: string): Promise<string>;
close(): Promise<void>;
}
/** Значение cookie `name=value` из ответа (без атрибутов). */
export function cookieFrom(response: Response, name: string): string | undefined {
return response.headers
.getSetCookie()
.map((cookie) => cookie.split(";")[0] ?? "")
.find((cookie) => cookie.startsWith(`${name}=`));
}
/** Приложение со списком пользователей: «anna» / «s3cret-pass» и «boris» / «Boris-pass-2026». */
export async function startApp(overrides: Partial<AppOptions> = {}): Promise<TestApp> {
let clock = Date.UTC(2026, 0, 1);
const now = () => clock;
const app = createApp({
auth: createAuth({ users: testUsers, now }),
sessionSecret: Buffer.from("test-session-secret"),
cookieSecure: false,
now,
...overrides,
});
const server: Server = createServer((req, res) => void app(req, res));
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
const get: TestApp["get"] = (path, headers = {}) =>
fetch(base + path, { headers, redirect: "manual" });
const post: TestApp["post"] = (path, form, headers = {}) =>
fetch(base + path, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded", ...headers },
body: new URLSearchParams(form).toString(),
redirect: "manual",
});
return {
advance: (ms) => {
clock += ms;
},
get,
post,
signIn: async (login, password) => {
const response = await post("/login", { login, password });
const cookie = cookieFrom(response, "session");
if (response.status !== 303 || !cookie) throw new Error(`Вход не удался: ${response.status}`);
return cookie;
},
close: () =>
new Promise<void>((resolve) => {
server.close(() => resolve());
server.closeAllConnections();
}),
};
}