1010import pytest
1111
1212from pytest_httpx import HTTPXMock
13- import websockets
1413from speechmatics import client
1514from speechmatics .batch_client import BatchClient
1615from speechmatics .exceptions import ForceEndSession
2524
2625from tests .utils import path_to_test_resource , default_ws_client_setup
2726
27+ try :
28+ # Try to import from new websockets >= 13
29+ from websockets .asyncio .client import connect
30+
31+ WS_HEADERS_KEY = "additional_headers"
32+ except ImportError :
33+ # Fall back to legacy websockets
34+ from websockets .legacy .client import connect
35+
36+ WS_HEADERS_KEY = "extra_headers"
37+
2838
2939def test_json_utf8 ():
3040 @client .json_utf8
@@ -229,13 +239,16 @@ async def test_send_message(mock_server, message_type: str, message_data: Any):
229239 """
230240 ws_client , _ , _ = default_ws_client_setup (mock_server .url )
231241 ws_client .session_running = True
232-
233- async with websockets .connect (
242+ ws_kwargs = {
243+ "ssl" : ws_client .connection_settings .ssl_context ,
244+ "ping_timeout" : ws_client .connection_settings .ping_timeout_seconds ,
245+ "max_size" : None ,
246+ WS_HEADERS_KEY : None ,
247+ }
248+
249+ async with connect (
234250 mock_server .url ,
235- ssl = ws_client .connection_settings .ssl_context ,
236- ping_timeout = ws_client .connection_settings .ping_timeout_seconds ,
237- max_size = None ,
238- additional_headers = None ,
251+ ** ws_kwargs ,
239252 ) as ws_client .websocket :
240253 await ws_client .send_message (message_type , message_data )
241254 assert message_type in [
@@ -387,7 +400,7 @@ async def mock_connect(*_, **__):
387400
388401 mock_logger_error_method = MagicMock ()
389402
390- with patch ("websockets .connect" , mock_connect ):
403+ with patch ("speechmatics.client .connect" , mock_connect ):
391404 with patch .object (client .LOGGER , "error" , mock_logger_error_method ):
392405 try :
393406 ws_client .run_synchronously (
@@ -411,7 +424,7 @@ def call_exit(*args, **kwargs):
411424 mock_server .url
412425 )
413426 stream = MagicMock ()
414- with patch ("websockets .connect" , connect_mock ):
427+ with patch ("speechmatics.client .connect" , connect_mock ):
415428 try :
416429 ws_client .run_synchronously (
417430 transcription_config = transcription_config ,
@@ -422,7 +435,7 @@ def call_exit(*args, **kwargs):
422435 except Exception :
423436 assert len (connect_mock .mock_calls ) == 1
424437 assert (
425- connect_mock .mock_calls [0 ][2 ]["additional_headers" ] == extra_headers
438+ connect_mock .mock_calls [0 ][2 ][WS_HEADERS_KEY ] == extra_headers
426439 ), f"Extra headers don't appear in the call list = { connect_mock .mock_calls } "
427440
428441
0 commit comments