Skip to content

Commit

Permalink
Handle mqtt.WebsocketConnectionError when connecting to the MQTT brok…
Browse files Browse the repository at this point in the history
…er (#133610)

fixes #132985
  • Loading branch information
bdraco authored Dec 19, 2024
1 parent b261c7f commit 551a584
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
2 changes: 1 addition & 1 deletion homeassistant/components/mqtt/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -661,7 +661,7 @@ async def async_connect(self, client_available: asyncio.Future[bool]) -> None:
self.conf.get(CONF_PORT, DEFAULT_PORT),
self.conf.get(CONF_KEEPALIVE, DEFAULT_KEEPALIVE),
)
except OSError as err:
except (OSError, mqtt.WebsocketConnectionError) as err:
_LOGGER.error("Failed to connect to MQTT server due to exception: %s", err)
self._async_connection_result(False)
finally:
Expand Down
11 changes: 9 additions & 2 deletions tests/components/mqtt/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1403,8 +1403,15 @@ def _mock_ack(topic: str, qos: int = 0) -> tuple[int, int]:
assert not mock_debouncer.is_set()


@pytest.mark.parametrize(
"exception",
[
OSError("Connection error"),
paho_mqtt.WebsocketConnectionError("Connection error"),
],
)
async def test_setup_raises_config_entry_not_ready_if_no_connect_broker(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, exception: Exception
) -> None:
"""Test for setup failure if connection to broker is missing."""
entry = MockConfigEntry(domain=mqtt.DOMAIN, data={mqtt.CONF_BROKER: "test-broker"})
Expand All @@ -1413,7 +1420,7 @@ async def test_setup_raises_config_entry_not_ready_if_no_connect_broker(
with patch(
"homeassistant.components.mqtt.async_client.AsyncMQTTClient"
) as mock_client:
mock_client().connect = MagicMock(side_effect=OSError("Connection error"))
mock_client().connect = MagicMock(side_effect=exception)
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert "Failed to connect to MQTT server due to exception:" in caplog.text
Expand Down

0 comments on commit 551a584

Please sign in to comment.