Выполнила лабораторную 2
This commit is contained in:
+1
-1
@@ -4,7 +4,7 @@ Python **3.9+**, стандартная библиотека. Сервер уж
|
||||
|
||||
```sh
|
||||
make check
|
||||
make test BASE_URL=http://localhost:8080
|
||||
make test BASE_URL=http://127.0.0.1:8080
|
||||
# без make:
|
||||
python3 tests/smoke.py --base-url http://localhost:8080
|
||||
```
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Demonstrate that restarting lab1 clears the in-memory state."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
|
||||
def request(base_url, method, path, body=None, actor=None):
|
||||
headers = {"Accept": "application/json"}
|
||||
if actor:
|
||||
headers["X-User-Id"] = actor
|
||||
data = None
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
headers["Content-Type"] = "application/json"
|
||||
request = Request(base_url + path, data=data, headers=headers, method=method)
|
||||
try:
|
||||
response = urlopen(request, timeout=3)
|
||||
except HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
payload = json.loads(response.read().decode("utf-8"))
|
||||
if not response.headers.get("X-Request-Id"):
|
||||
raise RuntimeError("API response is missing X-Request-Id")
|
||||
return response.status, payload
|
||||
|
||||
|
||||
def wait_ready(base_url, timeout=10):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
status, _ = request(base_url, "GET", "/health/ready")
|
||||
if status == 200:
|
||||
return
|
||||
except (OSError, URLError, TimeoutError):
|
||||
pass
|
||||
time.sleep(0.2)
|
||||
raise RuntimeError("API did not become ready within %s seconds" % timeout)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default=os.environ.get("BASE_URL", "http://localhost:8080"))
|
||||
parser.add_argument("--container", default=os.environ.get("CONTAINER_NAME", "mtusi-messenger-lab1"))
|
||||
args = parser.parse_args()
|
||||
base_url = args.base_url.rstrip("/")
|
||||
|
||||
username = "lifecycle_" + uuid.uuid4().hex[:12]
|
||||
status, user = request(base_url, "POST", "/api/v1/users", {
|
||||
"username": username,
|
||||
"display_name": "Lifecycle demo",
|
||||
})
|
||||
if status != 201:
|
||||
raise RuntimeError("user creation returned HTTP %s" % status)
|
||||
|
||||
status, chat = request(base_url, "POST", "/api/v1/chats", {
|
||||
"title": "Lifecycle demo",
|
||||
"member_ids": [user["id"]],
|
||||
}, actor=user["id"])
|
||||
if status != 201:
|
||||
raise RuntimeError("chat creation returned HTTP %s" % status)
|
||||
|
||||
message_text = "persisted only while this process is alive"
|
||||
status, message = request(base_url, "POST", "/api/v1/chats/%s/messages" % chat["id"], {
|
||||
"text": message_text,
|
||||
}, actor=user["id"])
|
||||
if status != 201:
|
||||
raise RuntimeError("message creation returned HTTP %s" % status)
|
||||
|
||||
status, page = request(base_url, "GET", "/api/v1/chats/%s/messages" % chat["id"], actor=user["id"])
|
||||
if status != 200 or not any(item["id"] == message["id"] for item in page["items"]):
|
||||
raise RuntimeError("created message was not readable before restart")
|
||||
print("before restart: user_id=%s message_id=%s message_read=yes" % (user["id"], message["id"]))
|
||||
|
||||
subprocess.run(["docker", "restart", "--timeout", "5", args.container], check=True, capture_output=True, text=True)
|
||||
wait_ready(base_url)
|
||||
status, error = request(base_url, "GET", "/api/v1/users/me", actor=user["id"])
|
||||
if status != 401 or error.get("error", {}).get("code") != "unauthorized":
|
||||
raise RuntimeError("old X-User-Id should be rejected after restart; got HTTP %s" % status)
|
||||
print("after restart: old_user_id_status=%s code=%s state_reset=yes" % (status, error["error"]["code"]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,132 @@
|
||||
import json
|
||||
import threading
|
||||
import unittest
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
import app
|
||||
|
||||
|
||||
class ApiTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.server = app.ThreadingHTTPServer(("127.0.0.1", 0), app.Handler)
|
||||
cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True)
|
||||
cls.thread.start()
|
||||
cls.base = "http://127.0.0.1:%d" % cls.server.server_port
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.server.shutdown()
|
||||
cls.server.server_close()
|
||||
|
||||
def request(self, method, path, body=None, user=None, raw=None):
|
||||
headers = {"Accept": "application/json"}
|
||||
if user:
|
||||
headers["X-User-Id"] = user
|
||||
data = raw
|
||||
if body is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
request = urllib.request.Request(self.base + path, data=data, headers=headers, method=method)
|
||||
try:
|
||||
response = urllib.request.urlopen(request)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
payload = json.loads(response.read().decode("utf-8"))
|
||||
self.assertTrue(response.headers.get("X-Request-Id"))
|
||||
return response.code, payload
|
||||
|
||||
def test_invalid_json_duplicate_user_and_foreign_chat(self):
|
||||
status, _ = self.request("POST", "/api/v1/users", body={"username": "alice", "display_name": "Алиса"})
|
||||
self.assertEqual(status, 201)
|
||||
alice_id = next(iter(app.state.users))
|
||||
status, _ = self.request("POST", "/api/v1/users", body={"username": "alice", "display_name": "Другая"})
|
||||
self.assertEqual(status, 409)
|
||||
bob = self.request("POST", "/api/v1/users", body={"username": "charlie", "display_name": "Чарли"})[1]
|
||||
chat = self.request("POST", "/api/v1/chats", user=alice_id, body={"title": "Тест", "member_ids": [alice_id]})[1]
|
||||
status, _ = self.request("GET", "/api/v1/chats/%s" % chat["id"], user=bob["id"])
|
||||
self.assertEqual(status, 404)
|
||||
status, _ = self.request("GET", "/api/v1/chats/not-a-uuid", user=alice_id)
|
||||
self.assertEqual(status, 400)
|
||||
status, _ = self.request("POST", "/api/v1/users", body={"username": "bad", "display_name": "x", "extra": 1})
|
||||
self.assertEqual(status, 400)
|
||||
status, _ = self.request("POST", "/api/v1/users", raw=b"{broken")
|
||||
self.assertEqual(status, 400)
|
||||
|
||||
def test_invalid_types_and_chat_pagination(self):
|
||||
status, _ = self.request("POST", "/api/v1/users", body={"username": 1, "display_name": "Тест"})
|
||||
self.assertEqual(status, 400)
|
||||
user = self.request("POST", "/api/v1/users", body={"username": "typecheck", "display_name": "Типы"})[1]
|
||||
for member_ids in ([{"id": user["id"]}], [user["id"], []]):
|
||||
status, _ = self.request(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
user=user["id"],
|
||||
body={"title": "Некорректный чат", "member_ids": member_ids},
|
||||
)
|
||||
self.assertEqual(status, 400)
|
||||
|
||||
for index in range(5):
|
||||
status, _ = self.request(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
user=user["id"],
|
||||
body={"title": "Чат %d" % index, "member_ids": [user["id"]]},
|
||||
)
|
||||
self.assertEqual(status, 201)
|
||||
|
||||
cursor = None
|
||||
chat_ids = []
|
||||
for _ in range(5):
|
||||
path = "/api/v1/chats?limit=1"
|
||||
if cursor:
|
||||
path += "&cursor=" + cursor
|
||||
status, page = self.request("GET", path, user=user["id"])
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(len(page["items"]), 1)
|
||||
chat_ids.append(page["items"][0]["id"])
|
||||
cursor = page["next_cursor"]
|
||||
self.assertIsNone(cursor)
|
||||
self.assertEqual(len(set(chat_ids)), 5)
|
||||
|
||||
def test_empty_message_and_multi_page_pagination(self):
|
||||
user = self.request("POST", "/api/v1/users", body={"username": "pager", "display_name": "Пейджер"})[1]
|
||||
chat = self.request("POST", "/api/v1/chats", user=user["id"], body={"title": "Страницы", "member_ids": [user["id"]]})[1]
|
||||
status, _ = self.request("POST", "/api/v1/chats/%s/messages" % chat["id"], user=user["id"], body={"text": " "})
|
||||
self.assertEqual(status, 400)
|
||||
for index in range(3):
|
||||
self.assertEqual(self.request("POST", "/api/v1/chats/%s/messages" % chat["id"], user=user["id"], body={"text": str(index)})[0], 201)
|
||||
status, first = self.request("GET", "/api/v1/chats/%s/messages?limit=2" % chat["id"], user=user["id"])
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(len(first["items"]), 2)
|
||||
self.assertTrue(first["next_cursor"])
|
||||
status, second = self.request("GET", "/api/v1/chats/%s/messages?limit=2&cursor=%s" % (chat["id"], first["next_cursor"]), user=user["id"])
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(len(second["items"]), 1)
|
||||
self.assertIsNone(second["next_cursor"])
|
||||
|
||||
def test_concurrent_messages_are_not_lost(self):
|
||||
users = [self.request("POST", "/api/v1/users", body={"username": "client%d" % index, "display_name": "Клиент %d" % index})[1] for index in range(10)]
|
||||
chat = self.request("POST", "/api/v1/chats", user=users[0]["id"], body={"title": "Тест", "member_ids": [user["id"] for user in users]})[1]
|
||||
barrier = threading.Barrier(10)
|
||||
|
||||
def send(client_index):
|
||||
barrier.wait()
|
||||
for message_index in range(10):
|
||||
self.request("POST", "/api/v1/chats/%s/messages" % chat["id"], user=users[client_index]["id"], body={"text": "message-%d-%d" % (client_index, message_index)})
|
||||
|
||||
threads = [threading.Thread(target=send, args=(index,)) for index in range(10)]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
status, page = self.request("GET", "/api/v1/chats/%s/messages?limit=100" % chat["id"], user=users[0]["id"])
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(len(page["items"]), 100)
|
||||
self.assertEqual(len({message["id"] for message in page["items"]}), 100)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user