"""Check the transferred lab2 API, optionally across make app-down/app-up.""" import argparse import base64 import json import secrets import subprocess from pathlib import Path from urllib.error import HTTPError from urllib.request import Request, urlopen def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--base-url", default="http://localhost:8080") parser.add_argument("--restart", action="store_true") args = parser.parse_args() def call(method, path, expected=200, body=None, token=None, headers=None): headers = dict(headers or {}) if token: headers["Authorization"] = "Bearer " + token data = None if body is not None: headers["Content-Type"] = "application/json" data = json.dumps(body).encode("utf-8") request = Request( args.base_url + path, data=data, headers=headers, method=method ) try: response = urlopen(request, timeout=10) except HTTPError as error: response = error with response: assert response.status == expected, ( f"{method} {path}: expected {expected}, got {response.status}" ) assert response.headers.get("X-Request-Id"), "Missing request ID" raw = response.read() return json.loads(raw) if raw else None call("GET", "/health/ready") password = secrets.token_hex(16) users = [] for name in ("alice", "bob"): username = name + "_" + secrets.token_hex(6) user = call( "POST", "/api/v1/users", 201, {"username": username, "display_name": name, "password": password}, ) credentials = base64.b64encode(f"{username}:{password}".encode()).decode() session = call( "POST", "/api/v1/auth/sessions", 201, headers={"Authorization": "Basic " + credentials}, ) users.append((user, session["token"])) alice, token = users[0] bob, bob_token = users[1] chat = call( "POST", "/api/v1/chats", 201, {"title": "Baseline lab3", "member_ids": [alice["id"], bob["id"]]}, token, ) path = "/api/v1/chats/" + chat["id"] + "/messages" key = secrets.token_hex(16) body = {"text": "Перенос из лабораторной 2"} message = call( "POST", path, 201, body, token, {"Idempotency-Key": key}, ) assert call("GET", path, token=bob_token)["items"] == [message] call("GET", "/api/v1/users/me", 401) if args.restart: root = Path(__file__).resolve().parents[1] subprocess.run(["make", "app-down"], cwd=root, check=True) subprocess.run(["make", "app-up"], cwd=root, check=True) assert call("GET", "/api/v1/users/me", token=token) == alice assert call("GET", path, token=bob_token)["items"] == [message] assert call("POST", path, 201, body, token, {"Idempotency-Key": key}) == message assert call("GET", path, token=bob_token)["items"] == [message] call("DELETE", "/api/v1/auth/sessions/current", 204, token=token) call("GET", "/api/v1/users/me", 401, token=token) print( "PASS: transferred API, shared sessions, chat, message, logout" + (", persistence and idempotent replay across app-down/app-up" if args.restart else "") ) if __name__ == "__main__": main()