import asyncio import threading from fastapi.testclient import TestClient import app.main as main_module def test_tts_cancel_is_processed_while_chat_turn_is_running(monkeypatch): chat_started = threading.Event() cancel_processed = threading.Event() release_chat = threading.Event() async def fake_handle_event(project_id, event_type, data): if event_type == "CHAT_TURN": chat_started.set() while not release_chat.is_set(): await asyncio.sleep(0.01) elif event_type == "TTS_CANCEL": cancel_processed.set() release_chat.set() monkeypatch.setenv("DEPLOYMENT_ENV", "demo") monkeypatch.setattr(main_module, "handle_event", fake_handle_event) with TestClient(main_module.app) as client: with client.websocket_connect("/ws/project") as socket: socket.send_json({"type": "CHAT_TURN", "data": {}}) assert chat_started.wait(timeout=1) socket.send_json({"type": "TTS_CANCEL", "data": {"generation_id": "tts_1"}}) try: assert cancel_processed.wait(timeout=1) finally: release_chat.set()