100 lines
4.0 KiB
Python
100 lines
4.0 KiB
Python
#!/usr/bin/env python3
|
|
"""Негативные сценарии lab1: неверный JSON, чужой чат, пустое сообщение,
|
|
дубликат username, обход нескольких страниц. Stdlib only, Python 3.9+."""
|
|
import sys
|
|
import urllib.error
|
|
import urllib.request
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
|
from client import Client, Failure, arguments, check, run # noqa: E402
|
|
|
|
|
|
def _raw_call(base_url, method, path, body=None, headers=None):
|
|
"""Сырой запрос для проверки malformed JSON (client.py всегда сериализует)."""
|
|
url = base_url.rstrip("/") + path
|
|
data = body if isinstance(body, (bytes, type(None))) else body.encode("utf-8")
|
|
req = urllib.request.Request(url, data=data, headers=headers or {}, method=method)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=10) as resp:
|
|
return resp.status, resp.read()
|
|
except urllib.error.HTTPError as e:
|
|
return e.code, e.read()
|
|
|
|
|
|
def main():
|
|
args = arguments("Lab1 negative scenarios")
|
|
c = Client(args.base_url, args.ca_file)
|
|
alice, bob, eve, chat = c.bootstrap()
|
|
path = "/api/v1/chats/" + chat["id"]
|
|
|
|
# 1. Дубликат username -> 409
|
|
c.call("POST", "/api/v1/users", 409, body=alice["registration"])
|
|
|
|
# 2. Неверный JSON (malformed) -> 400
|
|
status, _ = _raw_call(
|
|
c.base,
|
|
"POST",
|
|
"/api/v1/users",
|
|
body=b"{not json at all",
|
|
headers={"Content-Type": "application/json"},
|
|
)
|
|
check(status == 400, "malformed JSON must be 400, got %s" % status)
|
|
|
|
# 3. Лишние поля -> 400
|
|
c.call(
|
|
"POST",
|
|
"/api/v1/users",
|
|
400,
|
|
body={"username": "extra_user_x", "display_name": "X", "unexpected": True},
|
|
)
|
|
|
|
# 4. Неверный тип -> 400
|
|
c.call("POST", "/api/v1/users", 400, body={"username": 123, "display_name": "X"})
|
|
|
|
# 5. Пустое / пробельное сообщение -> 400
|
|
c.call("POST", path + "/messages", 400, actor=alice, body={"text": ""})
|
|
c.call("POST", path + "/messages", 400, actor=alice, body={"text": " "})
|
|
|
|
# 6. Чужой чат -> 404 (не 403)
|
|
c.call("GET", path, 404, actor=eve)
|
|
c.call("GET", path + "/messages", 404, actor=eve)
|
|
c.call("POST", path + "/messages", 404, actor=eve, body={"text": "чужое"})
|
|
|
|
# 7. Пагинация: обход нескольких страниц без потерь и дублей
|
|
texts = ["p-%02d" % i for i in range(7)]
|
|
for t in texts:
|
|
c.message(alice, chat, t)
|
|
collected = []
|
|
cursor = None
|
|
seen_cursors = set()
|
|
for _ in range(20): # предохранитель от бесконечного цикла
|
|
q = path + "/messages?limit=2"
|
|
if cursor:
|
|
from urllib.parse import quote
|
|
q += "&cursor=" + quote(cursor, safe="")
|
|
page = c.call("GET", q, actor=bob, schema="MessagePage")["json"]
|
|
collected.extend(m["text"] for m in page["items"])
|
|
cursor = page["next_cursor"]
|
|
if cursor is None:
|
|
break
|
|
check(cursor not in seen_cursors, "cursor loop detected")
|
|
seen_cursors.add(cursor)
|
|
check(len(collected) == len(texts), "pagination lost messages: %d != %d" % (len(collected), len(texts)))
|
|
check(len(set(collected)) == len(collected), "pagination duplicated messages")
|
|
check(collected == texts, "pagination order/contents mismatch")
|
|
|
|
# 8. Некорректный limit -> 400
|
|
c.call("GET", path + "/messages?limit=0", 400, actor=alice)
|
|
c.call("GET", path + "/messages?limit=101", 400, actor=alice)
|
|
|
|
# 9. Неизвестный X-User-Id -> 401
|
|
c.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": str(uuid.uuid4())})
|
|
|
|
print("PASS: lab1 negative scenarios (dup, malformed JSON, extra fields, "
|
|
"wrong type, empty text, foreign chat, pagination, bad limit, unknown user)")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
run(main) |