ЛР 2 — БВТ-2302 — Сабитов — на 3
Lab 2 application / postgres (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
2026-12-01 00:50:23 +03:00
parent 65003b6119
commit ff7296c240
17 changed files with 987 additions and 34 deletions
+104
View File
@@ -0,0 +1,104 @@
"""Focused Lab 2 contract checks (stdlib only). Needs running API + PostgreSQL.
Run: python tests/contract_edge_tests.py --base-url http://localhost:8080
Prints only status summary; credentials/tokens remain in process memory.
"""
import argparse
import base64
import json
import urllib.error
import urllib.parse
import urllib.request
import uuid
class Client:
def __init__(self, base):
self.base = base.rstrip('/')
self.count = 0
def call(self, method, path, expected, payload=None, auth=None, raw=None, content_type=None):
headers = {'Accept': 'application/json'}
if auth:
headers['Authorization'] = auth
if payload is not None:
raw = json.dumps(payload, ensure_ascii=True).encode('utf-8')
content_type = 'application/json'
if content_type:
headers['Content-Type'] = content_type
req = urllib.request.Request(self.base + path, data=raw, headers=headers, method=method)
try:
with urllib.request.urlopen(req, timeout=15) as response:
code = response.status
body = response.read()
reply_headers = response.headers
except urllib.error.HTTPError as error:
code = error.code
body = error.read()
reply_headers = error.headers
if code != expected:
raise AssertionError(f'{method} {path}: expected {expected}, received {code}')
if not reply_headers.get('X-Request-Id'):
raise AssertionError(f'{method} {path}: missing X-Request-Id')
self.count += 1
return json.loads(body) if body else None
def run(base):
c = Client(base)
prefix = uuid.uuid4().hex[:14]
name = 'ct_' + prefix
password = 'ContractTest-' + uuid.uuid4().hex[:16]
user_path = '/api/v1/users'
actor_path = '/api/v1/auth/sessions'
registration = {'username': name, 'display_name': 'Тест Unicode', 'password': password}
# Public registration must reject unknown fields and malformed Unicode.
c.call('POST', user_path, 400, payload={**registration, 'unknown': 'field'})
c.call('POST', user_path, 400, payload={**registration, 'display_name': '\ud800'})
c.call('POST', user_path, 415, raw=b'{}', content_type='text/plain')
user = c.call('POST', user_path, 201, payload=registration)
if user['username'] != name:
raise AssertionError('registration username mismatch')
basic = 'Basic ' + base64.b64encode((name + ':' + password).encode('utf-8')).decode('ascii')
# Login is Basic-only, without a JSON request body.
c.call('POST', actor_path, 400, auth=basic, payload={'unknown': 'field'})
session = c.call('POST', actor_path, 201, auth=basic)
bearer = 'Bearer ' + session['token']
# Protected POST endpoints must authenticate before parsing malformed JSON.
c.call('POST', '/api/v1/chats', 401, raw=b'{invalid', content_type='application/json')
c.call('POST', '/api/v1/chats', 400, auth=bearer, raw=b'{invalid', content_type='application/json')
c.call('POST', '/api/v1/chats', 415, auth=bearer, raw=b'{}', content_type='text/plain')
c.call('GET', '/api/v1/chats/' + uuid.uuid4().hex, 400, auth=bearer)
c.call('POST', '/api/v1/chats', 400, auth=bearer,
payload={'title': 'duplicate', 'member_ids': [user['id'], user['id']]})
c.call('POST', '/api/v1/chats', 400, auth=bearer,
payload={'title': 'missing author', 'member_ids': [str(uuid.uuid4())]})
chat1 = c.call('POST', '/api/v1/chats', 201, auth=bearer,
payload={'title': 'Page A', 'member_ids': [user['id']]})
chat2 = c.call('POST', '/api/v1/chats', 201, auth=bearer,
payload={'title': 'Page B', 'member_ids': [user['id']]})
msg_path1 = '/api/v1/chats/' + chat1['id'] + '/messages'
msg_path2 = '/api/v1/chats/' + chat2['id'] + '/messages'
c.call('POST', msg_path1, 401, raw=b'{invalid', content_type='application/json')
c.call('POST', msg_path1, 400, auth=bearer, raw=b'{invalid', content_type='application/json')
for i in range(2):
c.call('POST', msg_path1, 201, auth=bearer, payload={'text': f'Page test {i}'})
page = c.call('GET', msg_path1 + '?limit=1', 200, auth=bearer)
cursor = page.get('next_cursor')
if not cursor or len(page['items']) != 1:
raise AssertionError('expected next_cursor for two messages')
c.call('GET', msg_path2 + '?limit=1&cursor=' + urllib.parse.quote(cursor, safe=''), 400, auth=bearer)
c.call('GET', msg_path1 + '?limit=1&limit=2', 400, auth=bearer)
c.call('GET', msg_path1 + '?limit=1&cursor=@invalid@', 400, auth=bearer)
print(f'PASS: {c.count} Lab 2 contract edge-case HTTP checks')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--base-url', default='http://localhost:8080')
args = parser.parse_args()
run(args.base_url)
+69
View File
@@ -0,0 +1,69 @@
"""Simple grade-3 negative scenarios; run with the API+Postgres already started."""
import base64
import time
import uuid
from urllib.parse import quote
from client import Client, arguments, check, run
def configure(parser):
parser.add_argument('--expiry', action='store_true', help='Run only with SESSION_TTL_SECONDS=2')
def main():
args = arguments('Lab 2 student tests', configure)
c = Client(args.base_url, args.ca_file)
if args.expiry:
user = c.user('expiry')
c.call('GET', '/api/v1/users/me', actor=user, schema='User')
deadline = time.monotonic() + 12
while time.monotonic() < deadline:
response = c.call('GET', '/api/v1/users/me', (200, 401), actor=user, schema='User')
if response['status'] == 401:
print('PASS: Bearer session expires without logout')
return
time.sleep(0.25)
check(False, 'session did not expire; start API with SESSION_TTL_SECONDS=2')
alice, _, outsider, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id']
login_path = '/api/v1/auth/sessions'
json_header = {'Content-Type': 'application/json'}
c.call('POST', '/api/v1/users', 409, body=alice['registration'])
c.call('POST', '/api/v1/users', 400, raw=b'{invalid', headers=json_header)
c.call('POST', '/api/v1/chats', 401, raw=b'{invalid', headers=json_header)
c.call('POST', path + '/messages', 401, raw=b'{invalid', headers=json_header)
c.call('GET', path, 404, actor=outsider)
c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': alice['id']})
c.call('GET', path + '/messages?limit=0', 400, actor=alice)
c.call('GET', '/api/v1/chats/' + chat['id'].replace('-', ''), 400, actor=alice)
username = 'unicode_' + uuid.uuid4().hex[:12]
password = 'Пароль:abc-123456'
bad = f'{{"username":"{username}","display_name":"\\ud800","password":"{password}"}}'.encode('utf-8')
c.call('POST', '/api/v1/users', 400, raw=bad, headers=json_header)
registered = c.call('POST', '/api/v1/users', 201, schema='User',
body={'username': username, 'display_name': 'Проверка 👋', 'password': password})['json']
credentials = base64.b64encode(f'{username}:{password}'.encode('utf-8')).decode('ascii')
auth = {'Authorization': 'Basic ' + credentials}
c.call('POST', login_path, 400, body={}, headers=auth)
session = c.call('POST', login_path, 201, headers=auth, schema='Session')['json']
check(session['user'] == registered, 'Unicode Basic login returned the wrong user')
c.message(alice, chat, 'Первая запись')
c.message(alice, chat, 'Вторая запись')
first = c.call('GET', path + '/messages?limit=1', actor=alice, schema='MessagePage')['json']
check(bool(first['next_cursor']), 'missing second page')
c.call('GET', path + '/messages?cursor=' + quote(first['next_cursor'] + '!', safe=''), 400, actor=alice)
second = c.call('GET', path + '/messages?limit=1&cursor=' + quote(first['next_cursor'], safe=''),
actor=alice, schema='MessagePage')['json']
check(len(second['items']) == 1 and second['next_cursor'] is None, 'incorrect last page')
check(first['items'][0]['id'] != second['items'][0]['id'], 'pagination repeated a message')
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
c.call('GET', '/api/v1/users/me', 401, actor=alice)
print('PASS: validation, Unicode Basic login, access, pagination and logout')
if __name__ == '__main__':
run(main)