Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Tibber get_prices when called with aware datetime #123289

Merged
merged 5 commits into from
Oct 2, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
13 changes: 5 additions & 8 deletions homeassistant/components/tibber/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from __future__ import annotations

import datetime as dt
from datetime import date, datetime
from datetime import datetime
from functools import partial
from typing import Any, Final

Expand Down Expand Up @@ -61,27 +61,24 @@ async def __get_prices(call: ServiceCall, *, hass: HomeAssistant) -> ServiceResp
]

selected_data = [
price
for price in price_data
if price["start_time"].replace(tzinfo=None) >= start
and price["start_time"].replace(tzinfo=None) < end
price for price in price_data if start <= price["start_time"] < end
]
tibber_prices[home_nickname] = selected_data

return {"prices": tibber_prices}


def __get_date(date_input: str | None, mode: str | None) -> date | datetime:
def __get_date(date_input: str | None, mode: str | None) -> datetime:
"""Get date."""
if not date_input:
if mode == "end":
increment = dt.timedelta(days=1)
else:
increment = dt.timedelta()
return datetime.fromisoformat(dt_util.now().date().isoformat()) + increment
return dt_util.start_of_local_day() + increment

if value := dt_util.parse_datetime(date_input):
return value
return dt_util.as_local(value)

raise ServiceValidationError(
"Invalid datetime provided.",
Expand Down
89 changes: 88 additions & 1 deletion tests/components/tibber/test_services.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,11 @@
from homeassistant.components.tibber.services import PRICE_SERVICE_NAME, __get_prices
from homeassistant.core import ServiceCall
from homeassistant.exceptions import ServiceValidationError
from homeassistant.util import dt as dt_util

STARTTIME = dt.datetime.fromtimestamp(1615766400)
STARTTIME = dt.datetime.fromtimestamp(1615766400).replace(
tzinfo=dt_util.get_default_time_zone()
)


def generate_mock_home_data():
Expand Down Expand Up @@ -246,6 +249,90 @@ async def test_get_prices_start_tomorrow(
}


async def test_get_prices_with_timezone(
freezer: FrozenDateTimeFactory,
) -> None:
"""Test __get_prices with start date tomorrow."""
freezer.move_to(STARTTIME)
call = ServiceCall(
DOMAIN, PRICE_SERVICE_NAME, {"start": dt_util.start_of_local_day().isoformat()}
)

result = await __get_prices(call, hass=create_mock_hass())
Copy link
Member

@MartinHjelmare MartinHjelmare Oct 2, 2024

Choose a reason for hiding this comment

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

Please test the services by calling the services from the core service registry, while patching the library. Use hass.services.async_call.

https://developers.home-assistant.io/docs/development_testing#writing-tests-for-integrations

Set up integration with a MockConfigEntry while patching the library client, and then call the service.


assert result == {
"prices": {
"first_home": [
{
"start_time": STARTTIME,
"price": 0.46914,
"level": "VERY_EXPENSIVE",
},
{
"start_time": STARTTIME + dt.timedelta(hours=1),
"price": 0.46914,
"level": "VERY_EXPENSIVE",
},
],
"second_home": [
{
"start_time": STARTTIME,
"price": 0.46914,
"level": "VERY_EXPENSIVE",
},
{
"start_time": STARTTIME + dt.timedelta(hours=1),
"price": 0.46914,
"level": "VERY_EXPENSIVE",
},
],
}
}


async def test_get_prices_without_timezone(
freezer: FrozenDateTimeFactory,
) -> None:
"""Test __get_prices with start date tomorrow."""
freezer.move_to(STARTTIME)
call = ServiceCall(
DOMAIN,
PRICE_SERVICE_NAME,
{"start": dt_util.start_of_local_day().replace(tzinfo=None).isoformat()},
)

result = await __get_prices(call, hass=create_mock_hass())

assert result == {
"prices": {
"first_home": [
{
"start_time": STARTTIME,
"price": 0.46914,
"level": "VERY_EXPENSIVE",
},
{
"start_time": STARTTIME + dt.timedelta(hours=1),
"price": 0.46914,
"level": "VERY_EXPENSIVE",
},
],
"second_home": [
{
"start_time": STARTTIME,
"price": 0.46914,
"level": "VERY_EXPENSIVE",
},
{
"start_time": STARTTIME + dt.timedelta(hours=1),
"price": 0.46914,
"level": "VERY_EXPENSIVE",
},
],
}
}
frenck marked this conversation as resolved.
Show resolved Hide resolved


async def test_get_prices_invalid_input() -> None:
"""Test __get_prices with invalid input."""

Expand Down