Files
mtusi2026lab4/tests/client.py
T

161 lines
4.8 KiB
Python

#!/usr/bin/env python3
import sys
import uuid
import requests
BASE = "http://localhost:8080"
LOGIN = "test"
PASSWORD = "test123"
TIMEOUT = 5
LAB = "lab4"
failures = []
def check(condition, message):
if condition:
print("PASS:", message)
return True
failures.append(message)
print("FAIL:", message)
return False
def timestamp():
import datetime
return datetime.datetime.utcnow().isoformat() + "Z"
class _Arguments:
"""Простой объект для передачи аргументов в тесты скелета."""
base_url = BASE
login = LOGIN
password = PASSWORD
timeout = TIMEOUT
lab = LAB
def arguments(*args, **kwargs):
return _Arguments()
def run(func):
name = getattr(func, "__name__", "test")
print(f"=== {name} ===")
try:
func()
except Exception as exc:
failures.append(f"{name} crashed: {exc}")
print("FAIL:", f"{name} crashed: {exc}")
class Failure(Exception):
"""Исключение для тестов"""
pass
class Client:
def __init__(self, base_url=BASE):
self.base_url = base_url.rstrip("/")
self.token = None
self.session = requests.Session()
self.session.headers.update({"Accept": "application/json"})
def login(self, login=LOGIN, password=PASSWORD):
r = self.session.post(
f"{self.base_url}/api/auth/login",
json={"login": login, "password": password},
timeout=TIMEOUT,
)
r.raise_for_status()
self.token = r.json()["token"]
self.session.headers["Authorization"] = f"Bearer {self.token}"
return self.token
def get(self, path, **kwargs):
kwargs.setdefault("timeout", TIMEOUT)
return self.session.get(f"{self.base_url}{path}", **kwargs)
def post(self, path, **kwargs):
kwargs.setdefault("timeout", TIMEOUT)
return self.session.post(f"{self.base_url}{path}", **kwargs)
def delete(self, path, **kwargs):
kwargs.setdefault("timeout", TIMEOUT)
return self.session.delete(f"{self.base_url}{path}", **kwargs)
def login():
response = requests.post(
BASE + "/api/auth/login",
json={"login": LOGIN, "password": PASSWORD},
timeout=TIMEOUT,
)
if not check(response.status_code == 200, "login returns 200 (got %d)" % response.status_code):
print(response.text)
return None
token = response.json().get("token")
check(bool(token), "login returns a token")
return token
def main():
token = login()
if token is None:
return 1
auth = {"Authorization": "Bearer " + token}
response = requests.get(BASE + "/api/messages", headers=auth, timeout=TIMEOUT)
check(response.status_code == 200, "GET /api/messages returns 200")
instance = response.headers.get("X-Instance-Id")
check(bool(instance), "response carries X-Instance-Id (%s)" % instance)
check(isinstance(response.json(), list), "GET /api/messages returns a JSON array")
key = "key-" + uuid.uuid4().hex[:12]
body = {"recipient": LOGIN, "body": "hello " + uuid.uuid4().hex[:8]}
first = requests.post(
BASE + "/api/messages",
headers=dict(auth, **{"Idempotency-Key": key}),
json=body,
timeout=TIMEOUT,
)
check(first.status_code == 201, "first POST returns 201 (got %d)" % first.status_code)
second = requests.post(
BASE + "/api/messages",
headers=dict(auth, **{"Idempotency-Key": key}),
json=body,
timeout=TIMEOUT,
)
check(second.status_code in (200, 201), "replayed POST returns 2xx (got %d)" % second.status_code)
first_id = first.json().get("id")
second_id = second.json().get("id")
check(first_id is not None, "first POST returns message id")
check(first_id == second_id, "replay returns the same id (%s vs %s)" % (first_id, second_id))
missing_key = requests.post(BASE + "/api/messages", headers=auth, json=body, timeout=TIMEOUT)
check(missing_key.status_code == 400, "POST without Idempotency-Key returns 400 (got %d)" % missing_key.status_code)
unauthorized = requests.get(BASE + "/api/messages", timeout=TIMEOUT)
check(unauthorized.status_code == 401, "GET without token returns 401 (got %d)" % unauthorized.status_code)
messages = requests.get(BASE + "/api/messages", headers=auth, timeout=TIMEOUT).json()
matching = [m for m in messages if m.get("body") == body["body"]]
check(len(matching) == 1, "history contains exactly one copy of the message (got %d)" % len(matching))
if failures:
print("\n%d check(s) failed" % len(failures))
return 1
print("\nAll API checks passed")
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except requests.RequestException as exc:
print("request failed:", exc)
sys.exit(1)