testirovanie-robot/test/helpers.ts
Peppa 00ce7ff313
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 7s
deploy / deploy (pull_request) Successful in 8s
TR-1: окно входа — страница входа, проверка логина и пароля, страница после входа
Каркас на Node.js + TypeScript, тексты на трёх языках, проверки и деплой.
OpenSpec change tr-1-login-window (в архиве).

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

66 lines
2.4 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";
export interface TestApp {
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» (если не указано иное). */
export async function startApp(overrides: Partial<AppOptions> = {}): Promise<TestApp> {
const clock = Date.UTC(2026, 0, 1);
const app = createApp({
account: { login: "anna", password: "s3cret-pass" },
mockAuth: false,
sessionSecret: Buffer.from("test-session-secret"),
cookieSecure: false,
now: () => clock,
...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 {
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();
}),
};
}