From e23d01ad4badcefdaff60b2cc866216d6c93ee98 Mon Sep 17 00:00:00 2001 From: Jens Horn Date: Fri, 4 Sep 2026 11:23:07 +0200 Subject: [PATCH 1/5] Reuse pyCheckwatt client across coordinator updates --- custom_components/checkwatt/__init__.py | 38 +++++++++++++++++----- custom_components/checkwatt/api.py | 36 ++++++++++++++++++++ custom_components/checkwatt/config_flow.py | 15 ++++++--- 3 files changed, 76 insertions(+), 13 deletions(-) create mode 100644 custom_components/checkwatt/api.py diff --git a/custom_components/checkwatt/__init__.py b/custom_components/checkwatt/__init__.py index 3b8d545..eac45d7 100644 --- a/custom_components/checkwatt/__init__.py +++ b/custom_components/checkwatt/__init__.py @@ -7,7 +7,7 @@ import random from typing import TypedDict -from pycheckwatt import CheckwattManager, CheckWattRankManager +from pycheckwatt import CheckWattRankManager import voluptuous as vol from homeassistant.config_entries import ConfigEntry @@ -36,6 +36,10 @@ EVENT_SIGNAL_FCRD, INTEGRATION_NAME, ) +from .api import ( + CheckwattRateLimitError, + create_checkwatt_manager, +) _LOGGER = logging.getLogger(__name__) @@ -138,7 +142,9 @@ async def update_history_items(call: ServiceCall) -> ServiceResponse: status = None stored_items = 0 total_items = 0 - async with CheckwattManager(username, password, INTEGRATION_NAME) as cw: + async with create_checkwatt_manager( + hass, username, password, INTEGRATION_NAME + ) as cw: try: # Login to EnergyInBalance if await cw.login(): @@ -203,6 +209,9 @@ async def update_history_items(call: ServiceCall) -> ServiceResponse: except CheckwattError as err: status = f"Failed to update CheckWattRank: {err}" + except CheckwattRateLimitError as err: + status = f"CheckWatt rate limited requests for {err.retry_after}" + return { "start_date": start_date_str, "end_date": end_date_str, @@ -217,7 +226,9 @@ async def push_cwr(call: ServiceCall) -> ServiceResponse: password = entry.data.get(CONF_PASSWORD) cwr_name = entry.options.get(CONF_CWR_NAME) status = None - async with CheckwattManager(username, password, INTEGRATION_NAME) as cw: + async with create_checkwatt_manager( + hass, username, password, INTEGRATION_NAME + ) as cw: try: # Login to EnergyInBalance if await cw.login(): @@ -254,6 +265,9 @@ async def push_cwr(call: ServiceCall) -> ServiceResponse: except CheckwattError as err: status = f"Failed to update CheckWattRank: {err}" + except CheckwattRateLimitError as err: + status = f"CheckWatt rate limited requests for {err.retry_after}" + return { "result": status, } @@ -320,10 +334,17 @@ def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: super().__init__( hass, _LOGGER, + config_entry=entry, name=DOMAIN, update_interval=timedelta(minutes=CONF_UPDATE_INTERVAL_ALL), ) self._entry = entry + self.client = create_checkwatt_manager( + hass, + entry.data.get(CONF_USERNAME), + entry.data.get(CONF_PASSWORD), + INTEGRATION_NAME, + ) self.last_cw_rank_push = None self.is_boot = True self.energy_provider = None @@ -350,16 +371,12 @@ async def _async_update_data(self) -> CheckwattResp: # noqa: C901 """Fetch the latest data from the source.""" try: - username = self._entry.data.get(CONF_USERNAME) - password = self._entry.data.get(CONF_PASSWORD) use_power_sensors = self._entry.options.get(CONF_POWER_SENSORS) push_to_cw_rank = self._entry.options.get(CONF_PUSH_CW_TO_RANK) use_cm10_sensor = self._entry.options.get(CONF_CM10_SENSOR) cwr_name = self._entry.options.get(CONF_CWR_NAME) - async with CheckwattManager( - username, password, INTEGRATION_NAME - ) as cw_inst: + async with self.client as cw_inst: if not await cw_inst.login(): _LOGGER.error("Failed to login, abort update") raise UpdateFailed("Failed to login") @@ -555,6 +572,11 @@ async def _async_update_data(self) -> CheckwattResp: # noqa: C901 return resp + except CheckwattRateLimitError as err: + raise UpdateFailed( + "CheckWatt rate limited requests", + retry_after=err.retry_after.total_seconds(), + ) from err except InvalidAuth as err: raise ConfigEntryAuthFailed from err except CheckwattError as err: diff --git a/custom_components/checkwatt/api.py b/custom_components/checkwatt/api.py new file mode 100644 index 0000000..8f8c54e --- /dev/null +++ b/custom_components/checkwatt/api.py @@ -0,0 +1,36 @@ +"""Compatibility helpers for the pyCheckwatt API.""" + +from pycheckwatt import CheckwattManager + +from homeassistant.core import HomeAssistant +from homeassistant.helpers.aiohttp_client import async_get_clientsession + +try: + from pycheckwatt import CheckwattRateLimitError +except ImportError: + PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH = False + + class CheckwattRateLimitError(Exception): + """Placeholder that cannot be raised by legacy pyCheckwatt.""" + +else: + PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH = True + + +def create_checkwatt_manager( + hass: HomeAssistant, + username: str, + password: str, + application: str = "pyCheckwatt", +) -> CheckwattManager: + """Create a manager using optional APIs only when they are available.""" + if PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH: + return CheckwattManager( + username, + password, + application, + session=async_get_clientsession(hass), + raise_on_rate_limit=True, + ) + + return CheckwattManager(username, password, application) diff --git a/custom_components/checkwatt/config_flow.py b/custom_components/checkwatt/config_flow.py index 0c2a18a..1e5c631 100644 --- a/custom_components/checkwatt/config_flow.py +++ b/custom_components/checkwatt/config_flow.py @@ -5,7 +5,6 @@ import logging from typing import Any -from pycheckwatt import CheckwattManager import voluptuous as vol from homeassistant import config_entries @@ -14,6 +13,7 @@ from homeassistant.data_entry_flow import FlowResult from homeassistant.exceptions import HomeAssistantError +from .api import CheckwattRateLimitError, create_checkwatt_manager from .const import ( CONF_CM10_SENSOR, CONF_CWR_NAME, @@ -36,11 +36,16 @@ async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]: """Validate that the user input allows us to connect to CheckWatt.""" - async with CheckwattManager( - data[CONF_USERNAME], data[CONF_PASSWORD] + async with create_checkwatt_manager( + hass, + data[CONF_USERNAME], + data[CONF_PASSWORD], ) as check_watt_instance: - if not await check_watt_instance.login(): - raise InvalidAuth + try: + if not await check_watt_instance.login(): + raise InvalidAuth + except CheckwattRateLimitError as err: + raise CannotConnect from err class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): From 4ffa15a0c21995f101924daa9218cf38f08e34a2 Mon Sep 17 00:00:00 2001 From: Jens Horn Date: Fri, 4 Sep 2026 17:01:45 +0200 Subject: [PATCH 2/5] Require Home Assistant 2025.12.0 --- hacs.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hacs.json b/hacs.json index 0de7867..3b650ea 100644 --- a/hacs.json +++ b/hacs.json @@ -1,6 +1,6 @@ { "name": "CheckWatt", - "homeassistant": "2023.12.3", + "homeassistant": "2025.12.0", "render_readme": true, "country": ["ALL"] } From e1c5af97d6d01b88cb075f488831babcd5992add Mon Sep 17 00:00:00 2001 From: Jens Horn Date: Mon, 7 Sep 2026 13:48:53 +0200 Subject: [PATCH 3/5] Prepare staged pyCheckwatt rollout and recover failed updates --- custom_components/checkwatt/__init__.py | 28 +++- custom_components/checkwatt/api.py | 12 +- docs/auth-rollout.md | 65 ++++++++ pytest.ini | 6 + tests/Dockerfile | 12 ++ tests/README.md | 49 ++++++ tests/conftest.py | 176 ++++++++++++++++++++++ tests/test_rollout.py | 188 ++++++++++++++++++++++++ 8 files changed, 527 insertions(+), 9 deletions(-) create mode 100644 docs/auth-rollout.md create mode 100644 pytest.ini create mode 100644 tests/Dockerfile create mode 100644 tests/README.md create mode 100644 tests/conftest.py create mode 100644 tests/test_rollout.py diff --git a/custom_components/checkwatt/__init__.py b/custom_components/checkwatt/__init__.py index eac45d7..00e3716 100644 --- a/custom_components/checkwatt/__init__.py +++ b/custom_components/checkwatt/__init__.py @@ -37,6 +37,7 @@ INTEGRATION_NAME, ) from .api import ( + PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH, CheckwattRateLimitError, create_checkwatt_manager, ) @@ -339,11 +340,15 @@ def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: update_interval=timedelta(minutes=CONF_UPDATE_INTERVAL_ALL), ) self._entry = entry - self.client = create_checkwatt_manager( - hass, - entry.data.get(CONF_USERNAME), - entry.data.get(CONF_PASSWORD), - INTEGRATION_NAME, + self.client = ( + create_checkwatt_manager( + hass, + entry.data.get(CONF_USERNAME), + entry.data.get(CONF_PASSWORD), + INTEGRATION_NAME, + ) + if PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH + else None ) self.last_cw_rank_push = None self.is_boot = True @@ -376,7 +381,14 @@ async def _async_update_data(self) -> CheckwattResp: # noqa: C901 use_cm10_sensor = self._entry.options.get(CONF_CM10_SENSOR) cwr_name = self._entry.options.get(CONF_CWR_NAME) - async with self.client as cw_inst: + # Legacy managers accumulate revenue and must be fresh per poll. + client = self.client or create_checkwatt_manager( + self.hass, + self._entry.data.get(CONF_USERNAME), + self._entry.data.get(CONF_PASSWORD), + INTEGRATION_NAME, + ) + async with client as cw_inst: if not await cw_inst.login(): _LOGGER.error("Failed to login, abort update") raise UpdateFailed("Failed to login") @@ -396,7 +408,6 @@ async def _async_update_data(self) -> CheckwattResp: # noqa: C901 # Only fetch some parameters every 15 min if self.update_all == 0 and not self.is_boot: - self.update_all = CONF_UPDATE_INTERVAL_MONETARY _LOGGER.debug("Fetching daily revenue") if not await cw_inst.get_fcrd_today_net_revenue(): raise UpdateFailed("Unknown error get_fcrd_revenue") @@ -422,12 +433,12 @@ async def _async_update_data(self) -> CheckwattResp: # noqa: C901 self.fcrd_daily_net_average = cw_inst.fcrd_daily_net_average self.fcrd_year_net_revenue = cw_inst.fcrd_year_net_revenue self.monthly_grid_peak_power = cw_inst.month_peak_effect + self.update_all = CONF_UPDATE_INTERVAL_MONETARY if not self.is_boot: self.update_all -= 1 if self.is_boot: - self.is_boot = False self.energy_provider = await cw_inst.get_energy_trading_company( cw_inst.energy_provider_id ) @@ -435,6 +446,7 @@ async def _async_update_data(self) -> CheckwattResp: # noqa: C901 # Store fcrd_state at boot, used to spark event self.fcrd_state = cw_inst.fcrd_state self._id = cw_inst.customer_details["Id"] + self.is_boot = False # Price Zone is used both as Detailed Sensor and by Push to CheckWattRank if push_to_cw_rank or use_power_sensors: diff --git a/custom_components/checkwatt/api.py b/custom_components/checkwatt/api.py index 8f8c54e..36ececb 100644 --- a/custom_components/checkwatt/api.py +++ b/custom_components/checkwatt/api.py @@ -1,5 +1,8 @@ """Compatibility helpers for the pyCheckwatt API.""" +from importlib.metadata import PackageNotFoundError, version + +from packaging.version import Version from pycheckwatt import CheckwattManager from homeassistant.core import HomeAssistant @@ -14,7 +17,14 @@ class CheckwattRateLimitError(Exception): """Placeholder that cannot be raised by legacy pyCheckwatt.""" else: - PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH = True + # Earlier development builds exposed the exception before retained revenue + # was safe. The stabilized release is the persistence boundary. + try: + PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH = Version( + version("pycheckwatt") + ) >= Version("0.2.12") + except PackageNotFoundError: + PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH = False def create_checkwatt_manager( diff --git a/docs/auth-rollout.md b/docs/auth-rollout.md new file mode 100644 index 0000000..352eb4a --- /dev/null +++ b/docs/auth-rollout.md @@ -0,0 +1,65 @@ +# Authentication and HTTP 429 rollout + +The preparation release keeps `pycheckwatt~=0.2.11`. It uses a fresh manager on +every update with older libraries and retains a manager only when both the +rate-limit API and package version `>=0.2.12` are present. Version 0.2.12 is the +planned stabilized release; update this boundary if the upstream release number +changes. An exception import alone is not a persistence guarantee. + +## Proposed release stages + +1. Prepare and test the compatible HA integration. Legacy managers remain fresh + per poll, while newer managers use HA's shared session, persistent tokens and + typed throttling. Do not raise the library requirement in this preparation + change. +2. Publish the stabilized pyCheckwatt release after its PR and release checks + pass. Use this as a canary phase: explicitly install the released wheel in an + isolated HA instance, restart HA, and check repeated polling and recovery. + Merely publishing a newer wheel does not update every existing HA instance. +3. Publish the enforcing HA release with `pycheckwatt~=0.2.12` (or the actual + agreed stabilized version). This is the stage that makes older installations + upgrade. Remove the compatibility helper in that release or a later cleanup. + +### Two release gates + +Home Assistant checks whether installed packages already satisfy the manifest. +An installed 0.2.11 satisfies `~=0.2.11`, so it can remain installed after a +restart. The feature activates when a supported library is actually installed +and the Python process imports it; do not promise automatic upgrades at stage 2. +See HA's `_install_requirements_if_missing` in +[requirements.py](https://github.com/home-assistant/core/blob/2025.12.0/homeassistant/requirements.py). + +The published 0.2.11 wheel declares Python `>=3.10,<3.13`, while this HA branch +requires HA 2025.12, whose runtime is Python 3.13 or newer. Therefore the +preparation release cannot be treated as a supported fresh-install release on +that HA version before the compatible library is available. Keep stage 1 as +development/canary preparation, or publish the compatible library before the +first public HA release. Do not recommend overriding Python requirements in +production. If a public HA-first release is essential, supporting an older HA +runtime needs a separate compatibility change and validation. + +Publishing pyCheckwatt first and then the enforcing HA release is the simplest +public release order. The preparation stage is still useful for testing both +paths before either release. + +## Local validation + +The integration tests use real HA coordinator/config-flow objects and real +aiohttp traffic to a loopback fake CheckWatt server. They cover: + +- Legacy clients recreated per poll and stable repeated revenue values. +- Supported clients retained, JWT reuse, refresh and shared-session ownership. +- HTTP 429 propagation to HA's scheduled retry, and setup retry separately. +- No password fallback after refresh throttling or server errors. +- Immediate retry of failed monetary fetches at the next eligible poll. +- Config validation and integration setup, unload and setup again. + +The lifecycle test stubs HA's platform loaders; it does not claim to validate +entity/platform setup or the HA frontend. There are no live CheckWatt or +CheckWattRank requests. Containers run with external networking disabled and the +source mounted read-only. + +See [the regression test instructions](../tests/README.md). Normal candidate +wheel installation must pass without a Python-requirement override. The legacy +runtime test explicitly bypasses 0.2.11's known metadata restriction to test +its behavior in isolation; passing that test is not an installation gate pass. diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..af8127d --- /dev/null +++ b/pytest.ini @@ -0,0 +1,6 @@ +[pytest] +asyncio_mode = auto +asyncio_default_fixture_loop_scope = function +testpaths = tests +pythonpath = . +addopts = --tb=short diff --git a/tests/Dockerfile b/tests/Dockerfile new file mode 100644 index 0000000..dd8651d --- /dev/null +++ b/tests/Dockerfile @@ -0,0 +1,12 @@ +# Build context is an isolated test directory containing artifacts/*.whl. +ARG HA_VERSION=2025.12.0 +FROM ghcr.io/home-assistant/home-assistant:${HA_VERSION} +RUN uv pip install --system --index https://pypi.org/simple pytest==8.4.2 pytest-asyncio==1.1.1 pip==25.3 +COPY artifacts/*.whl /wheels/ +ARG LIBRARY_WHEEL +# For legacy runtime tests only; candidate installation must use the default. +ARG LEGACY_METADATA_WORKAROUND="" +RUN python -m pip install --no-deps ${LEGACY_METADATA_WORKAROUND} /wheels/${LIBRARY_WHEEL} +WORKDIR /workspace +ENTRYPOINT [] +CMD ["python", "-m", "pytest", "-q", "-p", "no:cacheprovider"] diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 0000000..721523a --- /dev/null +++ b/tests/README.md @@ -0,0 +1,49 @@ +# HA integration regressions + +Run these tests inside the supported HA images, with a pyCheckwatt wheel already +installed. The tests require Python 3.13+, pytest 8.4.2 and pytest-asyncio 1.1.1. +The provided Dockerfile supplies HA and these dependencies. + +Use a separate build directory containing `artifacts/*.whl`; never use a live HA +configuration as the test config. This task uses `C:\Users\jensh\source\ha-test`. +The existing `ha-test` service and its config are not used by these containers. + +Artifacts used during development: + +- The unmodified released `pycheckwatt-0.2.11-py3-none-any.whl` from PyPI. +- A wheel built from library commit `490e481`, with only its version changed in + a separate source copy to `0.2.12+localtest`. This exercises the agreed future + version boundary; it is not a published release. Use the real 0.2.12 wheel for + the eventual release checks. + +Example from the build directory, with the repository next to it under `repos`: + +```powershell +docker build -f ../repos/ha-checkwatt/tests/Dockerfile --build-arg HA_VERSION=2025.12.0 --build-arg LIBRARY_WHEEL=pycheckwatt-0.2.12+localtest-py3-none-any.whl -t ha-checkwatt-regression:candidate . +docker run --rm --network none --env CHECKWATT_EXPECT_PERSISTENT_AUTH=true --mount "type=bind,source=C:/Users/jensh/source/repos/ha-checkwatt,target=/workspace,readonly" ha-checkwatt-regression:candidate +``` + +Repeat with HA 2026.9.0 for the current release. For the legacy runtime test, +select the 0.2.11 wheel, add build argument +`LEGACY_METADATA_WORKAROUND=--ignore-requires-python`, and set +`CHECKWATT_EXPECT_PERSISTENT_AUTH=false` when running the container. This override +is for legacy runtime regression tests only, not production installation. +Tests for functionality absent in the legacy wheel are explicitly skipped. + +The environment variable is required so an unexpected library version cannot +silently exercise the wrong rollout path. The tests never use account secrets; +all HTTP requests must target the local fake server. + +## Recorded local verification (2026-09-07) + +| HA release | Candidate 0.2.12+localtest | Released 0.2.11 runtime | +| --- | --- | --- | +| 2025.12.0 | 15 passed | 8 passed, 7 feature-specific skips | +| 2026.9.0 | 15 passed | 8 passed, 7 feature-specific skips | + +Black, Flake8 and `git diff --check` passed. The legacy runs used the explicit +metadata override described above. Candidate installation used no override. +HA emitted dependency deprecation warnings; the tests reported no failures. +These results cover the fake-server regression suite, not live account or +frontend testing, and must be repeated with the actual published library before +the enforcing release. diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..1598f4e --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,176 @@ +"""Real HA objects and a local HTTP server; no account credentials are used.""" + +import base64 +from collections import Counter +from datetime import datetime, timedelta, timezone +import json +from types import MappingProxyType + +from aiohttp import ClientSession, DefaultResolver, web +import pytest +import pytest_asyncio + +from homeassistant.config_entries import ConfigEntries, ConfigEntry, ConfigEntryState +from homeassistant.core import HomeAssistant +from homeassistant.helpers import frame +from homeassistant.helpers.aiohttp_client import async_get_clientsession + +from custom_components import checkwatt +from custom_components.checkwatt import api +from custom_components.checkwatt.const import ( + CONF_CM10_SENSOR, + CONF_CWR_NAME, + CONF_POWER_SENSORS, + CONF_PUSH_CW_TO_RANK, +) + + +def jwt(expires_in=3600): + payload = { + "exp": (datetime.now(timezone.utc) + timedelta(seconds=expires_in)).timestamp() + } + encoded = ( + base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=") + ) + return f"header.{encoded}.signature" + + +@pytest.fixture +def entry(): + return ConfigEntry( + state=ConfigEntryState.SETUP_IN_PROGRESS, + version=1, + minor_version=1, + domain="checkwatt", + title="Regression account", + source="user", + unique_id="regression", + discovery_keys=MappingProxyType({}), + subentries_data=[], + data={"username": "test@example.invalid", "password": "dummy"}, + options={ + CONF_CM10_SENSOR: False, + CONF_POWER_SENSORS: False, + CONF_PUSH_CW_TO_RANK: False, + CONF_CWR_NAME: "", + }, + ) + + +@pytest_asyncio.fixture +async def hass(tmp_path, monkeypatch): + instance = HomeAssistant(str(tmp_path)) + frame.async_setup(instance) + instance.config_entries = ConfigEntries(instance, {}) + # The tests use loopback HTTP only, so avoid booting zeroconf for DNS. + monkeypatch.setattr( + "homeassistant.helpers.aiohttp_client._async_make_resolver", + lambda hass: DefaultResolver(), + ) + yield instance + session = async_get_clientsession(instance) + await instance.async_stop() + if not session.closed: + await ClientSession.close(session) + + +@pytest_asyncio.fixture +async def backend(monkeypatch): + calls = Counter() + failures = {} + managers = [] + + async def handle(request): + path = request.path + calls[path] += 1 + if path in failures: + return web.Response(status=failures[path], headers={"Retry-After": "600"}) + if path == "/ha-killswitch.txt": + return web.Response(text="0") + if path in ("/user/Login", "/user/RefreshToken"): + return web.json_response( + { + "JwtToken": jwt(), + "RefreshToken": "refresh", + "RefreshTokenExpires": ( + datetime.now(timezone.utc) + timedelta(days=1) + ).isoformat(), + } + ) + if path == "/controlpanel/CustomerDetail": + return web.json_response( + { + "Id": 42, + "FirstName": "Test", + "LastName": "Account", + "StreetAddress": "Test street", + "ZipCode": "12345", + "City": "Test", + "Meter": [ + { + "InstallationType": "SoC", + "DisplayName": "Test battery", + "ResellerId": 1, + "ElhandelsbolagId": 2, + "RpiSerial": "TEST", + } + ], + } + ) + if path == "/ems/energyflow": + return web.json_response( + {"BatteryNow": 1, "GridNow": 2, "SolarNow": 3, "BatterySoC": 50} + ) + if path == "/controlpanel/elhandelsbolag": + return web.json_response([{"Id": 2, "DisplayName": "Test provider"}]) + if path == "/Site/SiteIdBySerial": + return web.json_response({"SiteId": 42}) + if path.startswith("/revenue/"): + return web.json_response( + {"Revenue": [{"NetRevenue": 10}, {"NetRevenue": 20}]} + ) + if path == "/ems/PeakBoughtMonth": + return web.json_response({"HourPeak": 1}) + raise AssertionError(f"Unexpected API request: {request.method} {path}") + + application = web.Application() + application.router.add_route("*", "/{path:.*}", handle) + runner = web.AppRunner(application) + await runner.setup() + site = web.TCPSite(runner, "127.0.0.1", 0) + await site.start() + base_url = f"http://127.0.0.1:{runner.addresses[0][1]}" + + original_request = ClientSession._request + + async def request(session, method, url, **kwargs): + if str(url) == "https://checkwatt.se/ha-killswitch.txt": + url = base_url + "/ha-killswitch.txt" + assert str(url).startswith(base_url), f"External HTTP request blocked: {url}" + return await original_request(session, method, url, **kwargs) + + monkeypatch.setattr(ClientSession, "_request", request) + original_factory = api.create_checkwatt_manager + + def factory(*args, **kwargs): + manager = original_factory(*args, **kwargs) + manager.base_url = base_url + managers.append(manager) + return manager + + monkeypatch.setattr(api, "create_checkwatt_manager", factory) + monkeypatch.setattr(checkwatt, "create_checkwatt_manager", factory) + from custom_components.checkwatt import config_flow + + monkeypatch.setattr(config_flow, "create_checkwatt_manager", factory) + try: + yield calls, failures, managers + finally: + await runner.cleanup() + + +@pytest_asyncio.fixture +async def coordinator(hass, entry, backend): + instance = checkwatt.CheckwattCoordinator(hass, entry) + yield instance + await instance.async_shutdown() diff --git a/tests/test_rollout.py b/tests/test_rollout.py new file mode 100644 index 0000000..bf3a543 --- /dev/null +++ b/tests/test_rollout.py @@ -0,0 +1,188 @@ +"""Run against released legacy and candidate wheels on actual HA releases.""" + +import importlib.util +import os +from unittest.mock import AsyncMock, patch + +import pytest + +from homeassistant.exceptions import ConfigEntryNotReady +from homeassistant.helpers.aiohttp_client import async_get_clientsession +from homeassistant.helpers.update_coordinator import UpdateFailed + +from custom_components import checkwatt +from custom_components.checkwatt import api, config_flow +from custom_components.checkwatt.const import CONF_UPDATE_INTERVAL_MONETARY, DOMAIN + +from conftest import jwt + + +def test_installed_wheel_selects_expected_lifecycle(): + assert api.PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH is ( + os.environ["CHECKWATT_EXPECT_PERSISTENT_AUTH"] == "true" + ) + + +def test_older_development_version_does_not_enable_persistence(): + spec = importlib.util.spec_from_file_location("api_under_test", api.__file__) + module = importlib.util.module_from_spec(spec) + with patch("importlib.metadata.version", return_value="0.2.11"): + spec.loader.exec_module(module) + assert module.PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH is False + + +@pytest.mark.asyncio +async def test_repeated_polls_keep_revenue_stable(coordinator, backend, hass): + calls, _, managers = backend + await coordinator._async_update_data() + # Fetch the monetary group twice, including the real library calculations. + first = await coordinator._async_update_data() + coordinator.update_all = 0 + second = await coordinator._async_update_data() + assert first["monthly_net_revenue"] == second["monthly_net_revenue"] == 30 + assert first["annual_net_revenue"] == second["annual_net_revenue"] + assert first["month_estimate"] == second["month_estimate"] + if api.PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH: + assert len(managers) == 1 + assert calls["/user/Login"] == calls["/ha-killswitch.txt"] == 1 + assert managers[0].session is async_get_clientsession(hass) + assert not managers[0].session.closed + else: + assert len(managers) == calls["/user/Login"] == 3 + assert all(manager.session.closed for manager in managers) + + +@pytest.mark.asyncio +async def test_expired_token_refreshes_without_password(coordinator, backend): + if not api.PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH: + pytest.skip("Legacy wheel has no token-refresh API") + calls, _, _ = backend + await coordinator._async_update_data() + coordinator.client.jwt_token = jwt(-60) + await coordinator._async_update_data() + assert calls["/user/Login"] == calls["/user/RefreshToken"] == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("status", [429, 503]) +async def test_refresh_failure_does_not_send_password(coordinator, backend, status): + if not api.PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH: + pytest.skip("Legacy wheel has no token-refresh API") + calls, failures, _ = backend + await coordinator._async_update_data() + coordinator.client.jwt_token = jwt(-60) + failures["/user/RefreshToken"] = status + with pytest.raises(UpdateFailed) as error: + await coordinator._async_update_data() + if status == 429: + assert error.value.retry_after == 600 + assert calls["/user/Login"] == calls["/user/RefreshToken"] == 1 + + +@pytest.mark.asyncio +async def test_interrupted_initialization_is_retried(coordinator, backend): + if not api.PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH: + pytest.skip("Legacy wheel does not raise typed throttling") + _, failures, _ = backend + failures["/controlpanel/elhandelsbolag"] = 429 + with pytest.raises(UpdateFailed): + await coordinator._async_update_data() + assert coordinator.is_boot is True + failures.clear() + result = await coordinator._async_update_data() + assert result["energy_provider"] == "Test provider" + assert coordinator._id == 42 + assert coordinator.is_boot is False + + +@pytest.mark.asyncio +@pytest.mark.parametrize("status", [429, 503]) +async def test_failed_revenue_is_retried_on_next_poll(coordinator, backend, status): + calls, failures, _ = backend + await coordinator._async_update_data() + failures["/revenue/42"] = status + with pytest.raises(UpdateFailed): + await coordinator._async_update_data() + assert coordinator.update_all == 0 + assert coordinator.fcrd_month_net_revenue is None + failed_calls = calls["/revenue/42"] + failures.clear() + result = await coordinator._async_update_data() + assert calls["/revenue/42"] > failed_calls + assert result["monthly_net_revenue"] == 30 + assert coordinator.update_all == CONF_UPDATE_INTERVAL_MONETARY - 1 + + +@pytest.mark.asyncio +async def test_poll_throttling_reaches_ha_scheduler(coordinator, backend): + if not api.PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH: + pytest.skip("Legacy wheel cannot expose Retry-After") + _, failures, _ = backend + await coordinator.async_config_entry_first_refresh() + unsubscribe = coordinator.async_add_listener(lambda: None) + failures["/controlpanel/CustomerDetail"] = 429 + try: + with patch.object(coordinator, "_schedule_refresh") as schedule: + await coordinator.async_refresh() + assert coordinator.last_update_success is False + assert coordinator._retry_after == 600 + schedule.assert_called_once() + finally: + unsubscribe() + + +@pytest.mark.asyncio +async def test_setup_throttling_uses_config_entry_retry(coordinator, backend): + _, failures, _ = backend + failures["/controlpanel/CustomerDetail"] = 429 + with pytest.raises(ConfigEntryNotReady): + await coordinator.async_config_entry_first_refresh() + + +@pytest.mark.asyncio +async def test_config_flow_success_and_rejected_credentials(hass, entry, backend): + _, failures, _ = backend + await config_flow.validate_input(hass, entry.data) + failures["/user/Login"] = 401 + with pytest.raises(config_flow.InvalidAuth): + await config_flow.validate_input(hass, entry.data) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("endpoint", ["/user/Login", "/ha-killswitch.txt"]) +async def test_config_flow_throttling_is_not_invalid_auth( + hass, entry, backend, endpoint +): + if not api.PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH: + pytest.skip("Legacy wheel cannot distinguish throttling from False") + _, failures, _ = backend + failures[endpoint] = 429 + with pytest.raises(config_flow.CannotConnect): + await config_flow.validate_input(hass, entry.data) + + +@pytest.mark.asyncio +async def test_setup_unload_and_setup_again(hass, entry, backend): + """Exercise integration lifecycle while replacing HA's platform loaders.""" + with ( + patch.object( + hass.config_entries, "async_forward_entry_setups", new=AsyncMock() + ), + patch.object( + hass.config_entries, + "async_unload_platforms", + new=AsyncMock(return_value=True), + ), + ): + assert await checkwatt.async_setup_entry(hass, entry) + first = hass.data[DOMAIN][entry.entry_id] + assert await checkwatt.async_unload_entry(hass, entry) + await first.async_shutdown() + assert entry.entry_id not in hass.data[DOMAIN] + assert not async_get_clientsession(hass).closed + assert await checkwatt.async_setup_entry(hass, entry) + second = hass.data[DOMAIN][entry.entry_id] + assert second is not first + assert await checkwatt.async_unload_entry(hass, entry) + await second.async_shutdown() + assert not async_get_clientsession(hass).closed From 6891208df2dab0af72ce0b870cc97761bf728abf Mon Sep 17 00:00:00 2001 From: Jens Horn Date: Wed, 30 Sep 2026 12:10:40 +0200 Subject: [PATCH 4/5] chore: require pyCheckwatt 0.3.0 and trim rollout docs --- custom_components/checkwatt/api.py | 2 +- custom_components/checkwatt/manifest.json | 2 +- docs/auth-rollout.md | 65 ----------------------- tests/README.md | 54 ++++--------------- 4 files changed, 13 insertions(+), 110 deletions(-) delete mode 100644 docs/auth-rollout.md diff --git a/custom_components/checkwatt/api.py b/custom_components/checkwatt/api.py index 36ececb..93c2ac8 100644 --- a/custom_components/checkwatt/api.py +++ b/custom_components/checkwatt/api.py @@ -22,7 +22,7 @@ class CheckwattRateLimitError(Exception): try: PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH = Version( version("pycheckwatt") - ) >= Version("0.2.12") + ) >= Version("0.3.0") except PackageNotFoundError: PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH = False diff --git a/custom_components/checkwatt/manifest.json b/custom_components/checkwatt/manifest.json index 308392e..751c4aa 100644 --- a/custom_components/checkwatt/manifest.json +++ b/custom_components/checkwatt/manifest.json @@ -12,7 +12,7 @@ "homekit": {}, "iot_class": "cloud_polling", "issue_tracker": "https://github.com/faanskit/ha-checkwatt/issues", - "requirements": ["pycheckwatt~=0.2.11", "aiohttp>=3.9.1"], + "requirements": ["pycheckwatt~=0.3.0", "aiohttp>=3.9.1"], "ssdp": [], "version": "0.2.7", "zeroconf": [] diff --git a/docs/auth-rollout.md b/docs/auth-rollout.md deleted file mode 100644 index 352eb4a..0000000 --- a/docs/auth-rollout.md +++ /dev/null @@ -1,65 +0,0 @@ -# Authentication and HTTP 429 rollout - -The preparation release keeps `pycheckwatt~=0.2.11`. It uses a fresh manager on -every update with older libraries and retains a manager only when both the -rate-limit API and package version `>=0.2.12` are present. Version 0.2.12 is the -planned stabilized release; update this boundary if the upstream release number -changes. An exception import alone is not a persistence guarantee. - -## Proposed release stages - -1. Prepare and test the compatible HA integration. Legacy managers remain fresh - per poll, while newer managers use HA's shared session, persistent tokens and - typed throttling. Do not raise the library requirement in this preparation - change. -2. Publish the stabilized pyCheckwatt release after its PR and release checks - pass. Use this as a canary phase: explicitly install the released wheel in an - isolated HA instance, restart HA, and check repeated polling and recovery. - Merely publishing a newer wheel does not update every existing HA instance. -3. Publish the enforcing HA release with `pycheckwatt~=0.2.12` (or the actual - agreed stabilized version). This is the stage that makes older installations - upgrade. Remove the compatibility helper in that release or a later cleanup. - -### Two release gates - -Home Assistant checks whether installed packages already satisfy the manifest. -An installed 0.2.11 satisfies `~=0.2.11`, so it can remain installed after a -restart. The feature activates when a supported library is actually installed -and the Python process imports it; do not promise automatic upgrades at stage 2. -See HA's `_install_requirements_if_missing` in -[requirements.py](https://github.com/home-assistant/core/blob/2025.12.0/homeassistant/requirements.py). - -The published 0.2.11 wheel declares Python `>=3.10,<3.13`, while this HA branch -requires HA 2025.12, whose runtime is Python 3.13 or newer. Therefore the -preparation release cannot be treated as a supported fresh-install release on -that HA version before the compatible library is available. Keep stage 1 as -development/canary preparation, or publish the compatible library before the -first public HA release. Do not recommend overriding Python requirements in -production. If a public HA-first release is essential, supporting an older HA -runtime needs a separate compatibility change and validation. - -Publishing pyCheckwatt first and then the enforcing HA release is the simplest -public release order. The preparation stage is still useful for testing both -paths before either release. - -## Local validation - -The integration tests use real HA coordinator/config-flow objects and real -aiohttp traffic to a loopback fake CheckWatt server. They cover: - -- Legacy clients recreated per poll and stable repeated revenue values. -- Supported clients retained, JWT reuse, refresh and shared-session ownership. -- HTTP 429 propagation to HA's scheduled retry, and setup retry separately. -- No password fallback after refresh throttling or server errors. -- Immediate retry of failed monetary fetches at the next eligible poll. -- Config validation and integration setup, unload and setup again. - -The lifecycle test stubs HA's platform loaders; it does not claim to validate -entity/platform setup or the HA frontend. There are no live CheckWatt or -CheckWattRank requests. Containers run with external networking disabled and the -source mounted read-only. - -See [the regression test instructions](../tests/README.md). Normal candidate -wheel installation must pass without a Python-requirement override. The legacy -runtime test explicitly bypasses 0.2.11's known metadata restriction to test -its behavior in isolation; passing that test is not an installation gate pass. diff --git a/tests/README.md b/tests/README.md index 721523a..8c621b7 100644 --- a/tests/README.md +++ b/tests/README.md @@ -1,49 +1,17 @@ -# HA integration regressions +# Integration tests -Run these tests inside the supported HA images, with a pyCheckwatt wheel already -installed. The tests require Python 3.13+, pytest 8.4.2 and pytest-asyncio 1.1.1. -The provided Dockerfile supplies HA and these dependencies. - -Use a separate build directory containing `artifacts/*.whl`; never use a live HA -configuration as the test config. This task uses `C:\Users\jensh\source\ha-test`. -The existing `ha-test` service and its config are not used by these containers. - -Artifacts used during development: - -- The unmodified released `pycheckwatt-0.2.11-py3-none-any.whl` from PyPI. -- A wheel built from library commit `490e481`, with only its version changed in - a separate source copy to `0.2.12+localtest`. This exercises the agreed future - version boundary; it is not a published release. Use the real 0.2.12 wheel for - the eventual release checks. - -Example from the build directory, with the repository next to it under `repos`: +Place `pycheckwatt-0.3.0-py3-none-any.whl` in `artifacts/` under a separate +build directory. From that directory, set `$repo` to your ha-checkwatt checkout: ```powershell -docker build -f ../repos/ha-checkwatt/tests/Dockerfile --build-arg HA_VERSION=2025.12.0 --build-arg LIBRARY_WHEEL=pycheckwatt-0.2.12+localtest-py3-none-any.whl -t ha-checkwatt-regression:candidate . -docker run --rm --network none --env CHECKWATT_EXPECT_PERSISTENT_AUTH=true --mount "type=bind,source=C:/Users/jensh/source/repos/ha-checkwatt,target=/workspace,readonly" ha-checkwatt-regression:candidate +$repo = "C:/path/to/ha-checkwatt" +docker build -f "$repo/tests/Dockerfile" --build-arg HA_VERSION=2025.12.0 --build-arg LIBRARY_WHEEL=pycheckwatt-0.3.0-py3-none-any.whl -t ha-checkwatt-tests . +docker run --rm --network none --env CHECKWATT_EXPECT_PERSISTENT_AUTH=true --mount "type=bind,source=$repo,target=/workspace,readonly" ha-checkwatt-tests ``` -Repeat with HA 2026.9.0 for the current release. For the legacy runtime test, -select the 0.2.11 wheel, add build argument -`LEGACY_METADATA_WORKAROUND=--ignore-requires-python`, and set -`CHECKWATT_EXPECT_PERSISTENT_AUTH=false` when running the container. This override -is for legacy runtime regression tests only, not production installation. -Tests for functionality absent in the legacy wheel are explicitly skipped. - -The environment variable is required so an unexpected library version cannot -silently exercise the wrong rollout path. The tests never use account secrets; -all HTTP requests must target the local fake server. - -## Recorded local verification (2026-09-07) - -| HA release | Candidate 0.2.12+localtest | Released 0.2.11 runtime | -| --- | --- | --- | -| 2025.12.0 | 15 passed | 8 passed, 7 feature-specific skips | -| 2026.9.0 | 15 passed | 8 passed, 7 feature-specific skips | +Repeat with `HA_VERSION=2026.9.0`. Tests use local fake HTTP; platform loading +is stubbed. No live account or HA configuration is needed. -Black, Flake8 and `git diff --check` passed. The legacy runs used the explicit -metadata override described above. Candidate installation used no override. -HA emitted dependency deprecation warnings; the tests reported no failures. -These results cover the fake-server regression suite, not live account or -frontend testing, and must be repeated with the actual published library before -the enforcing release. +For legacy regression coverage, build with the 0.2.11 wheel and +`--build-arg LEGACY_METADATA_WORKAROUND=--ignore-requires-python`, then run with +`CHECKWATT_EXPECT_PERSISTENT_AUTH=false`. This override is for tests only. From caf62eaefa9cb2c110b59e955a8d3f7eb082967d Mon Sep 17 00:00:00 2001 From: Jens Horn Date: Wed, 30 Sep 2026 12:23:27 +0200 Subject: [PATCH 5/5] chore: bump integration version to 0.3.0 --- custom_components/checkwatt/manifest.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/custom_components/checkwatt/manifest.json b/custom_components/checkwatt/manifest.json index 751c4aa..cf327f0 100644 --- a/custom_components/checkwatt/manifest.json +++ b/custom_components/checkwatt/manifest.json @@ -14,7 +14,7 @@ "issue_tracker": "https://github.com/faanskit/ha-checkwatt/issues", "requirements": ["pycheckwatt~=0.3.0", "aiohttp>=3.9.1"], "ssdp": [], - "version": "0.2.7", + "version": "0.3.0", "zeroconf": [] }