feat: port backend implementation from lab1
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
# Собственные тесты
|
||||
|
||||
Проверки негативных сценариев и конкурентной работы, отдельно от публичных `tests/`.
|
||||
|
||||
Запуск (сервер уже должен быть поднят на `localhost:8080`):
|
||||
|
||||
python students-tests/run_all.py --base-url http://localhost:8080
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env python3
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
def main():
|
||||
args = sys.argv[1:]
|
||||
for script in ('test_cases.py', 'test_concurrency.py'):
|
||||
print(f'=== {script} ===')
|
||||
result = subprocess.run([sys.executable, str(ROOT / script), *args])
|
||||
if result.returncode != 0:
|
||||
sys.exit(result.returncode)
|
||||
print('=== Все тесты прошли ===')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,112 @@
|
||||
#!/usr/bin/env python3
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
|
||||
from client import Client, LAB, Failure, arguments, check, run # noqa: E402
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Собственные тесты негативных сценариев')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = '/api/v1/chats/' + chat['id']
|
||||
|
||||
# --- некорректный JSON ---
|
||||
malformed = b'{"username":"alice","display_name":"A"'
|
||||
c.call('POST', '/api/v1/users', 400, raw=malformed,
|
||||
headers={'Content-Type': 'application/json'})
|
||||
|
||||
# --- лишнее поле ---
|
||||
c.call('POST', '/api/v1/users', 400,
|
||||
body={'username': 'u_' + uuid.uuid4().hex[:8],
|
||||
'display_name': 'X', 'extra': 'мусор'})
|
||||
|
||||
# --- неверный тип поля ---
|
||||
c.call('POST', '/api/v1/users', 400,
|
||||
body={'username': 123, 'display_name': 'X'})
|
||||
|
||||
# --- пустой display_name ---
|
||||
c.call('POST', '/api/v1/users', 400,
|
||||
body={'username': 'u_' + uuid.uuid4().hex[:8], 'display_name': ''})
|
||||
|
||||
# --- display_name только из пробелов ---
|
||||
c.call('POST', '/api/v1/users', 400,
|
||||
body={'username': 'u_' + uuid.uuid4().hex[:8], 'display_name': ' '})
|
||||
|
||||
# --- заглавные в username ---
|
||||
c.call('POST', '/api/v1/users', 400,
|
||||
body={'username': 'UPPERCASE', 'display_name': 'X'})
|
||||
|
||||
# --- дубликат username ---
|
||||
c.call('POST', '/api/v1/users', 409, body=alice['registration'])
|
||||
|
||||
# --- пустое сообщение ---
|
||||
c.call('POST', path + '/messages', 400, actor=alice, body={'text': ''})
|
||||
|
||||
# --- сообщение только из пробелов ---
|
||||
c.call('POST', path + '/messages', 400, actor=alice, body={'text': ' '})
|
||||
|
||||
# --- чужой чат ---
|
||||
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': 'чужое'})
|
||||
|
||||
# --- чат без создателя в member_ids ---
|
||||
c.call('POST', '/api/v1/chats', 400, actor=alice,
|
||||
body={'title': 'Без меня', 'member_ids': [bob['id']]})
|
||||
|
||||
# --- чат с неизвестным участником ---
|
||||
c.call('POST', '/api/v1/chats', 400, actor=alice,
|
||||
body={'title': 'С фантомом',
|
||||
'member_ids': [alice['id'], '00000000-0000-4000-8000-000000000000']})
|
||||
|
||||
# --- чат с дубликатами ---
|
||||
c.call('POST', '/api/v1/chats', 400, actor=alice,
|
||||
body={'title': 'Дубликаты', 'member_ids': [alice['id'], alice['id']]})
|
||||
|
||||
# --- обход нескольких страниц ---
|
||||
for i in range(5):
|
||||
c.message(alice, chat, 'page-test-%d' % i)
|
||||
|
||||
seen = []
|
||||
cursor = None
|
||||
for _ in range(20):
|
||||
query = path + '/messages?limit=2'
|
||||
if cursor:
|
||||
from urllib.parse import quote
|
||||
query += '&cursor=' + quote(cursor, safe='')
|
||||
page = c.call('GET', query, actor=alice, schema='MessagePage')['json']
|
||||
seen.extend(x['id'] for x in page['items'])
|
||||
cursor = page['next_cursor']
|
||||
if cursor is None:
|
||||
break
|
||||
check(len(seen) == len(set(seen)), 'пагинация вернула дубликаты')
|
||||
check(len(seen) >= 5, 'пагинация потеряла сообщения')
|
||||
|
||||
# --- cursor от другого чата ---
|
||||
other_chat = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'Другой чат',
|
||||
'member_ids': [alice['id'], bob['id']]},
|
||||
schema='Chat')['json']
|
||||
other_path = '/api/v1/chats/' + other_chat['id']
|
||||
c.message(alice, other_chat, 'other-1')
|
||||
c.message(alice, other_chat, 'other-2')
|
||||
|
||||
other_page = c.call('GET', other_path + '/messages?limit=1', actor=alice,
|
||||
schema='MessagePage')['json']
|
||||
other_cursor = other_page['next_cursor']
|
||||
check(other_cursor is not None, 'ожидался cursor от другого чата, но получен null')
|
||||
|
||||
from urllib.parse import quote
|
||||
c.call('GET', path + '/messages?limit=2&cursor=' + quote(other_cursor, safe=''),
|
||||
400, actor=alice)
|
||||
|
||||
print('PASS: негативные сценарии прошли')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/env python3
|
||||
import threading
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
|
||||
from client import Client, LAB, Failure, arguments, check, run # noqa: E402
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Собственные тесты конкурентности')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = '/api/v1/chats/' + chat['id']
|
||||
|
||||
# --- 100 сообщений от 10 потоков ---
|
||||
workers = 10
|
||||
per_worker = 10
|
||||
expected_total = workers * per_worker
|
||||
barrier = threading.Barrier(workers)
|
||||
|
||||
def writer(worker_id):
|
||||
local = Client(args.base_url, args.ca_file, timeout=10)
|
||||
barrier.wait()
|
||||
for i in range(per_worker):
|
||||
local.message(alice, chat, 'c-%d-%d' % (worker_id, i))
|
||||
|
||||
with ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
list(pool.map(writer, range(workers)))
|
||||
|
||||
seen = []
|
||||
cursor = None
|
||||
while True:
|
||||
q = path + '/messages?limit=100'
|
||||
if cursor:
|
||||
from urllib.parse import quote
|
||||
q += '&cursor=' + quote(cursor, safe='')
|
||||
page = c.call('GET', q, actor=alice, schema='MessagePage')['json']
|
||||
seen.extend(x['id'] for x in page['items'])
|
||||
cursor = page['next_cursor']
|
||||
if cursor is None:
|
||||
break
|
||||
|
||||
check(len(seen) == len(set(seen)), 'после параллельной записи обнаружены дубликаты id сообщений')
|
||||
check(len(seen) == expected_total,
|
||||
'ожидалось ровно %d сообщений, получено %d' % (expected_total, len(seen)))
|
||||
|
||||
# --- гонка за username ---
|
||||
username = 'race_' + uuid.uuid4().hex[:8]
|
||||
barrier2 = threading.Barrier(workers)
|
||||
|
||||
def register(_):
|
||||
local = Client(args.base_url, args.ca_file, timeout=10)
|
||||
barrier2.wait()
|
||||
try:
|
||||
local.call('POST', '/api/v1/users', 201,
|
||||
body={'username': username, 'display_name': 'Race'})
|
||||
return 'ok'
|
||||
except Failure:
|
||||
return 'conflict'
|
||||
|
||||
with ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
results = list(pool.map(register, range(workers)))
|
||||
|
||||
ok_count = results.count('ok')
|
||||
conflict_count = results.count('conflict')
|
||||
check(ok_count == 1, 'ожидалась ровно одна успешная регистрация, получено %d' % ok_count)
|
||||
check(conflict_count == workers - 1,
|
||||
'ожидалось %d конфликтов, получено %d' % (workers - 1, conflict_count))
|
||||
|
||||
print('PASS: конкурентность (100 сообщений, 1 победитель в гонке за username)')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user