#!/usr/bin/env python3 """Regression: blocking boundaries must execute off the ASGI event-loop thread. Run inside the API image; no DB queries, external clients or extra dependencies. """ import asyncio from collections import defaultdict from contextlib import ExitStack from datetime import datetime, timezone import json import threading import unittest from unittest.mock import patch from uuid import UUID from psycopg import OperationalError from src import main USER_ID = '11111111-1111-4111-8111-111111111111' CHAT_ID = '22222222-2222-4222-8222-222222222222' USER = {'id': USER_ID, 'username': 'synthetic', 'display_name': 'Synthetic', 'created_at': '2026-11-06T00:00:00Z'} CHAT = {'id': CHAT_ID, 'title': 'Synthetic', 'member_ids': [USER_ID], 'created_at': USER['created_at']} MESSAGE = {'id': '33333333-3333-4333-8333-333333333333', 'chat_id': CHAT_ID, 'sender_id': USER_ID, 'text': 'test', 'created_at': USER['created_at']} async def request(method, path, body=None, headers=None): encoded = json.dumps(body).encode() if body is not None else b'' request_headers = {'host': 'test', 'authorization': 'Bearer ' + 'a'*43} if body is not None: request_headers['content-type'] = 'application/json' request_headers.update(headers or {}) scope = {'type': 'http', 'asgi': {'version': '3.0', 'spec_version': '2.4'}, 'http_version': '1.1', 'method': method, 'scheme': 'http', 'path': path, 'raw_path': path.encode(), 'query_string': b'', 'root_path': '', 'server': ('test', 80), 'client': ('127.0.0.1', 1234), 'headers': [(k.encode(), v.encode()) for k, v in request_headers.items()]} sent = [] received = False async def receive(): nonlocal received if not received: received = True return {'type': 'http.request', 'body': encoded, 'more_body': False} await asyncio.Event().wait() async def send(message): sent.append(message) await asyncio.wait_for(main.app(scope, receive, send), timeout=5) start = next(m for m in sent if m['type'] == 'http.response.start') data = b''.join(m.get('body', b'') for m in sent if m['type'] == 'http.response.body') return start['status'], dict(start['headers']), json.loads(data) if data else None class EventLoopTests(unittest.IsolatedAsyncioTestCase): async def asyncSetUp(self): self.loop_thread = threading.get_ident() self.calls = defaultdict(list) self.stack = ExitStack() self.addCleanup(self.stack.close) def blocking(self, name, result=None, error=None): def spy(*args, **kwargs): self.calls[name].append(threading.get_ident()) if error: raise error return result self.stack.enter_context(patch.object(main, name, side_effect=spy)) def assert_off_loop(self, *names): for name in names: self.assertTrue(self.calls[name], name + ' was not exercised') self.assertNotIn(self.loop_thread, self.calls[name], name + ' blocked the event loop') async def test_registration_hash_and_insert(self): self.blocking('hash_password', 'synthetic-hash') self.blocking('insert_user', USER) status, headers, _ = await request('POST', '/api/v1/users', {'username': 'synthetic', 'display_name': 'Synthetic', 'password': 'synthetic-password'}) self.assertEqual(status, 201) self.assertIn(b'x-instance-id', headers) self.assert_off_loop('hash_password', 'insert_user') async def test_login_lookup_verify_and_session(self): import base64 row = {**USER, 'id': UUID(USER_ID), 'password_hash': 'synthetic-hash', 'created_at': datetime.now(timezone.utc)} self.blocking('find_user_by_username', row) self.blocking('verify_password', True) self.blocking('create_session') basic = base64.b64encode(b'synthetic:synthetic-password').decode() status, _, _ = await request('POST', '/api/v1/auth/sessions', headers={'authorization': 'Basic '+basic}) self.assertEqual(status, 201) self.assert_off_loop('find_user_by_username', 'verify_password', 'create_session') async def test_chat_session_and_transaction(self): self.blocking('find_session_user_cached', USER) self.blocking('insert_chat', CHAT) status, _, _ = await request('POST', '/api/v1/chats', {'title': 'Synthetic', 'member_ids': [USER_ID]}) self.assertEqual(status, 201) self.assert_off_loop('find_session_user_cached', 'insert_chat') async def test_message_session_access_and_atomic_insert(self): self.blocking('find_session_user_cached', USER) self.blocking('find_chat', CHAT) self.blocking('insert_message', MESSAGE) status, _, _ = await request('POST', '/api/v1/chats/'+CHAT_ID+'/messages', {'text': 'test'}, {'idempotency-key': 'test-key'}) self.assertEqual(status, 201) self.assert_off_loop('find_session_user_cached', 'find_chat', 'insert_message') async def test_lifecycle_pool_open_and_close(self): self.blocking('open_database') self.blocking('close_database') await main.app.router.startup() await main.app.router.shutdown() self.assert_off_loop('open_database', 'close_database') async def test_openapi_does_not_read_file_in_request(self): with patch('pathlib.Path.read_text', side_effect=AssertionError('Disk I/O during HTTP request')): status, _, data = await request('GET', '/openapi.json') self.assertEqual(status, 200) self.assertEqual(data['info']['version'], '1.3.0') async def test_thread_exception_preserves_error_contract(self): self.blocking('hash_password', 'synthetic-hash') self.blocking('insert_user', error=OperationalError('synthetic outage')) status, headers, data = await request('POST', '/api/v1/users', {'username': 'synthetic', 'display_name': 'Synthetic', 'password': 'synthetic-password'}) self.assertEqual(status, 503) self.assertEqual(data['error']['code'], 'unavailable') self.assertEqual(data['error']['request_id'], headers[b'x-request-id'].decode()) self.assert_off_loop('hash_password', 'insert_user') if __name__ == '__main__': unittest.main(verbosity=2)