forked from mtusi2026/mtusi2026lab2
44 lines
2.0 KiB
Python
44 lines
2.0 KiB
Python
from concurrent.futures import ThreadPoolExecutor
|
|
import json
|
|
import urllib.error
|
|
import urllib.request
|
|
from urllib.parse import quote
|
|
import uuid
|
|
|
|
from client import Client
|
|
|
|
BASE="http://localhost:8080"
|
|
|
|
def register(body):
|
|
req=urllib.request.Request(BASE+"/api/v1/users",data=json.dumps(body).encode(),headers={"Content-Type":"application/json"},method="POST")
|
|
try:
|
|
with urllib.request.urlopen(req,timeout=10) as r: return r.status
|
|
except urllib.error.HTTPError as e: return e.code
|
|
|
|
def main():
|
|
uname="race_"+uuid.uuid4().hex[:20]
|
|
body={"username":uname,"display_name":"Race","password":"RacePassword-123456"}
|
|
with ThreadPoolExecutor(max_workers=12) as executor:
|
|
statuses=list(executor.map(register,[body]*12))
|
|
assert statuses.count(201)==1 and statuses.count(409)==11, statuses
|
|
|
|
c=Client(BASE)
|
|
actor=c.user("rollback")
|
|
for title in ("cursor first", "cursor second"):
|
|
c.call("POST", "/api/v1/chats", 201, actor=actor,
|
|
body={"title": title, "member_ids": [actor["id"]]}, schema="Chat")
|
|
page1=c.call("GET", "/api/v1/chats?limit=1", actor=actor, schema="ChatPage")["json"]
|
|
assert len(page1["items"]) == 1 and page1["next_cursor"]
|
|
page2=c.call("GET", "/api/v1/chats?limit=1&cursor=" + quote(page1["next_cursor"], safe=""), actor=actor, schema="ChatPage")["json"]
|
|
assert len(page2["items"]) == 1 and page2["next_cursor"] is None
|
|
assert page1["items"][0]["id"] != page2["items"][0]["id"]
|
|
before=c.call("GET","/api/v1/chats?limit=100",actor=actor,schema="ChatPage")["json"]["items"]
|
|
invalid=str(uuid.uuid4())
|
|
result=c.call("POST","/api/v1/chats",400,actor=actor,body={"title":"must rollback","member_ids":[actor["id"],invalid]})
|
|
assert result["status"]==400
|
|
after=c.call("GET","/api/v1/chats?limit=100",actor=actor,schema="ChatPage")["json"]["items"]
|
|
assert [x["id"] for x in after]==[x["id"] for x in before], "failed chat left partial state"
|
|
print("PASS: concurrent username uniqueness and atomic chat rollback")
|
|
|
|
if __name__=="__main__": main()
|