chore: carry over lab 1 solution into lab 2 skeleton
Copy the committed lab 1 sources as-is: src/, student-tests/, bench/, Dockerfile, docker-compose.yml, pyproject.toml, uv.lock, .python-version, config_example.toml, AGENTS.md, CLAUDE.md, .claude/, openspec/, .graphifyignore and KNOWN_ISSUES.md. Lab 1 evidence stays in the lab 1 repository. Merge the new skeleton files with own sections: Makefile (lab 2 targets plus own run, docker, bench and common targets), .gitignore, .dockerignore and .env.example. Rename the image to mtusi-messenger:lab2 and point AGENTS.md at lab 2. The application is still the in-memory lab 1 implementation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,173 @@
|
||||
---
|
||||
name: run-mtusi-messenger
|
||||
description: Запустить, остановить, прогнать и подёргать API мессенджера MTUSI (FastAPI, in-memory, лаба 1) — на хосте или в Docker. Use when asked to run / start / stop the server or the container, run the smoke test, `make test` or `make student_test`, check that an API change works on a live server, send a request to an endpoint, reproduce a bug over HTTP, check the container, or call services directly without HTTP.
|
||||
---
|
||||
|
||||
REST API мессенджера (пользователи, чаты, сообщения) — сервер на
|
||||
FastAPI/uvicorn, состояние в памяти процесса. Агент управляет им через
|
||||
`.claude/skills/run-mtusi-messenger/driver.py`: он поднимает свой
|
||||
экземпляр в фоне, гоняет сценарий по HTTP, публичный smoke и
|
||||
собственные тесты, шлёт одиночные запросы и останавливает сервер.
|
||||
Против контейнера (`make run_docker`) работают те же команды драйвера,
|
||||
кроме `start`/`stop`. Только стандартная библиотека Python.
|
||||
|
||||
Все пути — от корня репозитория. Проверено на macOS (arm64), uv 0.12,
|
||||
Python 3.12 из `.python-version`, Docker Desktop 29.8.
|
||||
|
||||
## Setup
|
||||
|
||||
```bash
|
||||
uv sync --all-extras # venv с ruff и dev-группой (openapi-spec-validator)
|
||||
make env_setup # .env и config.toml из шаблонов, существующие не трогает
|
||||
```
|
||||
|
||||
Без `.env` и `config.toml` сервер тоже поднимается — на дефолтах
|
||||
(порт 8080, `INFO`).
|
||||
|
||||
## Run (agent path)
|
||||
|
||||
```bash
|
||||
D=.claude/skills/run-mtusi-messenger/driver.py
|
||||
python3 $D all # start → flow → tests/smoke.py → student-tests → stop; код 0 = всё прошло
|
||||
```
|
||||
|
||||
По шагам, когда между ними нужно что-то сделать (поправить код,
|
||||
посмотреть лог, послать свой запрос):
|
||||
|
||||
```bash
|
||||
python3 $D start # фон, ждёт /health/ready до 30 с
|
||||
python3 $D status # listeners: [pid reloader, pid worker], ready: True
|
||||
python3 $D flow # ~35 проверок: регистрация, 409, /me, 401, чат, 5 сообщений,
|
||||
# пагинация limit=2 по курсору, чужой → 404, 400-е, X-Request-Id
|
||||
python3 $D req POST /api/v1/users --data '{"username":"zoe_demo","display_name":"Зоя"}'
|
||||
python3 $D req GET /api/v1/users/me --user <uuid из ответа выше>
|
||||
python3 $D smoke # публичный tests/smoke.py против этого порта
|
||||
python3 $D student # make student_test BASE_URL=http://localhost:<port> — 79 тестов, <1 с
|
||||
python3 $D stop
|
||||
```
|
||||
|
||||
| команда | что делает |
|
||||
|---|---|
|
||||
| `start` | `APP__RUN_MODE=console APP__PORT=<port> uv run python -m src` в своей группе процессов |
|
||||
| `status` | кто слушает порт, отвечает ли `/health/ready`; код 1, если никого |
|
||||
| `flow` | сквозной сценарий; `[FAIL]` в строке и код 1 при провале; в конце печатает id alice/bob/eve/chat |
|
||||
| `req METHOD PATH [--user UUID] [--data JSON]` | один запрос: статус, `x-request-id`, тело; код 2 при статусе ≥ 400 |
|
||||
| `smoke` | `tests/smoke.py --base-url http://localhost:<port>` |
|
||||
| `student` | `make student_test BASE_URL=http://localhost:<port>` (pytest по `student-tests/`); код 1, если каталога нет |
|
||||
| `stop` | SIGTERM всей группе; ждёт, пока порт освободится. Чужой сервер и контейнер не трогает |
|
||||
| `all` | всё подряд (`student` — если есть `student-tests/`), `stop` в `finally` |
|
||||
|
||||
- Порт по умолчанию **18080**, другой — `--port N` **перед** командой:
|
||||
`python3 $D --port 18081 start`.
|
||||
- Лог сервера (JSON, одна строка на запрос) — `/tmp/mtusi-api-<port>.log`,
|
||||
pid группы — `/tmp/mtusi-api-<port>.pid`.
|
||||
- `make test BASE_URL=http://localhost:18080` работает так же, как
|
||||
`driver.py smoke`.
|
||||
|
||||
## Run: контейнер (compose)
|
||||
|
||||
Образ `mtusi-messenger:lab1`, compose-сервис `api`. Внешний порт —
|
||||
аргументом make, чтобы не столкнуться с 8080:
|
||||
|
||||
```bash
|
||||
make run_docker APP_OUT_PORT=18090 # build + up -d; healthy за ~2 с
|
||||
docker compose ps --format '{{.Name}} {{.Ports}} {{.Status}}'
|
||||
python3 $D --port 18090 flow # те же проверки против контейнера
|
||||
python3 $D --port 18090 smoke
|
||||
docker compose logs --no-log-prefix api | tail -5 # JSON-строки, без -f
|
||||
docker compose restart api # рестарт = пустое состояние: старые X-User-Id → 401
|
||||
make down # остановить и удалить, ~0,5 с
|
||||
```
|
||||
|
||||
`make run_docker` сам создаёт недостающие `.env` и `config.toml`
|
||||
(`env_setup`) и монтирует `config.toml` только для чтения. Готовность —
|
||||
`docker inspect -f '{{.State.Health.Status}}' $(docker compose ps -q api)`
|
||||
→ `healthy`.
|
||||
|
||||
## Direct invocation (без HTTP)
|
||||
|
||||
Для правок в `src/core/` сервисы вызываются поверх `MemoryStore`, сервер
|
||||
не нужен. `APP__LOG_LEVEL=WARNING` убирает JSON-логи сервисов из вывода:
|
||||
|
||||
```bash
|
||||
APP__LOG_LEVEL=WARNING uv run python - <<'EOF'
|
||||
import asyncio
|
||||
from src.infra.memory import MemoryStore
|
||||
from src.core.services import UserService
|
||||
|
||||
async def main():
|
||||
users = UserService(store=MemoryStore())
|
||||
user = await users.register(username="alice", display_name="Alice")
|
||||
print(await users.identify(raw_user_id=str(user.id)))
|
||||
|
||||
asyncio.run(main())
|
||||
EOF
|
||||
```
|
||||
|
||||
`ChatService` и `MessageService` создаются так же (`store=...`), все
|
||||
методы keyword-only. Ошибки — доменные исключения из `src.core.exceptions`
|
||||
(базовый `DomainError`), не HTTP-коды: `identify(raw_user_id="not-a-uuid")`
|
||||
бросает `Unidentified`.
|
||||
|
||||
## Run (human path)
|
||||
|
||||
```bash
|
||||
make run_dev # 127.0.0.1:8080, reload по src/; Ctrl-C
|
||||
```
|
||||
|
||||
Блокирует терминал — агенту не подходит, используй `driver.py start`.
|
||||
|
||||
## Test
|
||||
|
||||
```bash
|
||||
make check # офлайн-структура skeleton
|
||||
python3 $D all # живой сервер + flow + smoke + student-tests
|
||||
make lint # ruff; затрагивает и driver.py
|
||||
```
|
||||
|
||||
Ожидаемо: `PASS: offline skeleton structure...`, `FAILED: none`,
|
||||
`PASS: lab1 public API scenario...`, `79 passed`, `All checks passed!`.
|
||||
|
||||
## Gotchas
|
||||
|
||||
- **На 8080 обычно уже работает `make run_dev` пользователя.** Поэтому
|
||||
драйвер по умолчанию на 18080. `driver.py --port 8080 stop` чужой
|
||||
сервер не убьёт (нет pid-файла → `left running`, код 1) — и не надо:
|
||||
в его памяти данные пользователя.
|
||||
- **Правка любого файла в `src/` (хватает `touch`) перезапускает worker
|
||||
и стирает всё состояние** — в логе `WatchFiles detected changes ...
|
||||
Reloading...`. Задевает и `make run_dev` на 8080. Старые `X-User-Id`
|
||||
после этого дают 401. После правки кода: `flow` заново, а не `req` со
|
||||
старыми id.
|
||||
- **`lsof` на порт показывает два PID** — reloader и worker делят один
|
||||
сокет. Убивать по `lsof -t | xargs kill` бессмысленно: reloader
|
||||
поднимет worker снова. Драйвер шлёт SIGTERM группе процессов; SIGTERM
|
||||
на обёртку `uv run` тоже гасит всё дерево.
|
||||
- **`uv sync` без `--all-extras` удалит ruff из `.venv`** (`Would
|
||||
uninstall ruff`): ruff в extra `dev`, а `make lint` и PyCharm им
|
||||
пользуются.
|
||||
- **`make lint` форматирует и `.claude/skills/`** — ruff в
|
||||
`pyproject.toml` исключает только `tests` и `scripts`. Драйвер написан
|
||||
под 79 колонок и COM812; при правке проверять
|
||||
`ruff format --check .claude/skills/run-mtusi-messenger/driver.py`.
|
||||
- **`.env` задаёт `APP__PORT=8080`, но драйвер его перекрывает**:
|
||||
`start` передаёт `APP__PORT=<port>` в окружении, а окружение важнее
|
||||
`.env`. `APP_OUT_PORT` приложение не читает — это порт публикации
|
||||
контейнера.
|
||||
- **`driver.py stop` контейнер не останавливает** (`not ours (no pid
|
||||
file)`, код 1) — это правильно, гасить его `make down`. `status` для
|
||||
контейнера показывает один PID — процесс Docker Desktop, а не uvicorn.
|
||||
- **`make logs` висит** (`logs -f`) — агенту нужен
|
||||
`docker compose logs --no-log-prefix api` без `-f`.
|
||||
- **`req` без `--user` на защищённом пути даёт 401 `unauthorized`** — это
|
||||
не сломанный сервер, а контракт: идентификация раньше доступа.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- **`port 8080 is not ours (no pid file); left running`** — `stop` на
|
||||
порту, который поднимал не драйвер. Свой экземпляр гасить `stop` на его
|
||||
порту; чужой не трогать. Чей он — `lsof -nP -iTCP:8080 -sTCP:LISTEN`,
|
||||
затем `ps -o pid,ppid,etime,command -p <pid>`.
|
||||
- **`req GET /api/v1/users/me --user <id>` вдруг даёт 401, хотя минуту
|
||||
назад было 200** — сервер перезагрузился после правки в `src/` и
|
||||
потерял пользователей (см. Gotchas).
|
||||
@@ -0,0 +1,355 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Драйвер API мессенджера для агента: запуск, сценарий, запросы, остановка.
|
||||
|
||||
Только стандартная библиотека. Запускать из корня репозитория:
|
||||
|
||||
python3 .claude/skills/run-mtusi-messenger/driver.py [--port N] <cmd>
|
||||
|
||||
Команды:
|
||||
start поднять `python -m src` в фоне (console, reload) и дождаться
|
||||
/health/ready; лог и pid — /tmp/mtusi-api-<port>.{log,pid}
|
||||
status кто слушает порт и что отвечает /health/ready
|
||||
flow сквозной сценарий по HTTP с проверками; код выхода 1 при провале
|
||||
req один запрос: req METHOD PATH [--user UUID] [--data JSON]
|
||||
smoke публичный tests/smoke.py против этого порта
|
||||
student собственные тесты student-tests/ (make student_test) против
|
||||
этого порта
|
||||
stop остановить свой экземпляр на порту
|
||||
all start → flow → smoke → student (если есть student-tests/) → stop
|
||||
|
||||
Порт по умолчанию 18080, а не 8080: на 8080 обычно висит `make run_dev`
|
||||
пользователя, и его состояние в памяти трогать не надо. flow, req, smoke
|
||||
и student работают с любым сервером на порту, в том числе с контейнером
|
||||
(`make run_docker APP_OUT_PORT=<port>`).
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import contextlib
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[3]
|
||||
DEFAULT_PORT = 18080
|
||||
USERS = "/api/v1/users"
|
||||
CHATS = "/api/v1/chats"
|
||||
|
||||
|
||||
def paths(port: int) -> tuple[Path, Path]:
|
||||
return (
|
||||
Path(f"/tmp/mtusi-api-{port}.log"),
|
||||
Path(f"/tmp/mtusi-api-{port}.pid"),
|
||||
)
|
||||
|
||||
|
||||
def base_url(port: int) -> str:
|
||||
return f"http://127.0.0.1:{port}"
|
||||
|
||||
|
||||
def call(
|
||||
port: int,
|
||||
method: str,
|
||||
path: str,
|
||||
*,
|
||||
user: str | None = None,
|
||||
body: object = None,
|
||||
raw: bytes | None = None,
|
||||
) -> tuple[int, dict[str, str], object]:
|
||||
data = raw
|
||||
headers = {"Accept": "application/json"}
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode()
|
||||
if data is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
if user is not None:
|
||||
headers["X-User-Id"] = user
|
||||
request = urllib.request.Request(
|
||||
base_url(port) + path,
|
||||
data=data,
|
||||
method=method,
|
||||
headers=headers,
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=5) as response:
|
||||
status = response.status
|
||||
hdrs = dict(response.headers)
|
||||
payload = response.read()
|
||||
except urllib.error.HTTPError as error:
|
||||
status, hdrs, payload = error.code, dict(error.headers), error.read()
|
||||
hdrs = {key.lower(): value for key, value in hdrs.items()}
|
||||
try:
|
||||
parsed = json.loads(payload) if payload else None
|
||||
except json.JSONDecodeError:
|
||||
parsed = payload.decode(errors="replace")
|
||||
return status, hdrs, parsed
|
||||
|
||||
|
||||
def listener_pids(port: int) -> list[int]:
|
||||
out = subprocess.run(
|
||||
["lsof", "-nP", f"-iTCP:{port}", "-sTCP:LISTEN", "-t"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
).stdout
|
||||
return [int(pid) for pid in out.split()]
|
||||
|
||||
|
||||
def is_ready(port: int) -> bool:
|
||||
try:
|
||||
status, _, _ = call(port, "GET", "/health/ready")
|
||||
except OSError:
|
||||
return False
|
||||
return status == 200
|
||||
|
||||
|
||||
def cmd_start(port: int) -> int:
|
||||
log_path, pid_path = paths(port)
|
||||
if listener_pids(port):
|
||||
if is_ready(port):
|
||||
print(f"already up on {base_url(port)}")
|
||||
return 0
|
||||
print(f"port {port} is busy:", listener_pids(port))
|
||||
return 1
|
||||
env = os.environ | {"APP__RUN_MODE": "console", "APP__PORT": str(port)}
|
||||
with log_path.open("wb") as log:
|
||||
proc = subprocess.Popen(
|
||||
["uv", "run", "python", "-m", "src"],
|
||||
cwd=ROOT,
|
||||
env=env,
|
||||
stdout=log,
|
||||
stderr=subprocess.STDOUT,
|
||||
# своя группа процессов: stop гасит uv, reloader и worker разом
|
||||
start_new_session=True,
|
||||
)
|
||||
pid_path.write_text(str(proc.pid))
|
||||
deadline = time.monotonic() + 30
|
||||
while time.monotonic() < deadline:
|
||||
if proc.poll() is not None:
|
||||
print(f"server exited with {proc.returncode}; log: {log_path}")
|
||||
print(log_path.read_text()[-2000:])
|
||||
return 1
|
||||
if is_ready(port):
|
||||
print(f"up on {base_url(port)} pgid={proc.pid} log={log_path}")
|
||||
return 0
|
||||
time.sleep(0.25)
|
||||
print(f"not ready after 30s; log: {log_path}")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_stop(port: int) -> int:
|
||||
_, pid_path = paths(port)
|
||||
if not pid_path.exists():
|
||||
# экземпляр не наш (например, make run_dev): не трогаем
|
||||
if listener_pids(port):
|
||||
print(f"port {port} is not ours (no pid file); left running")
|
||||
return 1
|
||||
print(f"nothing on {port}")
|
||||
return 0
|
||||
with contextlib.suppress(ProcessLookupError):
|
||||
os.killpg(int(pid_path.read_text()), signal.SIGTERM)
|
||||
pid_path.unlink()
|
||||
deadline = time.monotonic() + 12
|
||||
while listener_pids(port) and time.monotonic() < deadline:
|
||||
time.sleep(0.2)
|
||||
if listener_pids(port):
|
||||
print(f"still listening on {port}:", listener_pids(port))
|
||||
return 1
|
||||
print(f"stopped {port}")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_status(port: int) -> int:
|
||||
pids = listener_pids(port)
|
||||
print("listeners:", pids or "none")
|
||||
if pids:
|
||||
print("ready:", is_ready(port))
|
||||
return 0 if pids else 1
|
||||
|
||||
|
||||
def cmd_req(port: int, args: argparse.Namespace) -> int:
|
||||
body = json.loads(args.data) if args.data is not None else None
|
||||
status, hdrs, payload = call(
|
||||
port,
|
||||
args.method.upper(),
|
||||
args.path,
|
||||
user=args.user,
|
||||
body=body,
|
||||
)
|
||||
print(status, "x-request-id:", hdrs.get("x-request-id"))
|
||||
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
||||
return 0 if status < 400 else 2
|
||||
|
||||
|
||||
class Flow:
|
||||
def __init__(self, port: int) -> None:
|
||||
self.port = port
|
||||
self.failures = 0
|
||||
|
||||
def check(self, label: str, ok: bool, detail: object = "") -> None:
|
||||
mark = "ok " if ok else "FAIL"
|
||||
print(f"[{mark}] {label}" + (f" {detail}" if detail else ""))
|
||||
if not ok:
|
||||
self.failures += 1
|
||||
|
||||
def expect(
|
||||
self,
|
||||
label: str,
|
||||
method: str,
|
||||
path: str,
|
||||
status: int,
|
||||
**kwargs: object,
|
||||
) -> object:
|
||||
"""Запрос + проверка статуса, X-Request-Id и формата ошибки."""
|
||||
got, hdrs, payload = call(self.port, method, path, **kwargs)
|
||||
request_id = hdrs.get("x-request-id")
|
||||
ok = got == status and bool(request_id)
|
||||
detail = str(got)
|
||||
if got >= 400:
|
||||
error = {}
|
||||
if isinstance(payload, dict):
|
||||
error = payload.get("error", {})
|
||||
ok = ok and error.get("request_id") == request_id
|
||||
detail = f"{got} {error.get('code')}"
|
||||
shown = path if len(path) <= 60 else path[:57] + "..."
|
||||
self.check(f"{method} {shown} -> {status} ({label})", ok, detail)
|
||||
return payload
|
||||
|
||||
|
||||
def cmd_flow(port: int) -> int:
|
||||
flow = Flow(port)
|
||||
tag = uuid.uuid4().hex[:8]
|
||||
flow.expect("live", "GET", "/health/live", 200)
|
||||
flow.expect("ready", "GET", "/health/ready", 200)
|
||||
|
||||
ids = {}
|
||||
for name in ("alice", "bob", "eve"):
|
||||
body = {"username": f"{name}_{tag}", "display_name": f"{name} ✨"}
|
||||
ids[name] = flow.expect("register", "POST", USERS, 201, body=body)[
|
||||
"id"
|
||||
]
|
||||
alice, bob, eve = ids["alice"], ids["bob"], ids["eve"]
|
||||
dup = {"username": f"alice_{tag}", "display_name": "again"}
|
||||
flow.expect("duplicate username", "POST", USERS, 409, body=dup)
|
||||
me = flow.expect("me", "GET", f"{USERS}/me", 200, user=alice)
|
||||
flow.check("me.id == alice", me.get("id") == alice)
|
||||
flow.expect("no X-User-Id", "GET", f"{USERS}/me", 401)
|
||||
stranger = str(uuid.uuid4())
|
||||
flow.expect("unknown user", "GET", f"{USERS}/me", 401, user=stranger)
|
||||
|
||||
body = {"title": "Проект 🚀", "member_ids": [alice, bob]}
|
||||
chat = flow.expect("new chat", "POST", CHATS, 201, user=alice, body=body)
|
||||
chat_path = f"{CHATS}/{chat['id']}"
|
||||
msgs = f"{chat_path}/messages"
|
||||
body = {"title": "x", "member_ids": [alice]}
|
||||
flow.expect("not a member", "POST", CHATS, 400, user=eve, body=body)
|
||||
|
||||
texts = ["привет", "hi 👋", "третье", "четвёртое", "пятое"]
|
||||
for index, text in enumerate(texts):
|
||||
sender = alice if index % 2 == 0 else bob
|
||||
body = {"text": text}
|
||||
flow.expect("send", "POST", msgs, 201, user=sender, body=body)
|
||||
blank = {"text": " "}
|
||||
flow.expect("blank text", "POST", msgs, 400, user=alice, body=blank)
|
||||
spoof = {"text": "x", "sender_id": alice}
|
||||
flow.expect("sender_id", "POST", msgs, 400, user=alice, body=spoof)
|
||||
|
||||
seen, cursor, pages = [], None, 0
|
||||
while pages < 10:
|
||||
query = "?limit=2" + (f"&cursor={cursor}" if cursor else "")
|
||||
page = flow.expect("page", "GET", msgs + query, 200, user=bob)
|
||||
seen += [item["text"] for item in page["items"]]
|
||||
cursor, pages = page["next_cursor"], pages + 1
|
||||
if cursor is None:
|
||||
break
|
||||
flow.check("history order via cursor", seen == texts, f"{pages} pages")
|
||||
flow.check("created_at ends with Z", chat["created_at"].endswith("Z"))
|
||||
|
||||
flow.expect("outsider reads chat", "GET", chat_path, 404, user=eve)
|
||||
flow.expect("outsider reads history", "GET", msgs, 404, user=eve)
|
||||
hi = {"text": "hi"}
|
||||
flow.expect("outsider posts", "POST", msgs, 404, user=eve, body=hi)
|
||||
flow.expect("no header beats 404", "GET", chat_path, 401)
|
||||
flow.expect("limit=0", "GET", msgs + "?limit=0", 400, user=alice)
|
||||
flow.expect("bad cursor", "GET", msgs + "?cursor=zzz", 400, user=alice)
|
||||
flow.expect("chat_id not uuid", "GET", f"{CHATS}/nope", 400, user=alice)
|
||||
flow.expect("malformed json", "POST", USERS, 400, raw=b"{not json")
|
||||
flow.expect("unknown path", "GET", "/nope", 404)
|
||||
chats = flow.expect("list chats", "GET", CHATS, 200, user=bob)
|
||||
listed = [item["id"] for item in chats["items"]]
|
||||
flow.check("bob sees the chat", chat["id"] in listed)
|
||||
|
||||
print(f"\nalice={alice}\nbob={bob}\neve={eve}\nchat={chat['id']}")
|
||||
print("FAILED:", flow.failures or "none")
|
||||
return 1 if flow.failures else 0
|
||||
|
||||
|
||||
def cmd_smoke(port: int) -> int:
|
||||
return subprocess.call(
|
||||
[
|
||||
sys.executable,
|
||||
"tests/smoke.py",
|
||||
"--base-url",
|
||||
f"http://localhost:{port}",
|
||||
],
|
||||
cwd=ROOT,
|
||||
)
|
||||
|
||||
|
||||
def cmd_student(port: int) -> int:
|
||||
if not (ROOT / "student-tests").is_dir():
|
||||
print("no student-tests/ in this checkout")
|
||||
return 1
|
||||
return subprocess.call(
|
||||
["make", "student_test", f"BASE_URL=http://localhost:{port}"],
|
||||
cwd=ROOT,
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("--port", type=int, default=DEFAULT_PORT)
|
||||
sub = parser.add_subparsers(dest="cmd", required=True)
|
||||
for name in ("start", "stop", "status", "flow", "smoke", "student", "all"):
|
||||
sub.add_parser(name)
|
||||
req = sub.add_parser("req")
|
||||
req.add_argument("method")
|
||||
req.add_argument("path")
|
||||
req.add_argument("--user")
|
||||
req.add_argument("--data")
|
||||
args = parser.parse_args()
|
||||
port = args.port
|
||||
|
||||
if args.cmd == "all":
|
||||
if cmd_start(port) != 0:
|
||||
return 1
|
||||
try:
|
||||
flow_rc = cmd_flow(port)
|
||||
smoke_rc = cmd_smoke(port)
|
||||
student_rc = 0
|
||||
if (ROOT / "student-tests").is_dir():
|
||||
student_rc = cmd_student(port)
|
||||
finally:
|
||||
cmd_stop(port)
|
||||
return flow_rc or smoke_rc or student_rc
|
||||
if args.cmd == "req":
|
||||
return cmd_req(port, args)
|
||||
handlers = {
|
||||
"start": cmd_start,
|
||||
"stop": cmd_stop,
|
||||
"status": cmd_status,
|
||||
"flow": cmd_flow,
|
||||
"smoke": cmd_smoke,
|
||||
"student": cmd_student,
|
||||
}
|
||||
return handlers[args.cmd](port)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user