Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion homeassistant/components/starlink/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,6 @@ def __init__(self, hass: HomeAssistant, config_entry: StarlinkConfigEntry) -> No
def _get_starlink_data(self) -> StarlinkData:
"""Retrieve Starlink data."""
context = self.channel_context
status = status_data(context)
location = location_data(context)
sleep = get_sleep_config(context)
status, obstruction, alert = status_data(context)
Expand Down
9 changes: 6 additions & 3 deletions homeassistant/components/starlink/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import StateType
from homeassistant.util.dt import now
from homeassistant.util.variance import ignore_variance

from .coordinator import StarlinkConfigEntry, StarlinkData
from .entity import StarlinkEntity
Expand Down Expand Up @@ -91,6 +92,10 @@ async def async_added_to_hass(self) -> None:
self._attr_native_value = last_native_value


uptime_to_stable_datetime = ignore_variance(
lambda value: now() - timedelta(seconds=value), timedelta(minutes=1)
)

SENSORS: tuple[StarlinkSensorEntityDescription, ...] = (
StarlinkSensorEntityDescription(
key="ping",
Expand Down Expand Up @@ -150,9 +155,7 @@ async def async_added_to_hass(self) -> None:
translation_key="last_restart",
device_class=SensorDeviceClass.TIMESTAMP,
entity_category=EntityCategory.DIAGNOSTIC,
value_fn=lambda data: (
now() - timedelta(seconds=data.status["uptime"], milliseconds=-500)
).replace(microsecond=0),
value_fn=lambda data: uptime_to_stable_datetime(data.status["uptime"]),
entity_class=StarlinkSensorEntity,
),
StarlinkSensorEntityDescription(
Expand Down
11 changes: 6 additions & 5 deletions tests/components/starlink/patchers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,6 @@
"homeassistant.components.starlink.async_setup_entry", return_value=True
)

STATUS_DATA_SUCCESS_PATCHER = patch(
"homeassistant.components.starlink.coordinator.status_data",
return_value=json.loads(load_fixture("status_data_success.json", "starlink")),
)

LOCATION_DATA_SUCCESS_PATCHER = patch(
"homeassistant.components.starlink.coordinator.location_data",
return_value=json.loads(load_fixture("location_data_success.json", "starlink")),
Expand All @@ -24,6 +19,12 @@
return_value=json.loads(load_fixture("sleep_data_success.json", "starlink")),
)

STATUS_DATA_FIXTURE = json.loads(load_fixture("status_data_success.json", "starlink"))
STATUS_DATA_SUCCESS_PATCHER = patch(
"homeassistant.components.starlink.coordinator.status_data",
return_value=STATUS_DATA_FIXTURE,
)

HISTORY_STATS_SUCCESS_PATCHER = patch(
"homeassistant.components.starlink.coordinator.history_stats",
return_value=json.loads(load_fixture("history_stats_success.json", "starlink")),
Expand Down
112 changes: 107 additions & 5 deletions tests/components/starlink/test_init.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,28 @@
"""Tests Starlink integration init/unload."""

import copy
from datetime import datetime, timedelta
from unittest.mock import patch

from homeassistant.components.starlink.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import CONF_IP_ADDRESS
from homeassistant.core import HomeAssistant, State
from homeassistant.util import dt as dt_util

from .patchers import (
HISTORY_STATS_SUCCESS_PATCHER,
LOCATION_DATA_SUCCESS_PATCHER,
SLEEP_DATA_SUCCESS_PATCHER,
STATUS_DATA_FIXTURE,
STATUS_DATA_SUCCESS_PATCHER,
)

from tests.common import MockConfigEntry, mock_restore_cache_with_extra_data
from tests.common import (
MockConfigEntry,
async_fire_time_changed,
mock_restore_cache_with_extra_data,
)


async def test_successful_entry(hass: HomeAssistant) -> None:
Expand All @@ -25,9 +33,9 @@ async def test_successful_entry(hass: HomeAssistant) -> None:
)

with (
STATUS_DATA_SUCCESS_PATCHER,
LOCATION_DATA_SUCCESS_PATCHER,
SLEEP_DATA_SUCCESS_PATCHER,
STATUS_DATA_SUCCESS_PATCHER,
HISTORY_STATS_SUCCESS_PATCHER,
):
entry.add_to_hass(hass)
Expand All @@ -48,9 +56,9 @@ async def test_unload_entry(hass: HomeAssistant) -> None:
)

with (
STATUS_DATA_SUCCESS_PATCHER,
LOCATION_DATA_SUCCESS_PATCHER,
SLEEP_DATA_SUCCESS_PATCHER,
STATUS_DATA_SUCCESS_PATCHER,
HISTORY_STATS_SUCCESS_PATCHER,
):
entry.add_to_hass(hass)
Expand All @@ -65,7 +73,7 @@ async def test_unload_entry(hass: HomeAssistant) -> None:


