Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add try except to messaging connection #345

Merged
merged 4 commits into from
Jan 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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