Avoid naive datetime in Wallbox token validity check (#178492)

This commit is contained in:
jslponcev-ui
2026-10-11 22:13:29 -04:00
committed by GitHub
parent 6b5d484847
commit 489eeff371
3 changed files with 32 additions and 23 deletions
@@ -1,9 +1,10 @@
"""DataUpdateCoordinator for the wallbox integration."""
from collections.abc import Callable
from datetime import datetime, timedelta
from datetime import timedelta
from http import HTTPStatus
import logging
import time
from typing import Any, Concatenate, override
import requests
@@ -100,9 +101,7 @@ def _require_authentication[_WallboxCoordinatorT: WallboxCoordinator, **_P](
def check_token_validity(jwt_token_ttl: int, jwt_token_drift: int) -> bool:
"""Check if the jwtToken is still valid in order to reuse if possible."""
return round((jwt_token_ttl / 1000) - jwt_token_drift, 0) > datetime.timestamp(
datetime.now() # pylint: disable=home-assistant-enforce-naive-now
)
return round((jwt_token_ttl / 1000) - jwt_token_drift, 0) > time.time()
def _validate(wallbox: Wallbox) -> None:
+5 -13
View File
@@ -1,7 +1,7 @@
"""Test fixtures for the Wallbox integration."""
from datetime import datetime, timedelta
from http import HTTPStatus
import time
from unittest.mock import MagicMock, Mock, patch
import pytest
@@ -50,12 +50,8 @@ def entry(hass: HomeAssistant) -> MockConfigEntry:
CONF_STATION: "12345",
CHARGER_JWT_TOKEN: "test_token",
CHARGER_JWT_REFRESH_TOKEN: "test_refresh_token",
CHARGER_JWT_TTL: (
datetime.timestamp(datetime.now() + timedelta(hours=1)) * 1000 # pylint: disable=home-assistant-enforce-naive-now
),
CHARGER_JWT_REFRESH_TTL: (
datetime.timestamp(datetime.now() + timedelta(hours=1)) * 1000 # pylint: disable=home-assistant-enforce-naive-now
),
CHARGER_JWT_TTL: (time.time() + 3600) * 1000,
CHARGER_JWT_REFRESH_TTL: (time.time() + 3600) * 1000,
},
entry_id="testEntry",
)
@@ -98,12 +94,8 @@ def mock_wallbox():
wallbox.getChargerStatus = Mock(return_value=WALLBOX_STATUS_RESPONSE)
wallbox.jwtToken = "test_token"
wallbox.jwtRefreshToken = "test_refresh_token"
wallbox.jwtTokenTtl = (
datetime.timestamp(datetime.now() + timedelta(hours=1)) * 1000 # pylint: disable=home-assistant-enforce-naive-now
)
wallbox.jwtRefreshTokenTtl = (
datetime.timestamp(datetime.now() + timedelta(hours=1)) * 1000 # pylint: disable=home-assistant-enforce-naive-now
)
wallbox.jwtTokenTtl = (time.time() + 3600) * 1000
wallbox.jwtRefreshTokenTtl = (time.time() + 3600) * 1000
mock.return_value = wallbox
yield wallbox
+24 -6
View File
@@ -1,16 +1,19 @@
"""Test Wallbox Init Component."""
from datetime import datetime, timedelta
from datetime import timedelta
import time
from unittest.mock import patch
import pytest
from homeassistant.components.input_number import ATTR_VALUE, SERVICE_SET_VALUE
from homeassistant.components.wallbox.const import CHARGER_JWT_TTL
from homeassistant.components.wallbox.coordinator import check_token_validity
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed, HomeAssistantError
from homeassistant.util import dt as dt_util
from .conftest import http_403_error, http_429_error, setup_integration
from .const import (
@@ -21,6 +24,23 @@ from .const import (
from tests.common import MockConfigEntry, async_fire_time_changed
@pytest.mark.parametrize(
("remaining_seconds", "valid"),
[(-1, False), (0, False), (1, True)],
)
def test_token_validity(remaining_seconds: int, valid: bool) -> None:
"""Check the token validity boundary after accounting for clock drift."""
now = 1_700_000_000
drift = 30
with patch(
"homeassistant.components.wallbox.coordinator.time.time", return_value=now
):
assert (
check_token_validity((now + drift + remaining_seconds) * 1000, drift)
is valid
)
async def test_wallbox_setup_unload_entry(
hass: HomeAssistant, entry: MockConfigEntry, mock_wallbox
) -> None:
@@ -59,9 +79,7 @@ async def test_wallbox_refresh_failed_error_auth(
assert entry.state is ConfigEntryState.LOADED
data = dict(entry.data)
data[CHARGER_JWT_TTL] = (
datetime.timestamp(datetime.now() - timedelta(hours=1)) * 1000 # pylint: disable=home-assistant-enforce-naive-now
)
data[CHARGER_JWT_TTL] = (time.time() - 3600) * 1000
hass.config_entries.async_update_entry(entry, data=data)
with (
@@ -119,7 +137,7 @@ async def test_wallbox_refresh_failed_too_many_requests(
assert entry.state is ConfigEntryState.LOADED
with patch.object(mock_wallbox, "getChargerStatus", side_effect=http_429_error):
async_fire_time_changed(hass, datetime.now() + timedelta(seconds=120), True) # pylint: disable=home-assistant-enforce-naive-now
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=120), True)
await hass.async_block_till_done()
assert await hass.config_entries.async_unload(entry.entry_id)
@@ -135,7 +153,7 @@ async def test_wallbox_refresh_failed_connection_error(
assert entry.state is ConfigEntryState.LOADED
with patch.object(mock_wallbox, "pauseChargingSession", side_effect=http_403_error):
async_fire_time_changed(hass, datetime.now() + timedelta(seconds=120), True) # pylint: disable=home-assistant-enforce-naive-now
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=120), True)
await hass.async_block_till_done()
assert await hass.config_entries.async_unload(entry.entry_id)