Skip to content

Commit

Permalink
Add try except to messaging connection (#345)
Browse files Browse the repository at this point in the history
Just a try except around the connection attempt. It displays the
failure to connect in the logs but does not fail fast. It allows the
rest of the application setup to complete just without a connection to a
message bus. You can then `crtl+c` to close it.

I was advised to just add this fix until the subprocess work is done
then we can re-address the behaviour we want.
  • Loading branch information
abbiemery committed Jan 9, 2024
1 parent c5bf8f9 commit cad6bc0
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 6 deletions.
17 changes: 11 additions & 6 deletions src/blueapi/messaging/stomptemplate.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,12 +180,17 @@ def finished_connecting(_: Frame):
self._listener.on_disconnected = self._on_disconnected

LOGGER.info("Connecting...")
self._conn.connect(
username=self._authentication.username,
passcode=self._authentication.passcode,
wait=True,
)
connected.wait()

try:
self._conn.connect(
username=self._authentication.username,
passcode=self._authentication.passcode,
wait=True,
)
connected.wait()
except ConnectFailedException as ex:
LOGGER.exception(msg="Failed to connect to message bus", exc_info=ex)

self._ensure_subscribed()

def _ensure_subscribed(self, sub_ids: Optional[List[str]] = None) -> None:
Expand Down
26 changes: 26 additions & 0 deletions tests/messaging/test_stomptemplate.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@
from typing import Any, Iterable, List, Type

import pytest
from mock import ANY, MagicMock, patch
from pydantic import BaseModel, BaseSettings, Field
from stomp import Connection
from stomp.exception import ConnectFailedException

from blueapi.config import StompConfig
from blueapi.messaging import MessageContext, MessagingTemplate, StompMessagingTemplate
Expand Down Expand Up @@ -159,6 +162,29 @@ def test_reconnect(template: MessagingTemplate, test_queue: str) -> None:
assert reply == "ack"


@pytest.fixture()
def failing_template() -> MessagingTemplate:
def connection_exception(*args, **kwargs):
raise ConnectFailedException

connection = Connection()
connection.connect = MagicMock(side_effect=connection_exception)
return StompMessagingTemplate(connection)


@pytest.mark.stomp
def test_failed_connect(failing_template: MessagingTemplate, test_queue: str) -> None:
assert not failing_template.is_connected()
with patch(
"blueapi.messaging.stomptemplate.LOGGER.error", autospec=True
) as mock_logger:
failing_template.connect()
assert not failing_template.is_connected()
mock_logger.assert_called_once_with(
"Failed to connect to message bus", exc_info=ANY
)


@pytest.mark.stomp
def test_correlation_id(
template: MessagingTemplate, test_queue: str, test_queue_2: str
Expand Down

0 comments on commit cad6bc0

Please sign in to comment.