Skip to content

Commit

Permalink
Add send_message method to the client and test
Browse files Browse the repository at this point in the history
  • Loading branch information
dln22 committed Oct 3, 2024
1 parent 03ef7e1 commit 6d05087
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
27 changes: 27 additions & 0 deletions speechmatics/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -520,6 +520,33 @@ def run_synchronously(self, *args, timeout=None, **kwargs):
asyncio.run(asyncio.wait_for(self.run(*args, **kwargs), timeout=timeout))


async def send_message(self, msg):
"""
Sends a message to the server.
"""
if self.session_running:
assert self.websocket, "Websocket hasn't been instantiated"
try:
LOGGER.info(f"Sending msg={msg}")
await self.websocket.send(json.dumps(msg))
except TypeError as ex:
LOGGER.info(
f"Cannot send this type of object msg={msg} as a message. Exception occurred:%s",
repr(ex),
)
return
except websockets.exceptions.ConnectionClosedOK:
# Can occur if a timeout has closed the connection.
LOGGER.info("Cannot send from a closed websocket.")
return
except websockets.exceptions.ConnectionClosedError:
LOGGER.info("Disconnected while sending a message().")
return
else:
LOGGER.info(
f"Websocket client isn't running - Not sending the message = {msg}",
)

async def _get_temp_token(api_key):
"""
Used to get a temporary token from management platform api for SaaS users
Expand Down
31 changes: 31 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import pytest

from pytest_httpx import HTTPXMock
import websockets
from speechmatics import client
from speechmatics.batch_client import BatchClient
from speechmatics.exceptions import ForceEndSession
Expand Down Expand Up @@ -196,6 +197,36 @@ def test_run_synchronously_with_timeout(mock_server):
)


@pytest.mark.asyncio
@pytest.mark.parametrize(
"message",
[
pytest.param("random_str", id="Sending pure string"),
pytest.param(243, id="Sending random number"),
pytest.param({}, id="Sending empty dict"),
pytest.param({"message": "expected"}, id="Sending dict with strs"),
pytest.param({"3232": 43}, id="Sending dict with numbers"),
],
)
async def test_send_message(mock_server, message):
"""
Tests that the client.send_message method correctly sends the message to the server.
"""
ws_client, _, _ = default_ws_client_setup(mock_server.url)
ws_client.session_running = True

async with websockets.connect(
mock_server.url,
ssl=ws_client.connection_settings.ssl_context,
ping_timeout=ws_client.connection_settings.ping_timeout_seconds,
max_size=None,
extra_headers=None,
) as ws_client.websocket:
await ws_client.send_message(message)
assert message in mock_server.messages_received



@pytest.mark.parametrize(
"client_message_type, expect_received_count, expect_sent_count",
[
Expand Down

0 comments on commit 6d05087

Please sign in to comment.