From ed8a5e62f79703e528b4d33b060f515c7cb281e5 Mon Sep 17 00:00:00 2001 From: Nikolay Gagarinov Date: Wed, 18 Nov 2026 21:54:42 +0500 Subject: [PATCH] =?UTF-8?q?feat(python-async):=20=D0=BC=D0=B0=D1=80=D1=88?= =?UTF-8?q?=D1=80=D1=83=D1=82=D1=8B=20=D0=BA=D0=BD=D0=B8=D0=B3=20=D0=B4?= =?UTF-8?q?=D0=BB=D1=8F=20=D0=BA=D1=83=D1=80=D1=81=D0=B0=20=C2=AB=D0=90?= =?UTF-8?q?=D1=81=D0=B8=D0=BD=D1=85=D1=80=D0=BE=D0=BD=D0=BD=D0=BE=D1=81?= =?UTF-8?q?=D1=82=D1=8C=20=D0=B2=20Python=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GET /python-async/books/{id} отдаёт две фиксированные книги и 404 для остальных id. Урок «Асинхронные HTTP-запросы» перестаёт поднимать локальный сервер и ходит сюда. Добавлены страница курса, строка на главной, тесты и контракт в README. Refs: CONTENT-676 Co-Authored-By: Claude Opus 5.5 --- README.md | 12 ++++ custom-server/assets/main/index.html | 1 + custom-server/assets/python-async/index.html | 16 ++++++ custom-server/src/index.ts | 2 + custom-server/src/python-async.ts | 24 ++++++++ test/app.test.ts | 22 +++++--- test/python-async.test.ts | 58 ++++++++++++++++++++ 7 files changed, 127 insertions(+), 8 deletions(-) create mode 100644 custom-server/assets/python-async/index.html create mode 100644 custom-server/src/python-async.ts create mode 100644 test/python-async.test.ts diff --git a/README.md b/README.md index 39ad7ed..6cf5b38 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ | JS Playwright | `/js-playwright` | Фиксированные коллекции | | HTTP для автоматизации | `/http-for-automation` | Отдельные опыты с сессиями, кешем, вебхуками и ошибками | | Автоматизация рабочих процессов | `/workflow-automation` | Динамические заказы отдельного учебного магазина | +| Асинхронность в Python | `/python-async` | Две фиксированные книги без состояния | Префиксы приложений для Selenium и Playwright перечислены ниже. При добавлении или изменении набора запускается полный `mise run check`, чтобы проверить контракты всех курсов. @@ -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 для автоматизации использует следующие адреса. Обработчики показывают полученные данные без сохранения задач. diff --git a/custom-server/assets/main/index.html b/custom-server/assets/main/index.html index fa347f7..c7d6ef0 100644 --- a/custom-server/assets/main/index.html +++ b/custom-server/assets/main/index.html @@ -16,6 +16,7 @@

It works!

  • JS Playwright
  • Postman
  • Python Playwright
  • +
  • Python Async
  • diff --git a/custom-server/assets/python-async/index.html b/custom-server/assets/python-async/index.html new file mode 100644 index 0000000..bfada0a --- /dev/null +++ b/custom-server/assets/python-async/index.html @@ -0,0 +1,16 @@ + + + + + + Example + + +

    It works!

    + + + diff --git a/custom-server/src/index.ts b/custom-server/src/index.ts index f9dd4af..f49dd61 100644 --- a/custom-server/src/index.ts +++ b/custom-server/src/index.ts @@ -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'; @@ -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); diff --git a/custom-server/src/python-async.ts b/custom-server/src/python-async.ts new file mode 100644 index 0000000..f79d567 --- /dev/null +++ b/custom-server/src/python-async.ts @@ -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; + }); +} diff --git a/test/app.test.ts b/test/app.test.ts index 0e32110..e532ffa 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -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}`); @@ -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'); diff --git a/test/python-async.test.ts b/test/python-async.test.ts new file mode 100644 index 0000000..78eab8f --- /dev/null +++ b/test/python-async.test.ts @@ -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; + +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}"`); + } + }); +});