diff --git a/custom_components/checkwatt/__init__.py b/custom_components/checkwatt/__init__.py index 3b8d545..00e3716 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,11 @@ EVENT_SIGNAL_FCRD, INTEGRATION_NAME, ) +from .api import ( + PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH, + CheckwattRateLimitError, + create_checkwatt_manager, +) _LOGGER = logging.getLogger(__name__) @@ -138,7 +143,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 +210,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 +227,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 +266,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 +335,21 @@ 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, + ) + if PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH + else None + ) self.last_cw_rank_push = None self.is_boot = True self.energy_provider = None @@ -350,16 +376,19 @@ 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: + # 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") @@ -379,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") @@ -405,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 ) @@ -418,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: @@ -555,6 +584,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..93c2ac8 --- /dev/null +++ b/custom_components/checkwatt/api.py @@ -0,0 +1,46 @@ +"""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 +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: + # 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.3.0") + except PackageNotFoundError: + PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH = False + + +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): diff --git a/custom_components/checkwatt/manifest.json b/custom_components/checkwatt/manifest.json index 308392e..cf327f0 100644 --- a/custom_components/checkwatt/manifest.json +++ b/custom_components/checkwatt/manifest.json @@ -12,9 +12,9 @@ "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", + "version": "0.3.0", "zeroconf": [] } 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"] } 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..8c621b7 --- /dev/null +++ b/tests/README.md @@ -0,0 +1,17 @@ +# Integration tests + +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 +$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_VERSION=2026.9.0`. Tests use local fake HTTP; platform loading +is stubbed. No live account or HA configuration is needed. + +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. 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