Fix client_id not generated when connecting to the MQTT broker (#140264)

Fix client_id not generated when connecting to the MQTT broker
This commit is contained in:
Jan Bouwhuis 2025-03-10 11:04:49 +01:00 committed by Franck Nijhof
parent e4b31640b3
commit 5d9d6f099c
No known key found for this signature in database
GPG Key ID: D62583BA8AB11CA3
2 changed files with 42 additions and 4 deletions

View File

@ -15,6 +15,7 @@ import socket
import ssl
import time
from typing import TYPE_CHECKING, Any
from uuid import uuid4
import certifi
@ -292,7 +293,7 @@ class MqttClientSetup:
"""
# We don't import on the top because some integrations
# should be able to optionally rely on MQTT.
import paho.mqtt.client as mqtt # pylint: disable=import-outside-toplevel
from paho.mqtt import client as mqtt # pylint: disable=import-outside-toplevel
# pylint: disable-next=import-outside-toplevel
from .async_client import AsyncMQTTClient
@ -309,9 +310,10 @@ class MqttClientSetup:
clean_session = True
if (client_id := config.get(CONF_CLIENT_ID)) is None:
# PAHO MQTT relies on the MQTT server to generate random client IDs.
# However, that feature is not mandatory so we generate our own.
client_id = None
# PAHO MQTT relies on the MQTT server to generate random client ID
# for protocol version 3.1, however, that feature is not mandatory
# so we generate our own.
client_id = mqtt._base62(uuid4().int, padding=22) # noqa: SLF001
transport: str = config.get(CONF_TRANSPORT, DEFAULT_TRANSPORT)
self._client = AsyncMQTTClient(
callback_api_version=mqtt.CallbackAPIVersion.VERSION2,

View File

@ -1556,6 +1556,42 @@ async def test_setup_uses_certificate_on_certificate_set_to_auto_and_insecure(
assert insecure_check["insecure"] == insecure_param
@pytest.mark.parametrize(
("mqtt_config_entry_data", "client_id"),
[
(
{
mqtt.CONF_BROKER: "mock-broker",
"client_id": "random01234random0124",
},
"random01234random0124",
),
(
{
mqtt.CONF_BROKER: "mock-broker",
},
None,
),
],
)
async def test_client_id_is_set(
hass: HomeAssistant,
mqtt_mock_entry: MqttMockHAClientGenerator,
client_id: str | None,
) -> None:
"""Test setup defaults for tls."""
with patch(
"homeassistant.components.mqtt.async_client.AsyncMQTTClient"
) as async_client_mock:
await mqtt_mock_entry()
await hass.async_block_till_done()
assert async_client_mock.call_count == 1
call_params: dict[str, Any] = async_client_mock.call_args[1]
assert "client_id" in call_params
assert client_id is None or client_id == call_params["client_id"]
assert call_params["client_id"] is not None
@pytest.mark.parametrize(
"mqtt_config_entry_data",
[