Files
EOS/tests/test_measurementenergy.py
T
Bobby NoelteandClaude Opus 5.5 f441759dfa fix(measurement): use quality-aware meter energy for load and PV
Additional fixes
Measurement.meter_energy_kwh converts meter energy over the whole period in one read; the 31-day and 10000-interval limits apply to the public energy queries only.
Load intervals a meter does not fully cover are NaN and the load adjustment skips them; load_total_kwh returns an empty array for an empty store and keeps full last intervals.
The load adjustment compares over the period the load meters report, skips a stale load meter period and says when no load meter is configured.
PV calibration, snow feedback and the load adjustment fall back without measurements when a conversion fails, logged as error once per failure streak and consumer.
Measurement.keys_first_datetime and keys_last_datetime find each meter's first and last valid reading in bounded scans, keep each meter's newest reading and return stamps in the configured zone.
Measurement.keys_common_period derives the common meter period for PV calibration and the load adjustment and names the meter that ends it, also when meters share no period.
PV calibration warns once per stale period when a stopped PV meter holds it on old data; snow feedback warns once about a stale feedback meter.
Lasting meter conditions (silent, reset, gap, replaced meter, no shared period) are warned once per condition and consumer through one helper and warned again when they recur.
A replaced meter whose readings touch the new one is reported; a single reading is not; a meter group waiting for its second reading is an info once.
The PV meter resolution is detected from valid readings only (pre-existing), using one shared valid-reading rule in energy.py.
Stale meter stamps are compared with compare_datetimes; new meter tests create durations with datetimeutil.
The unused legacy Measurement._energy_from_meter_readings is removed; its test scenarios cover meter_energy_kwh.
The converter's range error no longer mentions the API's 31-day limit, and its duplicate interval check is gone.
Measurement and prediction docs describe the meter coverage rule, even gap spreading and when the load forecast stays unadjusted.
Tests reset the warn-once state of the shared measurement store and restore the EMS start they change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Assisted-by: Claude Code (claude-opus-5-5)
2026-11-15 18:30:00 +01:00

156 lines
5.8 KiB
Python