async def test_restore_cache_with_accumulation(hass: HomeAssistant) -> None:
"""Test configuring Starlink."""
"""Test Starlink accumulation."""
entry = MockConfigEntry(
domain=DOMAIN,
data={CONF_IP_ADDRESS: "1.2.3.4:0000"},
Expand All @@ -89,9 +97,9 @@ async def test_restore_cache_with_accumulation(hass: HomeAssistant) -> None:
)

with (
STATUS_DATA_SUCCESS_PATCHER,
LOCATION_DATA_SUCCESS_PATCHER,
SLEEP_DATA_SUCCESS_PATCHER,
STATUS_DATA_SUCCESS_PATCHER,
HISTORY_STATS_SUCCESS_PATCHER,
):
entry.add_to_hass(hass)
Expand All @@ -112,3 +120,97 @@ async def test_restore_cache_with_accumulation(hass: HomeAssistant) -> None:
await entry.runtime_data.async_refresh()

assert hass.states.get(entity_id).state == str(1 + 0.01572462736977)


async def test_last_restart_state(hass: HomeAssistant) -> None:
"""Test Starlink last restart state."""
entry = MockConfigEntry(
domain=DOMAIN,
data={CONF_IP_ADDRESS: "1.2.3.4:0000"},
)
entity_id = "sensor.starlink_last_restart"

with (
LOCATION_DATA_SUCCESS_PATCHER,
SLEEP_DATA_SUCCESS_PATCHER,
STATUS_DATA_SUCCESS_PATCHER,
HISTORY_STATS_SUCCESS_PATCHER,
patch(
"homeassistant.components.starlink.sensor.now",
return_value=datetime.fromisoformat("2025-10-22T13:31:29+00:00"),
),
):
entry.add_to_hass(hass)

await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()

assert entry.runtime_data
assert entry.runtime_data.data
assert entry.runtime_data.data.status["uptime"] == 804138

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh right, forgot to tell about the tests.

Ideally we don't touch internals like runtime_data. Also, we shouldn't patch now, and instead use the freezer. I have been playing around this for a little bit to refactor this test to use it, but I didn't have much luck, but that'd be nice if we could have that

Copy link
Contributor Author

@davidrapan davidrapan Nov 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I kinda wasn't able to make the tests work so this was some sort of a last resort. :) But maybe now we don't need to test it as a sensor and simply test the method?

BTW, I wasn't aware of the ignore_variance wrapper, this is certainly better. 👍

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In a way I think having the test test the sensor is best as that's eventually what the user will see, so testing only the method makes it a bit more fragile

Copy link
Contributor Author

@davidrapan davidrapan Nov 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

678c4dd is the only way I managed to get it working.

assert hass.states.get(entity_id).state == "2025-10-13T06:09:11+00:00"

status_data = copy.deepcopy(STATUS_DATA_FIXTURE)
status_data[0]["uptime"] = 804144

with (
patch(
"homeassistant.components.starlink.coordinator.status_data",
return_value=status_data,
),
patch(
"homeassistant.components.starlink.sensor.now",
return_value=datetime.fromisoformat("2025-10-22T13:31:34+00:00"),
),
):
await entry.runtime_data.async_refresh()

assert entry.runtime_data.data.status["uptime"] == 804144

async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=30))
await hass.async_block_till_done(wait_background_tasks=True)

assert hass.states.get(entity_id).state == "2025-10-13T06:09:11+00:00"

status_data[0]["uptime"] = 804134

with (
patch(
"homeassistant.components.starlink.coordinator.status_data",
return_value=status_data,
),
patch(
"homeassistant.components.starlink.sensor.now",
return_value=datetime.fromisoformat("2025-10-22T13:31:39+00:00"),
),
):
await entry.runtime_data.async_refresh()

assert entry.runtime_data.data.status["uptime"] == 804134

async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=30))
await hass.async_block_till_done(wait_background_tasks=True)

assert hass.states.get(entity_id).state == "2025-10-13T06:09:11+00:00"

status_data[0]["uptime"] = 100

with (
patch(
"homeassistant.components.starlink.coordinator.status_data",
return_value=status_data,
),
patch(
"homeassistant.components.starlink.sensor.now",
return_value=datetime.fromisoformat("2025-10-22T13:31:44+00:00"),
),
):
await entry.runtime_data.async_refresh()

assert entry.runtime_data.data.status["uptime"] == 100

async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=30))
await hass.async_block_till_done(wait_background_tasks=True)

assert hass.states.get(entity_id).state == "2025-10-22T13:30:04+00:00"
Loading