Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
| JS Playwright | `/js-playwright` | Фиксированные коллекции |
| HTTP для автоматизации | `/http-for-automation` | Отдельные опыты с сессиями, кешем, вебхуками и ошибками |
| Автоматизация рабочих процессов | `/workflow-automation` | Динамические заказы отдельного учебного магазина |
| Асинхронность в Python | `/python-async` | Две фиксированные книги без состояния |

Префиксы приложений для Selenium и Playwright перечислены ниже. При добавлении или изменении набора запускается полный `mise run check`, чтобы проверить контракты всех курсов.

Expand All @@ -40,6 +41,17 @@

Магазин живёт 24 часа и хранит до 300 заказов, одновременно доступны 200 магазинов. При достижении лимита заказов новый опрос возвращает 429, чтение и обработка уже созданных заказов остаются доступны. При истечении срока или перезапуске сервера магазин исчезает и запрос возвращает 404. В этих случаях создаётся новый магазин. Данные хранятся в памяти и изолированы от других магазинов и префиксов курсов. Ответы имеют `Cache-Control: no-store`.

## Книги для курса «Асинхронность в Python»

Страница `/python-async` ведёт на опыты курса. Ответы цитирует урок «Асинхронные HTTP-запросы» курса `python_asynchronous_programming_course`, поэтому значения полей менять нельзя. Набор данных фиксирован, состояния нет.

| Метод и путь | Ответ |
| --- | --- |
| `GET /python-async/books/1` | 200, `{"id": 1, "title": "Python"}` |
| `GET /python-async/books/2` | 200, `{"id": 2, "title": "Asyncio"}` |
| `GET /python-async/books/{id}` с любым другим или нечисловым `id` | 404, `{"error": "Book not found"}` |
| Любой другой метод на `/python-async/books/{id}` | 405 с заголовком `Allow` от `fastify-allow` |

## Примеры форматов тела

Урок `body-formats` курса HTTP для автоматизации использует следующие адреса. Обработчики показывают полученные данные без сохранения задач.
Expand Down
1 change: 1 addition & 0 deletions custom-server/assets/main/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ <h1>It works!</h1>
<li><a href="/js-playwright-openapi">JS Playwright</a></li>
<li><a href="/postman-openapi">Postman</a></li>
<li><a href="/python-playwright">Python Playwright</a></li>
<li><a href="/python-async">Python Async</a></li>
</ul>
</body>
</html>
16 changes: 16 additions & 0 deletions custom-server/assets/python-async/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Example</title>
</head>
<body>
<h1>It works!</h1>
<ul>
<li><a href="/python-async/books/1">Book 1</a></li>
<li><a href="/python-async/books/2">Book 2</a></li>
<li><a href="/python-async/books/99">Book 99 (404)</a></li>
</ul>
</body>
</html>
2 changes: 2 additions & 0 deletions custom-server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import setUpRpc from './rpc.ts';
import setUpBodyExamples from './body-examples.ts';
import setUpUiPages from './ui-pages.ts';
import setUpPythonPlaywright from './python-playwright.ts';
import setUpPythonAsync from './python-async.ts';
import setUpSessionCacheExamples from './session-cache-examples.ts';
import setUpWebhookExamples from './webhook-examples.ts';
import setUpReliabilityExamples from './reliability-examples.ts';
Expand Down Expand Up @@ -121,6 +122,7 @@ export default async (app: FastifyInstance, _options: unknown) => {
await app.register(setUpBodyExamples);
await app.register(setUpUiPages);
await app.register(setUpPythonPlaywright);
await app.register(setUpPythonAsync);
await app.register(setUpSessionCacheExamples);
await app.register(setUpWebhookExamples);
await app.register(setUpReliabilityExamples);
Expand Down
24 changes: 24 additions & 0 deletions custom-server/src/python-async.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import type { FastifyInstance } from 'fastify';

// Маршруты курса «Асинхронность в Python». Ответы цитирует урок «Асинхронные
// HTTP-запросы» курса python_asynchronous_programming_course, поэтому данные это
// текст курса. Набор фиксирован и состояния нет: запросы студентов не влияют друг
// на друга.

const prefix = '/python-async';

export const books = [
{ id: 1, title: 'Python' },
{ id: 2, title: 'Asyncio' },
];

export default async function setUpPythonAsync(server: FastifyInstance) {
server.get(prefix, (_req, res) => res.sendFile('python-async/index.html'));

server.get(`${prefix}/books/:id`, (req, res) => {
const { id } = req.params as { id: string };
const book = books.find((item) => String(item.id) === id);
if (!book) return res.code(404).send({ error: 'Book not found' });
return book;
});
}
22 changes: 14 additions & 8 deletions test/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ describe('контракт с fastify-cli', () => {
});
});