"""Physical and temporal contracts for interval energy."""
# ruff: noqa: S101
from datetime import datetime, timedelta, timezone
from typing import Any
from zoneinfo import ZoneInfo
import pytest
from akkudoktoreos.measurement.energy import energy_intervals, valid_reading
from akkudoktoreos.measurement.measurement import MeasurementChannelSettings
from akkudoktoreos.measurement.quality import SampleQuality
from akkudoktoreos.utils.datetimeutil import to_datetime
START = datetime(2026, 9, 10, tzinfo=timezone.utc)
def channel(quantity="power", **kwargs):
defaults: dict[str, dict[str, Any]] = {
"power": dict(unit="W", integration_method="hold", max_gap_seconds=900),
"cumulative_energy": dict(unit="kWh"),
"interval_energy": dict(unit="Wh", interval_seconds=900, timestamp_reference="start"),
}
return MeasurementChannelSettings(quantity=quantity, **(defaults[quantity] | kwargs))
def convert(points, config=None, seconds=900):
return energy_intervals(
[(START + timedelta(seconds=t), v) for t, v in points],
config or channel(),
START,
START + timedelta(seconds=seconds),
)
@pytest.mark.parametrize(
"config,points",
[
(channel(), [(0, 800), (900, 800)]),
(channel(unit="kW"), [(0, 0.8), (900, 0.8)]),
(channel("cumulative_energy"), [(0, 10), (900, 10.2)]),
(channel("interval_energy"), [(0, 200)]),
(channel("interval_energy", timestamp_reference="end"), [(900, 200)]),
],
)
def test_equivalent_measurements(config, points):
result = convert(points, config)[0]
assert result.energy_wh == pytest.approx(200)
assert result.coverage_seconds == 900
assert result.coverage_status == "complete"
def test_time_weighting_and_linear_interpolation():
assert convert([(0, 0), (600, 1200), (900, 1200)])[0].energy_wh == 100
assert convert([(0, 0), (900, 1600)], channel(integration_method="linear"))[0].energy_wh == 200
def test_gap_and_no_extrapolation():
result = convert([(0, 800), (300, 800)])[0]
assert result.energy_wh is None
assert result.observed_energy_wh == pytest.approx(800 / 12)
assert result.coverage_status == "partial"
assert convert([(0, 800), (900, 800)], channel(max_gap_seconds=60))[0].energy_wh is None
assert convert([])[0].coverage_status == "missing"
def test_null_breaks_hold_at_outage():
result = convert([(0, 800), (300, None), (600, 800), (900, 800)])[0]
assert result.coverage_seconds == 600
assert result.coverage_status == "partial"
assert len(result.coverage_ranges) == 2
def test_reset_does_not_create_negative_consumption():
result = convert([(0, 10), (450, 0), (900, 0.1)], channel("cumulative_energy"))[0]
assert result.energy_wh is None
assert result.observed_energy_wh == pytest.approx(100)
assert "meter_reset" in result.flags
def test_hour_allocation_conserves_energy_and_is_labelled():
result = convert([(0, 1000)], channel("interval_energy", interval_seconds=3600), 3600)
assert all(r.energy_wh is not None for r in result)
assert sum(r.energy_wh for r in result if r.energy_wh is not None) == 1000
assert all("allocated_energy" in r.methods for r in result)
@pytest.mark.parametrize(
"quantity,points",
[
("power", [(0, 1), (0, 2)]),
("interval_energy", [(0, 100), (450, 100)]),
],
)
def test_ambiguous_time_support_rejected(quantity, points):
with pytest.raises(ValueError):
convert(points, channel(quantity))
def test_nan_and_signed_power():
assert convert([(0, float("nan")), (900, 800)])[0].energy_wh is None
assert convert([(0, -800), (900, -800)])[0].energy_wh == -200
@pytest.mark.parametrize("month,day,hours", [(3, 29, 23), (10, 25, 25)])
def test_dst_calendar_day(month, day, hours):
start = datetime(2026, month, day, tzinfo=ZoneInfo("Europe/Berlin"))
end = start + timedelta(days=1)
result = energy_intervals([(start, 0), (end, hours)], channel("cumulative_energy"), start, end)
assert len(result) == hours * 4
assert all(r.energy_wh is not None for r in result)
assert sum(r.energy_wh for r in result if r.energy_wh is not None) == pytest.approx(hours * 1000)
@pytest.mark.asyncio
async def test_measurement_wrapper_preserves_asynchronous_channels(config_eos):
from akkudoktoreos.core.coreabc import get_measurement
from akkudoktoreos.measurement.measurement import MeasurementCommonSettings
measurement = get_measurement()
previous, records = config_eos.measurement, measurement.records
try:
config_eos.measurement = MeasurementCommonSettings(
channels={"p": channel(), "other": channel()}
)
measurement._db_reset_state()
(await measurement.update_value(to_datetime(START), "p", 800))
(await measurement.update_value(to_datetime(START + timedelta(seconds=450)), "other", 1))
(await measurement.update_value(to_datetime(START + timedelta(seconds=900)), "p", 800))
result = (await measurement.energy_intervals("p", START, START + timedelta(seconds=900)))
assert result[0].energy_wh == 200
finally:
measurement._db_reset_state()
measurement.records = records
config_eos.measurement = previous
@pytest.mark.parametrize(
("value", "quality", "expected"),
[
(1, None, 1.0),
(2.5, SampleQuality(status="estimated"), 2.5),
(2.5, SampleQuality(status="invalid"), None),
(2.5, SampleQuality(status="unavailable"), None),
(True, None, None),
(float("nan"), None, None),
(float("inf"), None, None),
(None, None, None),
("1.0", None, None),
],
)
def test_valid_reading(value: Any, quality: SampleQuality | None, expected: float | None) -> None:
"""One rule decides which raw readings count, shared by conversion and scans."""
assert valid_reading(value, quality) == expected