Add middleware option to Volkszaehler integration (#182511)

Co-authored-by: Joostlek <joostlek@outlook.com>
This commit is contained in:
StefanSchoof
2026-11-24 21:19:55 +01:00
committed by GitHub
co-authored by Joostlek
parent 78a85aa154
commit a124dfa396
7 changed files with 112 additions and 16 deletions
@@ -13,7 +13,7 @@ from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.util import Throttle
from .const import SUBENTRY_TYPE_CHANNEL
from .const import CONF_MIDDLEWARE, DEFAULT_MIDDLEWARE, SUBENTRY_TYPE_CHANNEL
_PLATFORMS: list[Platform] = [Platform.SENSOR]
@@ -58,6 +58,7 @@ async def async_setup_entry(
subentry.data[CONF_UUID],
host=entry.data[CONF_HOST],
port=entry.data[CONF_PORT],
middleware=entry.data.get(CONF_MIDDLEWARE, DEFAULT_MIDDLEWARE),
)
)
await vz_data.async_update()
@@ -24,7 +24,13 @@ from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from . import VolkszaehlerConfigEntry
from .const import DEFAULT_PORT, DOMAIN, SUBENTRY_TYPE_CHANNEL
from .const import (
CONF_MIDDLEWARE,
DEFAULT_MIDDLEWARE,
DEFAULT_PORT,
DOMAIN,
SUBENTRY_TYPE_CHANNEL,
)
_LOGGER = logging.getLogger(__name__)
@@ -33,6 +39,7 @@ STEP_USER_DATA_SCHEMA = probatio.Schema(
probatio.Required(CONF_HOST): cv.string,
probatio.Required(CONF_PORT, default=DEFAULT_PORT): probatio.Port(),
probatio.Required(CONF_UUID): cv.string,
probatio.Required(CONF_MIDDLEWARE, default=DEFAULT_MIDDLEWARE): bool,
}
)
@@ -41,6 +48,7 @@ RECONFIGURE_SCHEMA = probatio.Schema(
{
probatio.Required(CONF_HOST): cv.string,
probatio.Required(CONF_PORT, default=DEFAULT_PORT): probatio.Port(),
probatio.Required(CONF_MIDDLEWARE, default=DEFAULT_MIDDLEWARE): bool,
}
)
@@ -52,6 +60,7 @@ async def _validate_input(hass: HomeAssistant, data: dict[str, Any]) -> None:
uuid=data[CONF_UUID],
host=data[CONF_HOST],
port=data[CONF_PORT],
middleware=data.get(CONF_MIDDLEWARE, DEFAULT_MIDDLEWARE),
)
await api.get_data()
@@ -135,7 +144,9 @@ class VolkszaehlerConfigFlow(ConfigFlow, domain=DOMAIN):
entry = self._get_reconfigure_entry()
if user_input is not None:
self._async_abort_entries_match(user_input)
self._async_abort_entries_match(
{CONF_HOST: user_input[CONF_HOST], CONF_PORT: user_input[CONF_PORT]}
)
for subentry in entry.get_subentries_of_type(SUBENTRY_TYPE_CHANNEL):
if error := await _async_validate_input_errors(
self.hass,
@@ -143,6 +154,7 @@ class VolkszaehlerConfigFlow(ConfigFlow, domain=DOMAIN):
CONF_HOST: user_input[CONF_HOST],
CONF_PORT: user_input[CONF_PORT],
CONF_UUID: subentry.data[CONF_UUID],
CONF_MIDDLEWARE: user_input[CONF_MIDDLEWARE],
},
):
return self.async_show_form(
@@ -167,6 +179,9 @@ class VolkszaehlerConfigFlow(ConfigFlow, domain=DOMAIN):
{
CONF_HOST: entry.data[CONF_HOST],
CONF_PORT: entry.data.get(CONF_PORT, DEFAULT_PORT),
CONF_MIDDLEWARE: entry.data.get(
CONF_MIDDLEWARE, DEFAULT_MIDDLEWARE
),
},
),
)
@@ -194,6 +209,7 @@ class VolkszaehlerConfigFlow(ConfigFlow, domain=DOMAIN):
data={
CONF_HOST: user_input[CONF_HOST],
CONF_PORT: user_input[CONF_PORT],
CONF_MIDDLEWARE: user_input[CONF_MIDDLEWARE],
},
subentries=[
{
@@ -236,6 +252,9 @@ class VolkszaehlerSubentryFlow(ConfigSubentryFlow):
CONF_HOST: entry.data[CONF_HOST],
CONF_PORT: entry.data[CONF_PORT],
CONF_UUID: user_input[CONF_UUID],
CONF_MIDDLEWARE: entry.data.get(
CONF_MIDDLEWARE, DEFAULT_MIDDLEWARE
),
},
):
errors["base"] = error
@@ -2,6 +2,8 @@
DOMAIN = "volkszaehler"
SUBENTRY_TYPE_CHANNEL = "channel"
CONF_MIDDLEWARE = "middleware"
DEFAULT_MIDDLEWARE = True
DEFAULT_HOST = "localhost"
DEFAULT_NAME = "Volkszaehler"
DEFAULT_PORT = 80
@@ -13,10 +13,12 @@
"reconfigure": {
"data": {
"host": "[%key:common::config_flow::data::host%]",
"middleware": "[%key:component::volkszaehler::config::step::user::data::middleware%]",
"port": "[%key:common::config_flow::data::port%]"
},
"data_description": {
"host": "[%key:component::volkszaehler::config::step::user::data_description::host%]",
"middleware": "[%key:component::volkszaehler::config::step::user::data_description::middleware%]",
"port": "[%key:component::volkszaehler::config::step::user::data_description::port%]"
},
"description": "Update the Volkszaehler server connection.",
@@ -25,11 +27,13 @@
"user": {
"data": {
"host": "[%key:common::config_flow::data::host%]",
"middleware": "Use middleware.php",
"port": "[%key:common::config_flow::data::port%]",
"uuid": "UUID"
},
"data_description": {
"host": "IP address or hostname of the Volkszaehler server.",
"middleware": "Enable if your Volkszaehler instance uses 'middleware.php' in the URL (standard setup). Disable for Docker setups or custom endpoints without 'middleware.php'.",
"port": "Port number of the Volkszaehler server.",
"uuid": "UUID of the channel to monitor. In the Volkszaehler Web UI, click the (i) icon next to the channel to find it."
},
+26 -7
View File
@@ -6,7 +6,11 @@ from unittest.mock import AsyncMock, Mock, patch
import pytest
from pytest_homeassistant.common import MockConfigEntry
from homeassistant.components.volkszaehler.const import DOMAIN, SUBENTRY_TYPE_CHANNEL
from homeassistant.components.volkszaehler.const import (
CONF_MIDDLEWARE,
DOMAIN,
SUBENTRY_TYPE_CHANNEL,
)
from homeassistant.config_entries import ConfigSubentryData
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_UUID
@@ -36,20 +40,35 @@ def mock_client_api() -> Generator[Mock]:
):
api = mock_api.return_value
api.get_data = AsyncMock(return_value=None)
mock_api.get_data = api.get_data
yield api
yield mock_api
@pytest.fixture
def mock_config_entry() -> MockConfigEntry:
"""Fixture for a config entry with one existing channel subentry."""
"""Fixture for a config entry with one existing channel subentry and middleware enabled."""
return _mock_config_entry(middleware=True)
@pytest.fixture
def mock_config_entry_without_middleware() -> MockConfigEntry:
"""Fixture for a Volkszaehler config entry without middleware."""
return _mock_config_entry()
def _mock_config_entry(*, middleware: bool | None = None) -> MockConfigEntry:
"""Create a Volkszaehler config entry for testing."""
data = {
CONF_HOST: "localhost",
CONF_PORT: 80,
}
if middleware is not None:
data[CONF_MIDDLEWARE] = middleware
return MockConfigEntry(
domain=DOMAIN,
title="localhost",
data={
CONF_HOST: "localhost",
CONF_PORT: 80,
},
data=data,
subentries_data=[
ConfigSubentryData(
subentry_type=SUBENTRY_TYPE_CHANNEL,
@@ -9,7 +9,11 @@ from volkszaehler.exceptions import (
VolkszaehlerNoDataAvailable,
)
from homeassistant.components.volkszaehler.const import DOMAIN, SUBENTRY_TYPE_CHANNEL
from homeassistant.components.volkszaehler.const import (
CONF_MIDDLEWARE,
DOMAIN,
SUBENTRY_TYPE_CHANNEL,
)
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import (
CONF_HOST,
@@ -42,6 +46,7 @@ async def test_create_entry(
CONF_UUID: "test-uuid",
CONF_HOST: "localhost",
CONF_PORT: 80,
CONF_MIDDLEWARE: False,
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
@@ -49,6 +54,7 @@ async def test_create_entry(
assert result["data"] == {
CONF_HOST: "localhost",
CONF_PORT: 80,
CONF_MIDDLEWARE: False,
}
entry = result["result"]
@@ -60,6 +66,7 @@ async def test_create_entry(
assert subentry.data == {CONF_UUID: "test-uuid"}
assert mock_api.get_data.call_count == 1
assert mock_api.call_args.kwargs["middleware"] is False
assert len(mock_setup_entry.mock_calls) == 1
@@ -82,6 +89,7 @@ async def test_user_errors(
CONF_UUID: "test-uuid",
CONF_HOST: "localhost",
CONF_PORT: 80,
CONF_MIDDLEWARE: True,
}
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
@@ -104,6 +112,7 @@ async def test_user_errors(
assert result["data"] == {
CONF_HOST: "localhost",
CONF_PORT: 80,
CONF_MIDDLEWARE: True,
}
@@ -261,6 +270,7 @@ async def test_user_duplicate_uuid_from_entry_unique_id(
CONF_UUID: "existing-uuid",
CONF_HOST: "new-host",
CONF_PORT: 80,
CONF_MIDDLEWARE: True,
},
)
@@ -309,16 +319,25 @@ async def test_reconfigure(
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
assert (
get_schema_suggested_value(result["data_schema"].schema, CONF_MIDDLEWARE)
is True
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_HOST: "new-host", CONF_PORT: 9080},
{CONF_HOST: "new-host", CONF_PORT: 9080, CONF_MIDDLEWARE: False},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert mock_config_entry.data == {CONF_HOST: "new-host", CONF_PORT: 9080}
assert mock_config_entry.data == {
CONF_HOST: "new-host",
CONF_PORT: 9080,
CONF_MIDDLEWARE: False,
}
assert mock_api.get_data.call_count == 1
assert mock_api.call_args.kwargs["middleware"] is False
await hass.async_block_till_done()
assert mock_setup_entry.await_count == 1
+35 -3
View File
@@ -2,9 +2,11 @@
from unittest.mock import AsyncMock
import pytest
from pytest_homeassistant.common import MockConfigEntry
from volkszaehler.exceptions import VolkszaehlerApiConnectionError
from homeassistant.components.volkszaehler.const import CONF_MIDDLEWARE
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
@@ -15,7 +17,7 @@ async def test_setup_and_unload_entry(
mock_api: AsyncMock,
) -> None:
"""Test successful setup and unload of a config entry."""
mock_api.data = {"rows": []}
mock_api.return_value.data = {"rows": []}
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
@@ -36,7 +38,7 @@ async def test_setup_entry_connection_error(
mock_api: AsyncMock,
) -> None:
"""Test setup retry when the API cannot be reached."""
mock_api.get_data.side_effect = VolkszaehlerApiConnectionError()
mock_api.return_value.get_data.side_effect = VolkszaehlerApiConnectionError()
mock_config_entry.add_to_hass(hass)
assert not await hass.config_entries.async_setup(mock_config_entry.entry_id)
@@ -51,10 +53,40 @@ async def test_setup_entry_no_data(
mock_api: AsyncMock,
) -> None:
"""Test setup retry when the API returns no data."""
mock_api.data = None
mock_api.return_value.data = None
mock_config_entry.add_to_hass(hass)
assert not await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
@pytest.mark.parametrize(
("middleware_data", "expected_middleware"),
[
pytest.param({}, True, id="missing"),
pytest.param({CONF_MIDDLEWARE: True}, True, id="enabled"),
pytest.param({CONF_MIDDLEWARE: False}, False, id="disabled"),
],
)
async def test_setup_middleware(
hass: HomeAssistant,
mock_config_entry_without_middleware: MockConfigEntry,
mock_api: AsyncMock,
middleware_data: dict[str, bool],
expected_middleware: bool,
) -> None:
"""Test setup forwards the configured or default middleware value."""
mock_api.return_value.data = {"rows": []}
mock_config_entry_without_middleware.add_to_hass(hass)
hass.config_entries.async_update_entry(
mock_config_entry_without_middleware,
data={**mock_config_entry_without_middleware.data, **middleware_data},
)
assert await hass.config_entries.async_setup(
mock_config_entry_without_middleware.entry_id
)
assert mock_api.call_args.kwargs["middleware"] is expected_middleware