// Ссылки, которые страницы курсов дают ради показа 404.
const demoNotFound = ['/python-async/books/99'];

describe('документация и статика', () => {
it.each(appConfig.apps)('/%s-openapi отдаёт swagger-ui', async (name) => {
const reply = await client.send(`/${name}-${appConfig.docRoute}`);
Expand All @@ -34,14 +37,17 @@ describe('документация и статика', () => {
expect((await client.send('/')).status).toBe(200);
});

it.each(['/', '/http-for-automation', '/workflow-automation'])('ссылки со страницы %s живые', async (page) => {
const html = String((await client.send(page)).body);
const links = [...html.matchAll(/href="([^"]+)"/g)].map((match) => match[1]);
expect(links.length).toBeGreaterThan(0);
for (const link of links) {
expect({ link, status: (await client.send(link)).status }).not.toEqual({ link, status: 404 });
}
});
it.each(['/', '/http-for-automation', '/workflow-automation', '/python-async'])(
'ссылки со страницы %s живые',
async (page) => {
const html = String((await client.send(page)).body);
const links = [...html.matchAll(/href="([^"]+)"/g)].map((match) => match[1]);
expect(links.length).toBeGreaterThan(0);
for (const link of links.filter((item) => !demoNotFound.includes(item))) {
expect({ link, status: (await client.send(link)).status }).not.toEqual({ link, status: 404 });
}
},
);

it('несуществующий адрес → 404 с кодом в теле', async () => {
const reply = await client.send('/nosuch');
Expand Down
58 changes: 58 additions & 0 deletions test/python-async.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import type { FastifyInstance } from 'fastify';

import { buildApp, createClient } from './helpers.ts';

let app: FastifyInstance;
let client: ReturnType<typeof createClient>;

beforeAll(async () => {
app = await buildApp();
client = createClient(app);
});

afterAll(() => app.close());

const prefix = '/python-async';

describe('/python-async/books', () => {
it.each([
[1, 'Python'],
[2, 'Asyncio'],
])('книга %i → 200 с названием %s', async (id, title) => {
const reply = await client.send(`${prefix}/books/${id}`);
expect(reply.status).toBe(200);
expect(String(reply.headers['content-type'])).toContain('application/json');
expect(reply.body).toEqual({ id, title });
});

it.each(['99', 'abc', '0', '1.5'])('книга %s → 404', async (id) => {
const reply = await client.send(`${prefix}/books/${id}`);
expect(reply.status).toBe(404);
expect(String(reply.headers['content-type'])).toContain('application/json');
expect(reply.body).toEqual({ error: 'Book not found' });
});

// 405 даёт fastify-allow, как и у остальных ручных маршрутов.
it('POST → 405 с Allow и набор не меняется', async () => {
const reply = await client.json(`${prefix}/books/1`, 'POST', { title: 'Other' });
expect(reply.status).toBe(405);
expect(String(reply.headers.allow)).toContain('GET');
expect((await client.send(`${prefix}/books/1`)).body).toEqual({ id: 1, title: 'Python' });
});

// В текстах курсов адрес пишется без слеша.
it('трейлинг-слеш → 404', async () => {
expect((await client.send(`${prefix}/books/1/`)).status).toBe(404);
});
});

describe('страница /python-async', () => {
it('ведёт на три адреса книг', async () => {
const reply = await client.send(prefix);
expect(reply.status).toBe(200);
for (const id of [1, 2, 99]) {
expect(reply.body).toContain(`href="${prefix}/books/${id}"`);
}
});
});
Loading