mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2026-08-30 04:06:37 +00:00
Add new provider class for electricity fees providers. Add the generic providers: - ElecFeeFixed - ElecFeeImport The providers provide predictions for: - elecfee_consumption_amt_wh: Total fixed fee for consumed energy per Wh [amount/Wh]. This is the accumulation of all fixed per-Wh fees payable on "consumed energy - such as network charge, concession fee, and electricity charge - into a single amount. - elecfee_consumption_percent_amt: Total fixed surcharge on consumed energy, given as a percentage of the monetary amount already charged for that energy [%]. This is the accumulation of all percentage-based surcharges payable on top of the consumed-energy fee - such as VAT - into a single percentage. This is a percentage of the fee amount, not a per-Wh rate. - elecfee_feedin_amt_wh: Total fixed deduction from feed-in energy per Wh [amount/Wh]. This is the accumulation of all fixed per-Wh charges deducted from feed-in energy - such as metering fees or grid-operator handling "charges - into a single amount. Applied after the percentage-based deduction, i.e. it reduces the price by a flat amount per Wh rather than by a share of the raw price. - elecfee_feedin_percent_amt: Total percentage deducted from the raw feed-in price (spot price) [%]. This is the accumulation of all percentage-based deductions payable on the feed-in tariff - such as a marketing or balancing fee retained by the aggregator - into a single percentage. It is applied as `raw_price * (100 - percent) / 100`, i.e. it scales down the raw price rather than adding a surcharge to it. A new _apply_fee() method is added to the base class for ElecPrice and FeedInTariff to be used to add the fees in a consistent way. Fees are taken from the active ElecFee provider and applied to the raw prices given to the _apply_fee() method. The optional application of fees is added to: - ElecPriceAkkudoktor - ElecPriceFixed - ElecPriceEnergyCharts - ElecPriceSMARD - FeedInTariffEnergyCharts - FeedInTariffFixed - FeedInTariffSMARD The import providers ElecPriceImport and FeedInTariffImport do not apply fees by intentention. The following providers currently do not handle fees defined by ElecFee: - ElecPriceTibber - FeedInTariffAkkudoktor - FeedInTariffDvhubOnline - FeedInTariffTibber The tests for this feature are either added or existing tests are extended. The documentation was extended for the electricity fee provider settings. Besides this feature further improvements are added: * feat: add SMARD quarter-hour electricty price and feed-in tariff provider * feat: to_series method for TimeWindows and ValueTimeWindows Additional to to_array the time window sequence can now also produce a pandas series. Test have been extended to cover the series generation. * feat: use time windows in fixed feedin tariff provider Feedin tariff can now be configured by time windows - not a single value. * feat: EOSdash select for PVLib inverters and modules Provide PVLib inverter and module names in config selection. * feat: EOSdash lazy select for big option sets Add a new form for lazy selection of big option sets. Filtering and generation of the option set is done server-side. * fix: use raw data for ETS/ median prediction Use to raw time series data for ETS/ median prediction to avoid interference by e.g. dynamic grid charges. * fix: EOSdash config drops by type only on details resolve Drop configuration by type and path. Prevents dropping of configuration items with same type and level but different path. * fix: EOSdash configuration section closes on update Open section if searching or if last update touched this category — including updates on deeply nested sub-fields. * chore: make elecfeefixed, elecpricefixed and feedintarifffixed warn about no windows and default to 0 Missining configuration creates default 0 value and a warning instead of an exception. * fix: test setup for providers Reset db state on each test run. * chore: improve config option naming for elecpricefixed. * chore: adapt elecpricefixed test to changed time_windows naming * chore: factorized common price provider helpers to priceabc.py Factorized common price provider helpers to priceabc.py. Add tests for these helpers. Reduce/ change testing of elecpriceabc.py and feedintariffabc.py to cover only specifics. Rest of testing is already covered by test_priceabc.py. * chore: update version Signed-off-by: Bobby Noelte <b0661n0e17e@gmail.com>
128 lines
4.7 KiB
Python
128 lines
4.7 KiB
Python
"""Tests for the native quarter-hour Tibber feed-in tariff provider."""
|
|
|
|
import json
|
|
from unittest.mock import Mock, patch
|
|
|
|
import pytest
|
|
import pytest_asyncio
|
|
|
|
from akkudoktoreos.core.coreabc import get_ems
|
|
from akkudoktoreos.prediction.elecpricetibber import TibberGraphQLResponse
|
|
from akkudoktoreos.prediction.feedintarifftibber import FeedInTariffTibber
|
|
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration
|
|
|
|
|
|
def _point(starts_at: str, energy: float, total: float = 0.40) -> dict[str, object]:
|
|
return {"startsAt": starts_at, "energy": energy, "total": total}
|
|
|
|
|
|
def _payload(points: list[dict[str, object]]) -> dict[str, object]:
|
|
return {
|
|
"data": {
|
|
"viewer": {
|
|
"homes": [
|
|
{
|
|
"id": "home-1",
|
|
"currentSubscription": {
|
|
"priceInfo": {"today": points[:4], "tomorrow": points[4:]},
|
|
"priceInfoRange": {"nodes": points},
|
|
},
|
|
}
|
|
]
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
@pytest.fixture
|
|
def quarter_hour_points() -> list[dict]:
|
|
return [
|
|
_point(f"2026-07-15T0{index // 4}:{(index % 4) * 15:02d}:00+02:00", 0.10 + index / 100)
|
|
for index in range(8)
|
|
]
|
|
|
|
|
|
@pytest.fixture
|
|
def provider(config_eos):
|
|
"""Create a fresh Tibber feed-in tariff provider."""
|
|
config_eos.merge_settings_from_dict(
|
|
{
|
|
"elecprice": {"tibber": {"access_token": "token-123", "home_id": "home-1"}},
|
|
"feedintariff": {
|
|
"provider": "FeedInTariffTibber",
|
|
},
|
|
"prediction": {"hours": 2},
|
|
}
|
|
)
|
|
get_ems().set_start_datetime(
|
|
to_datetime("2026-07-15T00:00:00+02:00", in_timezone="Europe/Berlin")
|
|
)
|
|
provider = FeedInTariffTibber()
|
|
provider.highest_orig_datetime = None
|
|
assert provider.enabled()
|
|
provider._db_reset_state()
|
|
return provider
|
|
|
|
|
|
class TestFeedInTariffTibber:
|
|
|
|
def test_provider_is_registered_and_used_for_direct_marketing(self, provider, config_eos):
|
|
assert provider.enabled()
|
|
assert "FeedInTariffTibber" in config_eos.feedintariff.provider
|
|
|
|
def test_parse_uses_energy_component_at_native_quarter_hour_resolution(
|
|
self, provider, quarter_hour_points
|
|
):
|
|
response = TibberGraphQLResponse.model_validate(_payload(quarter_hour_points))
|
|
|
|
series = provider._parse_data(response)
|
|
|
|
assert series.tolist() == pytest.approx([(0.10 + index / 100) / 1000 for index in range(8)])
|
|
assert series.index.to_series().diff().dropna().dt.total_seconds().unique().tolist() == [900.0]
|
|
|
|
@patch("requests.post")
|
|
def test_request_is_strictly_quarter_hourly_and_requests_energy(
|
|
self, mock_post, provider, quarter_hour_points
|
|
):
|
|
response = Mock()
|
|
response.content = json.dumps(_payload(quarter_hour_points)).encode()
|
|
response.raise_for_status = Mock()
|
|
mock_post.return_value = response
|
|
|
|
provider._request_forecast(force_update=True)
|
|
|
|
query = mock_post.call_args.kwargs["json"]["query"]
|
|
assert "priceInfo(resolution: QUARTER_HOURLY)" in " ".join(query.split())
|
|
assert "priceInfoRange(resolution: QUARTER_HOURLY" in " ".join(query.split())
|
|
assert "energy" in query
|
|
assert mock_post.call_args.kwargs["headers"]["Authorization"] == "Bearer token-123"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_update_keeps_four_distinct_prices_per_hour(self, provider, quarter_hour_points, monkeypatch):
|
|
response = TibberGraphQLResponse.model_validate(_payload(quarter_hour_points))
|
|
monkeypatch.setattr(provider, "_request_forecast", lambda **_: response)
|
|
|
|
await provider._update_data(force_update=True)
|
|
|
|
start = to_datetime("2026-07-15T00:00:00+02:00", in_timezone="Europe/Berlin")
|
|
prices = await provider.key_to_array(
|
|
key="feed_in_tariff_wh",
|
|
start_datetime=start,
|
|
end_datetime=start + to_duration("2 hours"),
|
|
interval=to_duration("15 minutes"),
|
|
fill_method="ffill",
|
|
)
|
|
assert prices.tolist() == pytest.approx([(0.10 + index / 100) / 1000 for index in range(8)])
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_update_rejects_hourly_tibber_data(self, provider, monkeypatch):
|
|
hourly = [
|
|
_point("2026-07-15T00:00:00+02:00", 0.10),
|
|
_point("2026-07-15T01:00:00+02:00", 0.11),
|
|
]
|
|
response = TibberGraphQLResponse.model_validate(_payload(hourly))
|
|
monkeypatch.setattr(provider, "_request_forecast", lambda **_: response)
|
|
|
|
with pytest.raises(ValueError, match="requires native 15-minute prices"):
|
|
await provider._update_data(force_update=True)
|