mirror of
https://github.com/home-assistant/core.git
synced 2026-12-03 04:08:19 -04:00
Add budget sensors to Monarch Money (#182774)
Co-authored-by: bradleyseanf <bradleyseanf@users.noreply.github.com> Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
co-authored by
bradleyseanf
Copilot Autofix powered by AI
parent
3d5b89916b
commit
7bfbf0d6be
@@ -2,7 +2,7 @@
|
||||
|
||||
import asyncio
|
||||
from dataclasses import dataclass
|
||||
from datetime import timedelta
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Never, override
|
||||
|
||||
from aiohttp import ClientError, ClientResponseError
|
||||
@@ -11,6 +11,7 @@ from monarchmoney import LoginFailedException
|
||||
from typedmonarchmoney import TypedMonarchMoney
|
||||
from typedmonarchmoney.models import (
|
||||
MonarchAccount,
|
||||
MonarchBudget,
|
||||
MonarchCashflowSummary,
|
||||
MonarchSubscription,
|
||||
)
|
||||
@@ -30,6 +31,9 @@ class MonarchData:
|
||||
|
||||
account_data: dict[str, MonarchAccount]
|
||||
cashflow_summary: MonarchCashflowSummary
|
||||
budgets: dict[str, MonarchBudget]
|
||||
budget_month: str
|
||||
budget_month_start: datetime
|
||||
|
||||
|
||||
type MonarchMoneyConfigEntry = ConfigEntry[MonarchMoneyDataUpdateCoordinator]
|
||||
@@ -81,21 +85,36 @@ class MonarchMoneyDataUpdateCoordinator(DataUpdateCoordinator[MonarchData]):
|
||||
|
||||
@override
|
||||
async def _async_update_data(self) -> MonarchData:
|
||||
"""Fetch data for all accounts."""
|
||||
"""Fetch account, cashflow, and current budget data."""
|
||||
|
||||
now = dt_util.now()
|
||||
budget_month = f"{now.year:04d}-{now.month:02d}"
|
||||
budget_start_date = f"{budget_month}-01"
|
||||
next_month = now.replace(day=28) + timedelta(days=4)
|
||||
budget_end_date = (next_month - timedelta(days=next_month.day)).strftime(
|
||||
"%Y-%m-%d"
|
||||
)
|
||||
|
||||
try:
|
||||
account_data, cashflow_summary = await asyncio.gather(
|
||||
account_data, cashflow_summary, budgets = await asyncio.gather(
|
||||
self.client.get_accounts_as_dict_with_id_key(),
|
||||
self.client.get_cashflow_summary(
|
||||
start_date=f"{now.year}-01-01", end_date=f"{now.year}-12-31"
|
||||
),
|
||||
self.client.get_budgets_as_dict_with_id_key(
|
||||
start_date=budget_start_date, end_date=budget_end_date
|
||||
),
|
||||
)
|
||||
except (LoginFailedException, TransportError, ClientError, TimeoutError) as err:
|
||||
_raise_update_error(err)
|
||||
|
||||
return MonarchData(account_data=account_data, cashflow_summary=cashflow_summary)
|
||||
return MonarchData(
|
||||
account_data=account_data,
|
||||
cashflow_summary=cashflow_summary,
|
||||
budgets=budgets,
|
||||
budget_month=budget_start_date,
|
||||
budget_month_start=dt_util.start_of_local_day(now.replace(day=1)),
|
||||
)
|
||||
|
||||
@property
|
||||
def cashflow_summary(self) -> MonarchCashflowSummary:
|
||||
|
||||
@@ -2,7 +2,11 @@
|
||||
|
||||
from typing import override
|
||||
|
||||
from typedmonarchmoney.models import MonarchAccount, MonarchCashflowSummary
|
||||
from typedmonarchmoney.models import (
|
||||
MonarchAccount,
|
||||
MonarchBudget,
|
||||
MonarchCashflowSummary,
|
||||
)
|
||||
|
||||
from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
|
||||
from homeassistant.helpers.entity import EntityDescription
|
||||
@@ -88,3 +92,38 @@ class MonarchMoneyAccountEntity(MonarchMoneyEntityBase):
|
||||
def account_data(self) -> MonarchAccount:
|
||||
"""Return the account data."""
|
||||
return self.coordinator.data.account_data[self._account_id]
|
||||
|
||||
|
||||
class MonarchMoneyBudgetEntity(MonarchMoneyEntityBase):
|
||||
"""Entity for budget sensors."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
coordinator: MonarchMoneyDataUpdateCoordinator,
|
||||
description: EntityDescription,
|
||||
budget: MonarchBudget,
|
||||
) -> None:
|
||||
"""Initialize the budget entity."""
|
||||
super().__init__(coordinator)
|
||||
self.entity_description = description
|
||||
self._budget_id = budget.id
|
||||
self._attr_unique_id = (
|
||||
f"{coordinator.subscription_id}_budget_{budget.id}_{description.key}"
|
||||
)
|
||||
self._attr_device_info = DeviceInfo(
|
||||
identifiers={(DOMAIN, f"{coordinator.subscription_id}_budget_{budget.id}")},
|
||||
name=f"{budget.group_name} - {budget.name}",
|
||||
entry_type=DeviceEntryType.SERVICE,
|
||||
manufacturer="Monarch Money",
|
||||
)
|
||||
|
||||
@property
|
||||
@override
|
||||
def available(self) -> bool:
|
||||
"""Return if the budget has data for the current month."""
|
||||
return (
|
||||
super().available
|
||||
and (budget := self.coordinator.data.budgets.get(self._budget_id))
|
||||
is not None
|
||||
and self.coordinator.data.budget_month in budget.monthly_amounts
|
||||
)
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
{
|
||||
"entity": {
|
||||
"sensor": {
|
||||
"budget_actual": { "default": "mdi:cash" },
|
||||
"budget_planned": { "default": "mdi:cash-multiple" },
|
||||
"budget_remaining": { "default": "mdi:cash-clock" },
|
||||
"savings": { "default": "mdi:piggy-bank-outline" },
|
||||
"savings_rate": { "default": "mdi:cash-sync" },
|
||||
"sum_expense": { "default": "mdi:cash-minus" },
|
||||
|
||||
@@ -5,7 +5,11 @@ from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import override
|
||||
|
||||
from typedmonarchmoney.models import MonarchAccount, MonarchCashflowSummary
|
||||
from typedmonarchmoney.models import (
|
||||
MonarchAccount,
|
||||
MonarchBudgetMonth,
|
||||
MonarchCashflowSummary,
|
||||
)
|
||||
|
||||
from homeassistant.components.sensor import (
|
||||
SensorDeviceClass,
|
||||
@@ -14,12 +18,16 @@ from homeassistant.components.sensor import (
|
||||
SensorStateClass,
|
||||
)
|
||||
from homeassistant.const import CURRENCY_DOLLAR, PERCENTAGE, EntityCategory
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
|
||||
from homeassistant.helpers.typing import StateType
|
||||
|
||||
from .coordinator import MonarchMoneyConfigEntry
|
||||
from .entity import MonarchMoneyAccountEntity, MonarchMoneyCashFlowEntity
|
||||
from .entity import (
|
||||
MonarchMoneyAccountEntity,
|
||||
MonarchMoneyBudgetEntity,
|
||||
MonarchMoneyCashFlowEntity,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
@@ -37,6 +45,13 @@ class MonarchMoneyCashflowSensorEntityDescription(SensorEntityDescription):
|
||||
summary_fn: Callable[[MonarchCashflowSummary], StateType]
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class MonarchMoneyBudgetSensorEntityDescription(SensorEntityDescription):
|
||||
"""Describe a budget sensor entity."""
|
||||
|
||||
value_fn: Callable[[MonarchBudgetMonth], StateType]
|
||||
|
||||
|
||||
def _account_owner_name(account: MonarchAccount) -> str | None:
|
||||
"""Return the account owner's display name."""
|
||||
if not account.account_owner:
|
||||
@@ -128,6 +143,34 @@ MONARCH_CASHFLOW_SENSORS: tuple[MonarchMoneyCashflowSensorEntityDescription, ...
|
||||
)
|
||||
|
||||
|
||||
MONARCH_BUDGET_SENSORS: tuple[MonarchMoneyBudgetSensorEntityDescription, ...] = (
|
||||
MonarchMoneyBudgetSensorEntityDescription(
|
||||
key="actual",
|
||||
translation_key="budget_actual",
|
||||
state_class=SensorStateClass.TOTAL,
|
||||
device_class=SensorDeviceClass.MONETARY,
|
||||
native_unit_of_measurement=CURRENCY_DOLLAR,
|
||||
value_fn=lambda month: month.actual_amount,
|
||||
),
|
||||
MonarchMoneyBudgetSensorEntityDescription(
|
||||
key="planned",
|
||||
translation_key="budget_planned",
|
||||
state_class=SensorStateClass.TOTAL,
|
||||
device_class=SensorDeviceClass.MONETARY,
|
||||
native_unit_of_measurement=CURRENCY_DOLLAR,
|
||||
value_fn=lambda month: month.planned_amount,
|
||||
),
|
||||
MonarchMoneyBudgetSensorEntityDescription(
|
||||
key="remaining",
|
||||
translation_key="budget_remaining",
|
||||
state_class=SensorStateClass.TOTAL,
|
||||
device_class=SensorDeviceClass.MONETARY,
|
||||
native_unit_of_measurement=CURRENCY_DOLLAR,
|
||||
value_fn=lambda month: month.remaining_amount,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
config_entry: MonarchMoneyConfigEntry,
|
||||
@@ -182,6 +225,31 @@ async def async_setup_entry(
|
||||
|
||||
async_add_entities(entity_list)
|
||||
|
||||
added_budget_ids: set[str] = set()
|
||||
|
||||
@callback
|
||||
def _async_add_new_budget_entities() -> None:
|
||||
"""Add sensors for budget categories discovered during an update."""
|
||||
new_budget_ids = set(mm_coordinator.data.budgets) - added_budget_ids
|
||||
if not new_budget_ids:
|
||||
return
|
||||
|
||||
async_add_entities(
|
||||
MonarchMoneyBudgetSensor(
|
||||
mm_coordinator,
|
||||
sensor_description,
|
||||
mm_coordinator.data.budgets[budget_id],
|
||||
)
|
||||
for budget_id in new_budget_ids
|
||||
for sensor_description in MONARCH_BUDGET_SENSORS
|
||||
)
|
||||
added_budget_ids.update(new_budget_ids)
|
||||
|
||||
_async_add_new_budget_entities()
|
||||
config_entry.async_on_unload(
|
||||
mm_coordinator.async_add_listener(_async_add_new_budget_entities)
|
||||
)
|
||||
|
||||
|
||||
class MonarchMoneyCashFlowSensor(MonarchMoneyCashFlowEntity, SensorEntity):
|
||||
"""Cashflow summary sensor."""
|
||||
@@ -213,3 +281,40 @@ class MonarchMoneySensor(MonarchMoneyAccountEntity, SensorEntity):
|
||||
if self.entity_description.picture_fn is not None:
|
||||
return self.entity_description.picture_fn(self.account_data)
|
||||
return None
|
||||
|
||||
|
||||
class MonarchMoneyBudgetSensor(MonarchMoneyBudgetEntity, SensorEntity):
|
||||
"""Budget category sensor."""
|
||||
|
||||
entity_description: MonarchMoneyBudgetSensorEntityDescription
|
||||
|
||||
@property
|
||||
@override
|
||||
def native_value(self) -> StateType:
|
||||
"""Return the budget value."""
|
||||
if (budget := self.coordinator.data.budgets.get(self._budget_id)) is None:
|
||||
return None
|
||||
if (
|
||||
month := budget.monthly_amounts.get(self.coordinator.data.budget_month)
|
||||
) is None:
|
||||
return None
|
||||
return self.entity_description.value_fn(month)
|
||||
|
||||
@property
|
||||
@override
|
||||
def extra_state_attributes(self) -> dict[str, str] | None:
|
||||
"""Return budget metadata."""
|
||||
budget = self.coordinator.data.budgets.get(self._budget_id)
|
||||
if (
|
||||
budget is None
|
||||
or (month := budget.monthly_amounts.get(self.coordinator.data.budget_month))
|
||||
is None
|
||||
):
|
||||
return None
|
||||
return {"category_group": budget.group_name, "month": month.month}
|
||||
|
||||
@property
|
||||
@override
|
||||
def last_reset(self) -> datetime:
|
||||
"""Return the start of the budget month."""
|
||||
return self.coordinator.data.budget_month_start
|
||||
|
||||
@@ -37,6 +37,9 @@
|
||||
},
|
||||
|
||||
"balance": { "name": "Balance" },
|
||||
"budget_actual": { "name": "Budget actual" },
|
||||
"budget_planned": { "name": "Budget planned" },
|
||||
"budget_remaining": { "name": "Budget remaining" },
|
||||
"owner": {
|
||||
"name": "Owner"
|
||||
},
|
||||
|
||||
@@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, PropertyMock, patch
|
||||
import pytest
|
||||
from typedmonarchmoney.models import (
|
||||
MonarchAccount,
|
||||
MonarchBudget,
|
||||
MonarchCashflowSummary,
|
||||
MonarchSubscription,
|
||||
)
|
||||
@@ -17,6 +18,23 @@ from homeassistant.const import CONF_TOKEN
|
||||
from tests.common import MockConfigEntry, load_json_object_fixture
|
||||
|
||||
|
||||
def _typed_budgets(data: dict[str, Any]) -> dict[str, MonarchBudget]:
|
||||
"""Build the typed response returned by the Monarch client."""
|
||||
monthly_amounts = {
|
||||
category["category"]["id"]: category["monthlyAmounts"]
|
||||
for category in data["budgetData"]["monthlyAmountsByCategory"]
|
||||
}
|
||||
return {
|
||||
category["id"]: MonarchBudget(
|
||||
category,
|
||||
group_name=group["name"],
|
||||
monthly_amounts=monthly_amounts.get(category["id"]),
|
||||
)
|
||||
for group in data["categoryGroups"]
|
||||
for category in group["categories"]
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_setup_entry() -> Generator[AsyncMock]:
|
||||
"""Override async_setup_entry."""
|
||||
@@ -51,6 +69,7 @@ def mock_config_api() -> Generator[AsyncMock]:
|
||||
"get_cashflow_summary.json", DOMAIN
|
||||
)
|
||||
cashflow_summary = MonarchCashflowSummary(cashflow_json)
|
||||
budget_data = _typed_budgets(load_json_object_fixture("get_budgets.json", DOMAIN))
|
||||
subscription_details = MonarchSubscription(
|
||||
load_json_object_fixture("get_subscription_details.json", DOMAIN)
|
||||
)
|
||||
@@ -74,5 +93,5 @@ def mock_config_api() -> Generator[AsyncMock]:
|
||||
return_value=account_data_dict
|
||||
)
|
||||
instance.get_cashflow_summary = AsyncMock(return_value=cashflow_summary)
|
||||
instance.get_subscription_details = AsyncMock(return_value=subscription_details)
|
||||
instance.get_budgets_as_dict_with_id_key = AsyncMock(return_value=budget_data)
|
||||
yield mock_class
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
{
|
||||
"budgetData": {
|
||||
"monthlyAmountsByCategory": [
|
||||
{
|
||||
"category": { "id": "category-food" },
|
||||
"monthlyAmounts": [
|
||||
{
|
||||
"month": "2026-08-01",
|
||||
"plannedCashFlowAmount": -500.0,
|
||||
"actualAmount": -550.0,
|
||||
"remainingAmount": -50.0
|
||||
},
|
||||
{
|
||||
"month": "2026-09-01",
|
||||
"plannedCashFlowAmount": -500.0,
|
||||
"actualAmount": -150.0,
|
||||
"remainingAmount": 625.0
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"category": { "id": "category-vacation" },
|
||||
"monthlyAmounts": [
|
||||
{
|
||||
"month": "2026-09-01",
|
||||
"plannedCashFlowAmount": null,
|
||||
"actualAmount": null,
|
||||
"remainingAmount": null
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"category": { "id": "category-housing" },
|
||||
"monthlyAmounts": [
|
||||
{
|
||||
"month": "2026-08-01",
|
||||
"plannedCashFlowAmount": -1200.0,
|
||||
"actualAmount": -1200.0,
|
||||
"remainingAmount": 0.0
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"category": { "id": "category-archived" },
|
||||
"monthlyAmounts": [
|
||||
{
|
||||
"month": "2026-09-01",
|
||||
"plannedCashFlowAmount": -100.0,
|
||||
"actualAmount": -50.0,
|
||||
"remainingAmount": -50.0
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"categoryGroups": [
|
||||
{
|
||||
"name": "Food & Dining",
|
||||
"categories": [{ "id": "category-food", "name": "Groceries" }]
|
||||
},
|
||||
{
|
||||
"name": "Travel",
|
||||
"categories": [{ "id": "category-vacation", "name": "Vacation" }]
|
||||
},
|
||||
{
|
||||
"name": "Housing",
|
||||
"categories": [{ "id": "category-housing", "name": "Rent" }]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -218,6 +218,345 @@
|
||||
'state': '6000.0',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[sensor.food_dining_groceries_budget_actual-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
<SensorEntityCapabilityAttribute.STATE_CLASS: 'state_class'>: <SensorStateClass.TOTAL: 'total'>,
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': <ANY>,
|
||||
'device_class': None,
|
||||
'device_id': <ANY>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.food_dining_groceries_budget_actual',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Budget actual',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <SensorDeviceClass.MONETARY: 'monetary'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'Budget actual',
|
||||
'platform': 'monarch_money',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'budget_actual',
|
||||
'unique_id': '222260252323873333_budget_category-food_actual',
|
||||
'unit_of_measurement': '$',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[sensor.food_dining_groceries_budget_actual-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
'category_group': 'Food & Dining',
|
||||
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'monetary',
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Food & Dining - Groceries Budget actual',
|
||||
<SensorEntityStateAttribute.LAST_RESET: 'last_reset'>: '2026-09-01T00:00:00+00:00',
|
||||
'month': '2026-09-01',
|
||||
<SensorEntityCapabilityAttribute.STATE_CLASS: 'state_class'>: <SensorStateClass.TOTAL: 'total'>,
|
||||
<EntityStateAttribute.UNIT_OF_MEASUREMENT: 'unit_of_measurement'>: '$',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.food_dining_groceries_budget_actual',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': '-150.0',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[sensor.food_dining_groceries_budget_planned-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
<SensorEntityCapabilityAttribute.STATE_CLASS: 'state_class'>: <SensorStateClass.TOTAL: 'total'>,
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': <ANY>,
|
||||
'device_class': None,
|
||||
'device_id': <ANY>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.food_dining_groceries_budget_planned',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Budget planned',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <SensorDeviceClass.MONETARY: 'monetary'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'Budget planned',
|
||||
'platform': 'monarch_money',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'budget_planned',
|
||||
'unique_id': '222260252323873333_budget_category-food_planned',
|
||||
'unit_of_measurement': '$',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[sensor.food_dining_groceries_budget_planned-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
'category_group': 'Food & Dining',
|
||||
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'monetary',
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Food & Dining - Groceries Budget planned',
|
||||
<SensorEntityStateAttribute.LAST_RESET: 'last_reset'>: '2026-09-01T00:00:00+00:00',
|
||||
'month': '2026-09-01',
|
||||
<SensorEntityCapabilityAttribute.STATE_CLASS: 'state_class'>: <SensorStateClass.TOTAL: 'total'>,
|
||||
<EntityStateAttribute.UNIT_OF_MEASUREMENT: 'unit_of_measurement'>: '$',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.food_dining_groceries_budget_planned',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': '-500.0',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[sensor.food_dining_groceries_budget_remaining-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
<SensorEntityCapabilityAttribute.STATE_CLASS: 'state_class'>: <SensorStateClass.TOTAL: 'total'>,
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': <ANY>,
|
||||
'device_class': None,
|
||||
'device_id': <ANY>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.food_dining_groceries_budget_remaining',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Budget remaining',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <SensorDeviceClass.MONETARY: 'monetary'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'Budget remaining',
|
||||
'platform': 'monarch_money',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'budget_remaining',
|
||||
'unique_id': '222260252323873333_budget_category-food_remaining',
|
||||
'unit_of_measurement': '$',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[sensor.food_dining_groceries_budget_remaining-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
'category_group': 'Food & Dining',
|
||||
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'monetary',
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Food & Dining - Groceries Budget remaining',
|
||||
<SensorEntityStateAttribute.LAST_RESET: 'last_reset'>: '2026-09-01T00:00:00+00:00',
|
||||
'month': '2026-09-01',
|
||||
<SensorEntityCapabilityAttribute.STATE_CLASS: 'state_class'>: <SensorStateClass.TOTAL: 'total'>,
|
||||
<EntityStateAttribute.UNIT_OF_MEASUREMENT: 'unit_of_measurement'>: '$',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.food_dining_groceries_budget_remaining',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': '625.0',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[sensor.housing_rent_budget_actual-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
<SensorEntityCapabilityAttribute.STATE_CLASS: 'state_class'>: <SensorStateClass.TOTAL: 'total'>,
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': <ANY>,
|
||||
'device_class': None,
|
||||
'device_id': <ANY>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.housing_rent_budget_actual',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Budget actual',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <SensorDeviceClass.MONETARY: 'monetary'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'Budget actual',
|
||||
'platform': 'monarch_money',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'budget_actual',
|
||||
'unique_id': '222260252323873333_budget_category-housing_actual',
|
||||
'unit_of_measurement': '$',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[sensor.housing_rent_budget_actual-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'monetary',
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Housing - Rent Budget actual',
|
||||
<SensorEntityCapabilityAttribute.STATE_CLASS: 'state_class'>: <SensorStateClass.TOTAL: 'total'>,
|
||||
<EntityStateAttribute.UNIT_OF_MEASUREMENT: 'unit_of_measurement'>: '$',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.housing_rent_budget_actual',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'unavailable',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[sensor.housing_rent_budget_planned-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
<SensorEntityCapabilityAttribute.STATE_CLASS: 'state_class'>: <SensorStateClass.TOTAL: 'total'>,
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': <ANY>,
|
||||
'device_class': None,
|
||||
'device_id': <ANY>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.housing_rent_budget_planned',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Budget planned',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <SensorDeviceClass.MONETARY: 'monetary'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'Budget planned',
|
||||
'platform': 'monarch_money',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'budget_planned',
|
||||
'unique_id': '222260252323873333_budget_category-housing_planned',
|
||||
'unit_of_measurement': '$',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[sensor.housing_rent_budget_planned-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'monetary',
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Housing - Rent Budget planned',
|
||||
<SensorEntityCapabilityAttribute.STATE_CLASS: 'state_class'>: <SensorStateClass.TOTAL: 'total'>,
|
||||
<EntityStateAttribute.UNIT_OF_MEASUREMENT: 'unit_of_measurement'>: '$',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.housing_rent_budget_planned',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'unavailable',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[sensor.housing_rent_budget_remaining-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
<SensorEntityCapabilityAttribute.STATE_CLASS: 'state_class'>: <SensorStateClass.TOTAL: 'total'>,
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': <ANY>,
|
||||
'device_class': None,
|
||||
'device_id': <ANY>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.housing_rent_budget_remaining',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Budget remaining',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <SensorDeviceClass.MONETARY: 'monetary'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'Budget remaining',
|
||||
'platform': 'monarch_money',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'budget_remaining',
|
||||
'unique_id': '222260252323873333_budget_category-housing_remaining',
|
||||
'unit_of_measurement': '$',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[sensor.housing_rent_budget_remaining-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'monetary',
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Housing - Rent Budget remaining',
|
||||
<SensorEntityCapabilityAttribute.STATE_CLASS: 'state_class'>: <SensorStateClass.TOTAL: 'total'>,
|
||||
<EntityStateAttribute.UNIT_OF_MEASUREMENT: 'unit_of_measurement'>: '$',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.housing_rent_budget_remaining',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'unavailable',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[sensor.manual_entry_wallet_balance-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
@@ -1337,6 +1676,180 @@
|
||||
'state': 'unknown',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[sensor.travel_vacation_budget_actual-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
<SensorEntityCapabilityAttribute.STATE_CLASS: 'state_class'>: <SensorStateClass.TOTAL: 'total'>,
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': <ANY>,
|
||||
'device_class': None,
|
||||
'device_id': <ANY>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.travel_vacation_budget_actual',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Budget actual',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <SensorDeviceClass.MONETARY: 'monetary'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'Budget actual',
|
||||
'platform': 'monarch_money',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'budget_actual',
|
||||
'unique_id': '222260252323873333_budget_category-vacation_actual',
|
||||
'unit_of_measurement': '$',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[sensor.travel_vacation_budget_actual-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
'category_group': 'Travel',
|
||||
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'monetary',
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Travel - Vacation Budget actual',
|
||||
<SensorEntityStateAttribute.LAST_RESET: 'last_reset'>: '2026-09-01T00:00:00+00:00',
|
||||
'month': '2026-09-01',
|
||||
<SensorEntityCapabilityAttribute.STATE_CLASS: 'state_class'>: <SensorStateClass.TOTAL: 'total'>,
|
||||
<EntityStateAttribute.UNIT_OF_MEASUREMENT: 'unit_of_measurement'>: '$',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.travel_vacation_budget_actual',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'unknown',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[sensor.travel_vacation_budget_planned-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
<SensorEntityCapabilityAttribute.STATE_CLASS: 'state_class'>: <SensorStateClass.TOTAL: 'total'>,
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': <ANY>,
|
||||
'device_class': None,
|
||||
'device_id': <ANY>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.travel_vacation_budget_planned',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Budget planned',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <SensorDeviceClass.MONETARY: 'monetary'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'Budget planned',
|
||||
'platform': 'monarch_money',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'budget_planned',
|
||||
'unique_id': '222260252323873333_budget_category-vacation_planned',
|
||||
'unit_of_measurement': '$',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[sensor.travel_vacation_budget_planned-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
'category_group': 'Travel',
|
||||
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'monetary',
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Travel - Vacation Budget planned',
|
||||
<SensorEntityStateAttribute.LAST_RESET: 'last_reset'>: '2026-09-01T00:00:00+00:00',
|
||||
'month': '2026-09-01',
|
||||
<SensorEntityCapabilityAttribute.STATE_CLASS: 'state_class'>: <SensorStateClass.TOTAL: 'total'>,
|
||||
<EntityStateAttribute.UNIT_OF_MEASUREMENT: 'unit_of_measurement'>: '$',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.travel_vacation_budget_planned',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'unknown',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[sensor.travel_vacation_budget_remaining-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
<SensorEntityCapabilityAttribute.STATE_CLASS: 'state_class'>: <SensorStateClass.TOTAL: 'total'>,
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': <ANY>,
|
||||
'device_class': None,
|
||||
'device_id': <ANY>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.travel_vacation_budget_remaining',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Budget remaining',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <SensorDeviceClass.MONETARY: 'monetary'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'Budget remaining',
|
||||
'platform': 'monarch_money',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'budget_remaining',
|
||||
'unique_id': '222260252323873333_budget_category-vacation_remaining',
|
||||
'unit_of_measurement': '$',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[sensor.travel_vacation_budget_remaining-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
'category_group': 'Travel',
|
||||
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'monetary',
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Travel - Vacation Budget remaining',
|
||||
<SensorEntityStateAttribute.LAST_RESET: 'last_reset'>: '2026-09-01T00:00:00+00:00',
|
||||
'month': '2026-09-01',
|
||||
<SensorEntityCapabilityAttribute.STATE_CLASS: 'state_class'>: <SensorStateClass.TOTAL: 'total'>,
|
||||
<EntityStateAttribute.UNIT_OF_MEASUREMENT: 'unit_of_measurement'>: '$',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.travel_vacation_budget_remaining',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'unknown',
|
||||
})
|
||||
# ---
|
||||
# name: test_all_entities[sensor.vinaudit_2050_toyota_rav8_data_age-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
|
||||
@@ -20,25 +20,59 @@ from . import setup_integration
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
|
||||
async def test_cashflow_year_follows_configured_time_zone(
|
||||
@pytest.mark.parametrize(
|
||||
(
|
||||
"time_zone",
|
||||
"frozen_time",
|
||||
"cashflow_start_date",
|
||||
"cashflow_end_date",
|
||||
"budget_start_date",
|
||||
"budget_end_date",
|
||||
),
|
||||
[
|
||||
pytest.param(
|
||||
"Pacific/Kiritimati",
|
||||
"2025-12-31T12:00:00+00:00",
|
||||
"2026-01-01",
|
||||
"2026-12-31",
|
||||
"2026-01-01",
|
||||
"2026-01-31",
|
||||
id="new_year_in_configured_time_zone",
|
||||
),
|
||||
pytest.param(
|
||||
"America/Los_Angeles",
|
||||
"2024-02-29T23:30:00-08:00",
|
||||
"2024-01-01",
|
||||
"2024-12-31",
|
||||
"2024-02-01",
|
||||
"2024-02-29",
|
||||
id="leap_year",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_query_windows_follow_configured_time_zone(
|
||||
hass: HomeAssistant,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_config_api: AsyncMock,
|
||||
time_zone: str,
|
||||
frozen_time: str,
|
||||
cashflow_start_date: str,
|
||||
cashflow_end_date: str,
|
||||
budget_start_date: str,
|
||||
budget_end_date: str,
|
||||
) -> None:
|
||||
"""Test the cashflow window uses the year of the configured time zone.
|
||||
|
||||
The clock is stopped at a moment that is still 2025 in UTC but already 2026
|
||||
in Pacific/Kiritimati, so a query built from the host clock would ask for
|
||||
the wrong year.
|
||||
"""
|
||||
await hass.config.async_set_time_zone("Pacific/Kiritimati") # UTC+14
|
||||
freezer.move_to("2025-12-31T12:00:00+00:00")
|
||||
"""Test query windows use the configured time zone."""
|
||||
await hass.config.async_set_time_zone(time_zone)
|
||||
freezer.move_to(frozen_time)
|
||||
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
mock_config_api.return_value.get_cashflow_summary.assert_called_with(
|
||||
start_date="2026-01-01", end_date="2026-12-31"
|
||||
start_date=cashflow_start_date, end_date=cashflow_end_date
|
||||
)
|
||||
mock_config_api.return_value.get_budgets_as_dict_with_id_key.assert_called_with(
|
||||
start_date=budget_start_date, end_date=budget_end_date
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
"""Test sensors."""
|
||||
|
||||
from copy import deepcopy
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
import pytest
|
||||
from syrupy.assertion import SnapshotAssertion
|
||||
from typedmonarchmoney.models import MonarchBudget
|
||||
|
||||
from homeassistant.components.monarch_money.const import DOMAIN
|
||||
from homeassistant.const import Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
from homeassistant.helpers import device_registry as dr, entity_registry as er
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
from . import setup_integration
|
||||
|
||||
@@ -21,14 +25,218 @@ async def test_all_entities(
|
||||
mock_config_entry: MockConfigEntry,
|
||||
entity_registry: er.EntityRegistry,
|
||||
mock_config_api: AsyncMock,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""Test all entities."""
|
||||
await hass.config.async_set_time_zone("UTC")
|
||||
freezer.move_to("2026-09-20T12:00:00+00:00")
|
||||
with patch("homeassistant.components.monarch_money.PLATFORMS", [Platform.SENSOR]):
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
|
||||
|
||||
|
||||
async def test_budget_sensors(
|
||||
hass: HomeAssistant,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
device_registry: dr.DeviceRegistry,
|
||||
entity_registry: er.EntityRegistry,
|
||||
mock_config_api: AsyncMock,
|
||||
) -> None:
|
||||
"""Test budget sensors preserve rollovers and missing amounts."""
|
||||
await hass.config.async_set_time_zone("UTC")
|
||||
freezer.move_to("2026-09-20T12:00:00+00:00")
|
||||
with patch("homeassistant.components.monarch_money.PLATFORMS", [Platform.SENSOR]):
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
subscription_id = (
|
||||
mock_config_api.return_value.get_subscription_details.return_value.id
|
||||
)
|
||||
actual_entity_id = entity_registry.async_get_entity_id(
|
||||
"sensor", DOMAIN, f"{subscription_id}_budget_category-food_actual"
|
||||
)
|
||||
planned_entity_id = entity_registry.async_get_entity_id(
|
||||
"sensor", DOMAIN, f"{subscription_id}_budget_category-food_planned"
|
||||
)
|
||||
remaining_entity_id = entity_registry.async_get_entity_id(
|
||||
"sensor", DOMAIN, f"{subscription_id}_budget_category-food_remaining"
|
||||
)
|
||||
missing_value_entity_id = entity_registry.async_get_entity_id(
|
||||
"sensor", DOMAIN, f"{subscription_id}_budget_category-vacation_actual"
|
||||
)
|
||||
|
||||
assert actual_entity_id is not None
|
||||
assert planned_entity_id is not None
|
||||
assert remaining_entity_id is not None
|
||||
assert missing_value_entity_id is not None
|
||||
actual_entry = entity_registry.async_get(actual_entity_id)
|
||||
planned_entry = entity_registry.async_get(planned_entity_id)
|
||||
remaining_entry = entity_registry.async_get(remaining_entity_id)
|
||||
assert actual_entry is not None
|
||||
assert planned_entry is not None
|
||||
assert remaining_entry is not None
|
||||
assert actual_entry.device_id is not None
|
||||
assert (
|
||||
actual_entry.device_id == planned_entry.device_id == remaining_entry.device_id
|
||||
)
|
||||
|
||||
device = device_registry.async_get(actual_entry.device_id)
|
||||
assert device is not None
|
||||
assert device.entry_type is dr.DeviceEntryType.SERVICE
|
||||
assert (DOMAIN, f"{subscription_id}_budget_category-food") in device.identifiers
|
||||
|
||||
actual_state = hass.states.get(actual_entity_id)
|
||||
assert actual_state is not None
|
||||
remaining_state = hass.states.get(remaining_entity_id)
|
||||
missing_value_state = hass.states.get(missing_value_entity_id)
|
||||
assert remaining_state is not None
|
||||
assert missing_value_state is not None
|
||||
assert remaining_state.state == "625.0"
|
||||
assert missing_value_state.state == "unknown"
|
||||
assert (
|
||||
actual_state.attributes["last_reset"]
|
||||
== dt_util.start_of_local_day(dt_util.now().replace(day=1)).isoformat()
|
||||
)
|
||||
|
||||
|
||||
async def test_budget_sensors_discover_and_recover_categories(
|
||||
hass: HomeAssistant,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
entity_registry: er.EntityRegistry,
|
||||
mock_config_api: AsyncMock,
|
||||
) -> None:
|
||||
"""Test budget categories are added later and recover after missing data."""
|
||||
await hass.config.async_set_time_zone("UTC")
|
||||
freezer.move_to("2026-09-20T12:00:00+00:00")
|
||||
budget_data = (
|
||||
mock_config_api.return_value.get_budgets_as_dict_with_id_key.return_value
|
||||
)
|
||||
budget_data_without_vacation = {"category-food": budget_data["category-food"]}
|
||||
mock_config_api.return_value.get_budgets_as_dict_with_id_key.side_effect = [
|
||||
budget_data_without_vacation,
|
||||
budget_data,
|
||||
budget_data_without_vacation,
|
||||
budget_data,
|
||||
]
|
||||
|
||||
with patch("homeassistant.components.monarch_money.PLATFORMS", [Platform.SENSOR]):
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
subscription_id = (
|
||||
mock_config_api.return_value.get_subscription_details.return_value.id
|
||||
)
|
||||
vacation_unique_id = f"{subscription_id}_budget_category-vacation_actual"
|
||||
assert (
|
||||
entity_registry.async_get_entity_id("sensor", DOMAIN, vacation_unique_id)
|
||||
is None
|
||||
)
|
||||
|
||||
coordinator = mock_config_entry.runtime_data
|
||||
await coordinator.async_refresh()
|
||||
await hass.async_block_till_done()
|
||||
|
||||
vacation_entity_id = entity_registry.async_get_entity_id(
|
||||
"sensor", DOMAIN, vacation_unique_id
|
||||
)
|
||||
assert vacation_entity_id is not None
|
||||
|
||||
await coordinator.async_refresh()
|
||||
await hass.async_block_till_done()
|
||||
vacation_state = hass.states.get(vacation_entity_id)
|
||||
assert vacation_state is not None
|
||||
assert vacation_state.state == "unavailable"
|
||||
|
||||
await coordinator.async_refresh()
|
||||
await hass.async_block_till_done()
|
||||
vacation_state = hass.states.get(vacation_entity_id)
|
||||
assert vacation_state is not None
|
||||
assert vacation_state.state == "unknown"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("category_id", "monthly_amounts"),
|
||||
[
|
||||
pytest.param(
|
||||
"category-stale",
|
||||
[
|
||||
{
|
||||
"month": "2026-08-01",
|
||||
"plannedCashFlowAmount": -1200.0,
|
||||
"actualAmount": -1200.0,
|
||||
"remainingAmount": 0.0,
|
||||
}
|
||||
],
|
||||
id="stale_month_only",
|
||||
),
|
||||
pytest.param(
|
||||
"category-without-amounts",
|
||||
[],
|
||||
id="no_monthly_record",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_budget_sensors_recover_when_current_month_appears(
|
||||
hass: HomeAssistant,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
entity_registry: er.EntityRegistry,
|
||||
mock_config_api: AsyncMock,
|
||||
category_id: str,
|
||||
monthly_amounts: list[dict[str, str | float]],
|
||||
) -> None:
|
||||
"""Test a known budget starts unavailable until its current month appears."""
|
||||
await hass.config.async_set_time_zone("UTC")
|
||||
freezer.move_to("2026-09-20T12:00:00+00:00")
|
||||
budget_data = deepcopy(
|
||||
mock_config_api.return_value.get_budgets_as_dict_with_id_key.return_value
|
||||
)
|
||||
budget_data[category_id] = MonarchBudget(
|
||||
{"id": category_id, "name": "Test budget"},
|
||||
group_name="Test budgets",
|
||||
monthly_amounts=monthly_amounts,
|
||||
)
|
||||
budget_data_with_current_month = deepcopy(budget_data)
|
||||
budget_data_with_current_month[category_id] = MonarchBudget(
|
||||
{"id": category_id, "name": "Test budget"},
|
||||
group_name="Test budgets",
|
||||
monthly_amounts=[
|
||||
{
|
||||
"month": "2026-09-01",
|
||||
"plannedCashFlowAmount": -1200.0,
|
||||
"actualAmount": -400.0,
|
||||
"remainingAmount": 800.0,
|
||||
}
|
||||
],
|
||||
)
|
||||
mock_config_api.return_value.get_budgets_as_dict_with_id_key.side_effect = [
|
||||
budget_data,
|
||||
budget_data_with_current_month,
|
||||
]
|
||||
|
||||
with patch("homeassistant.components.monarch_money.PLATFORMS", [Platform.SENSOR]):
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
subscription_id = (
|
||||
mock_config_api.return_value.get_subscription_details.return_value.id
|
||||
)
|
||||
budget_entity_id = entity_registry.async_get_entity_id(
|
||||
"sensor", DOMAIN, f"{subscription_id}_budget_{category_id}_actual"
|
||||
)
|
||||
assert budget_entity_id is not None
|
||||
budget_state = hass.states.get(budget_entity_id)
|
||||
assert budget_state is not None
|
||||
assert budget_state.state == "unavailable"
|
||||
|
||||
await mock_config_entry.runtime_data.async_refresh()
|
||||
await hass.async_block_till_done()
|
||||
|
||||
budget_state = hass.states.get(budget_entity_id)
|
||||
assert budget_state is not None
|
||||
assert budget_state.state == "-400.0"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("account_owner", "expected_state"),
|
||||
[
|
||||
|
||||
Reference in New Issue
Block a user