"""Inherited contract checks (stdlib only). Needs running LB + 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 method == 'POST' and path.endswith('/messages'): headers['Idempotency-Key'] = uuid.uuid4().hex 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') if not reply_headers.get('X-Instance-Id'): raise AssertionError(f'{method} {path}: missing X-Instance-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)