Files
mtusi2026lab4/student-tests/checks.py
T
2026-10-16 22:47:54 +03:00

91 lines
4.6 KiB
Python

"""Дополнения к публичному 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')
args = arguments('Student API checks', configure)
c = Client(args.base_url)
alice, bob, eve, chat = c.bootstrap()
if args.expiry:
time.sleep(2.2)
c.call('GET', '/api/v1/users/me', 401, actor=alice)
print('PASS: short TTL expiry')
return
registration = {'username': 'race_' + uuid4().hex[:12], 'display_name': 'Гонка',
'password': 'Synthetic-password-42'}
# Для гонки регистрируем оба допустимых исхода через urllib.
import urllib.request
import urllib.error
def register(_):
req = urllib.request.Request(c.base + '/api/v1/users',
data=json.dumps(registration).encode(),
headers={'Content-Type': 'application/json'})
try:
with urllib.request.urlopen(req, timeout=10) as response:
return response.status
except urllib.error.HTTPError as error:
return error.code
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor:
codes = list(executor.map(register, range(8)))
check(codes.count(201) == 1 and codes.count(409) == 7, 'username race failed')
path = '/api/v1/chats/' + chat['id']
c.call('POST', '/api/v1/chats', 400, actor=alice,
body={'title': 'unknown member', 'member_ids': [alice['id'], str(uuid4())]})
for body in [{'text': 'x', 'sender_id': eve['id']}, {'text': 4}, {'text': ' '}]:
c.call('POST', path + '/messages', 400, actor=alice, body=body)
c.call('GET', path + '/messages?limit=true', 400, actor=alice)
c.call('GET', path + '/messages?cursor=not-a-cursor', 400, actor=alice)
for n in range(3):
c.message(alice, chat, 'read-after-write ' + str(n))
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']
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/types on two API, read-after-write, logout')
if __name__ == '__main__':
run(main)