Skip to content
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
4 changes: 3 additions & 1 deletion homeassistant/components/mqtt/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -872,7 +872,9 @@ async def async_subscribe(
subscription = Subscription(topic, msg_callback, qos, encoding)
self.subscriptions.append(subscription)

await self._async_perform_subscription(topic, qos)
# Only subscribe if currently connected.
if self.connected:
await self._async_perform_subscription(topic, qos)

@callback
def async_remove() -> None:
Expand Down
12 changes: 12 additions & 0 deletions tests/components/mqtt/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -608,6 +608,9 @@ def side_effect(*args):

self.hass.data["mqtt"]._mqttc.subscribe.side_effect = side_effect

# Fake that the client is connected
self.hass.data["mqtt"].connected = True

calls_a = mock.MagicMock()
mqtt.subscribe(self.hass, "test/state", calls_a)
self.hass.block_till_done()
Expand All @@ -620,6 +623,9 @@ def side_effect(*args):

def test_not_calling_unsubscribe_with_active_subscribers(self):
"""Test not calling unsubscribe() when other subscribers are active."""
# Fake that the client is connected
self.hass.data["mqtt"].connected = True

unsub = mqtt.subscribe(self.hass, "test/state", None)
mqtt.subscribe(self.hass, "test/state", None)
self.hass.block_till_done()
Expand All @@ -631,6 +637,9 @@ def test_not_calling_unsubscribe_with_active_subscribers(self):

def test_restore_subscriptions_on_reconnect(self):
"""Test subscriptions are restored on reconnect."""
# Fake that the client is connected
self.hass.data["mqtt"].connected = True

mqtt.subscribe(self.hass, "test/state", None)
self.hass.block_till_done()
assert self.hass.data["mqtt"]._mqttc.subscribe.call_count == 1
Expand All @@ -642,6 +651,9 @@ def test_restore_subscriptions_on_reconnect(self):

def test_restore_all_active_subscriptions_on_reconnect(self):
"""Test active subscriptions are restored correctly on reconnect."""
# Fake that the client is connected
self.hass.data["mqtt"].connected = True

self.hass.data["mqtt"]._mqttc.subscribe.side_effect = (
(0, 1),
(0, 2),
Expand Down