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

Handle mqtt.WebsocketConnectionError when connecting to the MQTT broker #133610

Merged
merged 1 commit into from
Dec 19, 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
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