lab3: cursor fix

This commit is contained in:
Максим Шептунов
2026-10-16 11:44:19 +03:00
parent 2af739065d
commit 1f9e250c60
3 changed files with 43 additions and 3 deletions
+10
View File
@@ -0,0 +1,10 @@
python3 student-tests/test_api.py --base-url "http://localhost:8080"
PASS: malformed JSON/media type, duplicate username, blank message, outsider access, pagination
PASS: 10 clients created exactly 100 unique messages
python3 student-tests/checks.py --base-url "http://localhost:8080"
PASS: registration race, invalid input, cursor scope/types on two API, read-after-write, logout
python3 student-tests/idempotency.py --base-url "http://localhost:8080"
PASS: shared idempotency, scope, conflict and auth on replay
docker exec "$(docker compose ps --status running -q api | head -n 1)" python student-tests/database.py
PASS: rollback of chat + members; migration reapplied twice
PASS: persisted key expiry, atomic message/result rollback
+5 -1
View File
@@ -329,7 +329,11 @@ def decode_cursor(cursor: str, expected_scope: str) -> tuple[datetime, uuid.UUID
raise ValueError
padded = cursor + "=" * (-len(cursor) % 4)
payload = json.loads(base64.b64decode(padded.encode(), altchars=b"-_", validate=True).decode())
if set(payload) != {"scope", "created_at", "id"} or payload["scope"] != expected_scope:
if not isinstance(payload, dict) or set(payload) != {"scope", "created_at", "id"}:
raise ValueError
if payload["scope"] != expected_scope:
raise ValueError
if not isinstance(payload["created_at"], str) or not isinstance(payload["id"], str):
raise ValueError
created_at = datetime.fromisoformat(payload["created_at"].replace("Z", "+00:00"))
item_id = uuid.UUID(payload["id"])
+28 -2
View File
@@ -1,15 +1,39 @@
"""Дополнения к публичному smoke. Не печатает и не сохраняет tokens."""
import base64
import concurrent.futures
import json
import sys
import time
from pathlib import Path
from uuid import uuid4
from urllib.parse import quote
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, arguments, check, run
def check_cursor_types(c, actor, path, cursor, schema):
check(bool(cursor), 'test requires a real pagination cursor')
payload = json.loads(base64.urlsafe_b64decode(cursor + '=' * (-len(cursor) % 4)))
c.call('GET', path + '?cursor=' + quote(cursor, safe=''), actor=actor, schema=schema)
invalid = []
for field in ['created_at', 'id']:
for value in [1, 1.5, None, True, [], {}, '', 'invalid']:
invalid.append({**payload, field: value})
invalid.extend([None, 1, True, [], 'cursor'])
for value in invalid:
encoded = base64.urlsafe_b64encode(json.dumps(value).encode()).decode().rstrip('=')
instances = set()
# Проверяем один и тот же cursor на обеих API за round-robin LB.
for _ in range(8):
response = c.call('GET', path + '?cursor=' + quote(encoded, safe=''), 400, actor=actor)
check(response['json']['error']['code'] == 'invalid_request', 'incorrect cursor error code')
instances.add(response['headers']['X-Instance-Id'])
if len(instances) >= 2:
break
check(len(instances) >= 2, 'invalid cursor was not checked on two API instances')
def main():
def configure(p):
p.add_argument('--expiry', action='store_true', help='API must run with TTL=2')
@@ -50,14 +74,16 @@ def main():
page = c.call('GET', path + '/messages?limit=1', actor=alice, schema='MessagePage')['json']
other = c.call('POST', '/api/v1/chats', 201, actor=alice,
body={'title': 'other', 'member_ids': [alice['id']]}, schema='Chat')['json']
from urllib.parse import quote
c.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' +
quote(page['next_cursor'], safe=''), 400, actor=alice)
check_cursor_types(c, alice, path + '/messages', page['next_cursor'], 'MessagePage')
chats = c.call('GET', '/api/v1/chats?limit=1', actor=alice, schema='ChatPage')['json']
check_cursor_types(c, alice, '/api/v1/chats', chats['next_cursor'], 'ChatPage')
history = c.call('GET', path + '/messages', actor=bob, schema='MessagePage')['json']['items']
check(len(history) == 3 and history[-1]['text'] == 'read-after-write 2', 'read-after-write failed')
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
c.call('GET', '/api/v1/users/me', 401, actor=alice)
print('PASS: registration race, invalid input, cursor scope, read-after-write, logout')
print('PASS: registration race, invalid input, cursor scope/types on two API, read-after-write, logout')
if __name__ == '__main__':