M8-R01: add configurable MQTT client identity

This commit is contained in:
2026-08-24 00:44:28 +02:00
parent 2a47dab272
commit e59c192097
12 changed files with 184 additions and 15 deletions
+45 -1
View File
@@ -9,7 +9,7 @@ from unittest.mock import MagicMock, patch
import pytest
from fastapi.testclient import TestClient
from app.integrations.mqtt import MqttManager
from app.integrations.mqtt import MqttManager, mqtt_source_client_id, mqtt_test_client_id
# ---------------------------------------------------------------------------
@@ -24,6 +24,7 @@ def _make_settings(
mqtt_username: str = "",
mqtt_password: str = "",
mqtt_tls_enabled: bool = False,
mqtt_client_id: str = "home-automation",
ha_discovery_prefix: str = "homeassistant",
):
"""Return a simple namespace that acts like a Settings object for MqttManager tests."""
@@ -34,6 +35,7 @@ def _make_settings(
s.mqtt_username = mqtt_username
s.mqtt_password = mqtt_password
s.mqtt_tls_enabled = mqtt_tls_enabled
s.mqtt_client_id = mqtt_client_id
s.ha_discovery_prefix = ha_discovery_prefix
return s
@@ -120,6 +122,34 @@ def test_connect_creates_paho_client_with_version2() -> None:
)
def test_connect_uses_configured_client_id() -> None:
manager = MqttManager()
settings = _make_settings(mqtt_client_id="home-automation-dev")
mock_client = MagicMock()
with patch("app.integrations.mqtt.mqtt.Client", return_value=mock_client) as mock_cls:
manager.connect(settings)
assert mock_cls.call_args.kwargs["client_id"] == "home-automation-dev"
def test_deployment_client_id_variants_are_distinct() -> None:
production_ids = {
"home-automation",
mqtt_source_client_id("home-automation", 7),
mqtt_test_client_id("home-automation"),
}
development_ids = {
"home-automation-dev",
mqtt_source_client_id("home-automation-dev", 7),
mqtt_test_client_id("home-automation-dev"),
}
assert len(production_ids) == 3
assert len(development_ids) == 3
assert production_ids.isdisjoint(development_ids)
def test_connect_sets_credentials_when_username_provided() -> None:
manager = MqttManager()
settings = _make_settings(mqtt_username="user", mqtt_password="s3cr3t")
@@ -431,3 +461,17 @@ def test_run_mqtt_test_raises_connection_error_on_timeout() -> None:
with patch("threading.Event", side_effect=_make_event):
with pytest.raises(_MqttConnectionError, match="timed out"):
_run_mqtt_test(settings)
def test_run_mqtt_test_uses_deployment_scoped_client_id() -> None:
from app.api.routes.api.config import _run_mqtt_test, _MqttConnectionError
settings = _make_settings(mqtt_client_id="home-automation-dev")
mock_client = MagicMock()
mock_client.connect.side_effect = OSError("Connection refused")
with patch("paho.mqtt.client.Client", return_value=mock_client) as mock_cls:
with pytest.raises(_MqttConnectionError):
_run_mqtt_test(settings)
assert mock_cls.call_args.kwargs["client_id"] == "home-automation-dev-test"