diff --git a/tests/components/mqtt/test_init.py b/tests/components/mqtt/test_init.py index cfb8ce7ac04941..f948889fd80c87 100644 --- a/tests/components/mqtt/test_init.py +++ b/tests/components/mqtt/test_init.py @@ -2534,6 +2534,75 @@ async def wait_birth(msg: ReceiveMessage) -> None: ) +@pytest.mark.parametrize( + "mqtt_config_entry_data", + [ + { + mqtt.CONF_BROKER: "mock-broker", + mqtt.CONF_BIRTH_MESSAGE: { + mqtt.ATTR_TOPIC: "homeassistant/status", + mqtt.ATTR_PAYLOAD: "online", + mqtt.ATTR_QOS: 0, + mqtt.ATTR_RETAIN: False, + }, + } + ], +) +async def test_subscription_done_when_birth_message_is_sent( + hass: HomeAssistant, + mqtt_client_mock: MqttMockPahoClient, + mqtt_config_entry_data, + mqtt_mock_entry: MqttMockHAClientGenerator, +) -> None: + """Test sending birth message until initial subscription has been completed.""" + mqtt_mock = await mqtt_mock_entry() + + hass.set_state(CoreState.starting) + birth = asyncio.Event() + + await hass.async_block_till_done() + + entry = MockConfigEntry(domain=mqtt.DOMAIN, data=mqtt_config_entry_data) + entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + mqtt_component_mock = MagicMock( + return_value=hass.data["mqtt"].client, + wraps=hass.data["mqtt"].client, + ) + mqtt_component_mock._mqttc = mqtt_client_mock + + hass.data["mqtt"].client = mqtt_component_mock + mqtt_mock = hass.data["mqtt"].client + mqtt_mock.reset_mock() + + @callback + def wait_birth(msg: ReceiveMessage) -> None: + """Handle birth message.""" + birth.set() + + mqtt_client_mock.reset_mock() + with patch("homeassistant.components.mqtt.client.DISCOVERY_COOLDOWN", 0.0): + await mqtt.async_subscribe(hass, "homeassistant/status", wait_birth) + mqtt_client_mock.on_connect(None, None, 0, 0) + await hass.async_block_till_done() + hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED) + # We wait until we receive a birth message + await asyncio.wait_for(birth.wait(), 1) + # Assert we already have subscribed at the client + # for new config payloads at the time we the birth message is received + assert ("homeassistant/+/+/config", 0) in help_all_subscribe_calls( + mqtt_client_mock + ) + assert ("homeassistant/+/+/+/config", 0) in help_all_subscribe_calls( + mqtt_client_mock + ) + mqtt_client_mock.publish.assert_called_with( + "homeassistant/status", "online", 0, False + ) + + @pytest.mark.parametrize( "mqtt_config_entry_data", [