Files
EOS/tests/test_measurement.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

736 lines
33 KiB
Python

import json
from unittest.mock import AsyncMock
import numpy as np
import pytest
import pytest_asyncio
from pendulum import datetime, duration
from pydantic import ValidationError
from akkudoktoreos.core.coreabc import get_measurement
from akkudoktoreos.core.dataabc import DataSequence
from akkudoktoreos.core.databaseabc import DatabaseTimestamp
from akkudoktoreos.measurement.measurement import (
MeasurementChannelSettings,
MeasurementCommonSettings,
MeasurementDataRecord,
)
from akkudoktoreos.measurement.quality import SampleQuality
from akkudoktoreos.utils.datetimeutil import (
compare_datetimes,
to_datetime,
to_duration,
)
class TestMeasurementDataRecord:
"""Measurement-specific keys, values, and serialization.
Generic native-field access is covered by TestDataRecord in test_dataabcrecord.py.
"""
@pytest.fixture
def sample_config(self, config_eos):
"""Fixture to configure the measurement keys on the global config."""
config_eos.measurement.load_emr_keys = ["dish_washer_mr", "temp"]
config_eos.measurement.pv_production_emr_keys = ["solar_power"]
return config_eos
@pytest.fixture
def record(self, sample_config):
"""Fixture to create a sample MeasurementDataRecord with some measurements set."""
rec = MeasurementDataRecord(date_time=None)
rec.configured_data = {"dish_washer_mr": 123.0, "solar_power": 456.0}
return rec
def test_record_keys_includes_measurement_keys(self, record):
"""Ensure record_keys includes all configured measurement keys."""
assert set(record.record_keys()) >= set(record.config.measurement.keys)
def test_record_keys_writable_includes_measurement_keys(self, record):
"""Ensure record_keys_writable includes all configured measurement keys."""
assert set(record.record_keys_writable()) >= set(record.config.measurement.keys)
def test_getitem_existing_field(self, record):
"""Test that __getitem__ returns correct value for existing native field."""
date_time = "2024-01-01T00:00:00+00:00"
record.date_time = date_time
assert compare_datetimes(record["date_time"], to_datetime(date_time)).equal
def test_getitem_existing_measurement(self, record):
"""Test that __getitem__ retrieves existing measurement values."""
assert record["dish_washer_mr"] == 123.0
assert record["solar_power"] == 456.0
def test_getitem_missing_measurement_returns_none(self, record):
"""Test that __getitem__ returns None for missing but known measurement keys."""
assert record["temp"] is None
def test_getitem_raises_keyerror(self, record):
"""Test that __getitem__ raises KeyError for completely unknown keys."""
with pytest.raises(KeyError):
_ = record["nonexistent"]
def test_setitem_measurement(self, record):
"""Test setting a known measurement key using __setitem__."""
record["temp"] = 25.5
assert record["temp"] == 25.5
def test_setitem_invalid_key_raises(self, record):
"""Test that __setitem__ raises KeyError for unknown keys."""
with pytest.raises(KeyError):
record["unknown_key"] = 123
def test_delitem_measurement(self, record):
"""Test deleting a known measurement key using __delitem__."""
del record["solar_power"]
assert record["solar_power"] is None
def test_delitem_unknown_raises(self, record):
"""Test that __delitem__ raises KeyError for unknown keys."""
with pytest.raises(KeyError):
del record["nonexistent"]
def test_attribute_get_existing_measurement(self, record):
"""Test accessing an existing measurement via attribute."""
assert record.dish_washer_mr == 123.0
def test_attribute_get_missing_measurement(self, record):
"""Test accessing a missing but known measurement returns None."""
assert record.temp is None
def test_attribute_get_invalid_raises(self, record):
"""Test accessing an unknown attribute raises AttributeError."""
with pytest.raises(AttributeError):
_ = record.nonexistent
def test_attribute_set_existing_measurement(self, record):
"""Test setting a known measurement key via attribute."""
record.temp = 99.9
assert record["temp"] == 99.9
def test_attribute_set_invalid_raises(self, record):
"""Test setting an unknown attribute raises AttributeError."""
with pytest.raises(AttributeError):
record.invalid = 123
def test_delattr_measurement(self, record):
"""Test deleting a known measurement key via attribute."""
record.temp = 88.0
del record.temp
assert record.temp is None
def test_delattr_ignored_missing_measurement_key(self, record):
"""Test deleting a known measurement key that was never set is a no-op."""
del record.temp
assert record.temp is None
def test_len_and_iter(self, record):
"""Test that __len__ and __iter__ behave as expected."""
keys = list(iter(record))
assert set(record.record_keys_writable()) == set(keys)
assert len(record) == len(keys)
def test_hasattr_behavior(self, record):
"""Test that hasattr returns True for fields and known measurements."""
assert hasattr(record, "date_time")
assert hasattr(record, "dish_washer_mr")
assert hasattr(record, "temp") # allowed, even if not yet set
assert not hasattr(record, "nonexistent")
def test_model_validate_roundtrip(self, record):
"""Test that MeasurementDataRecord can be serialized and revalidated."""
dumped = record.model_dump()
restored = MeasurementDataRecord.model_validate(dumped)
assert restored.dish_washer_mr == 123.0
assert restored.solar_power == 456.0
assert restored.temp is None # not set
def test_copy_preserves_measurements(self, record):
"""Test that copying preserves measurement values."""
record.temp = 22.2
copied = record.model_copy()
assert copied.dish_washer_mr == 123.0
assert copied.temp == 22.2
assert copied is not record
def test_inequality_differs_with_measurements(self, record):
"""Test that records with different measurements are not equal."""
other = record.model_copy(deep=True)
# Modify one measurement value in the copy
other["dish_washer_mr"] = 999.9
assert record != other
def test_in_operator_for_measurements_and_fields(self, record):
"""Ensure 'in' works for both fields and configured measurement keys."""
assert "dish_washer_mr" in record
assert "solar_power" in record
assert "date_time" in record # standard field
assert "temp" in record # allowed but not yet set
assert "unknown" not in record
def test_dir_includes_measurement_keys(self, record):
"""`dir(record)` should include measurement keys for introspection.
It shall not include the internal 'measurements' attribute.
"""
keys = dir(record)
assert "measurements" not in keys
for key in record.config.measurement.keys:
assert key in keys
@pytest.mark.asyncio
class TestMeasurement:
"""Test suite for the Measuremen class."""
@pytest_asyncio.fixture
async def measurement_eos(self, config_eos):
"""Fixture to create a Measurement instance."""
# Load meter readings are in kWh
config_eos.measurement.load_emr_keys = ["load0_mr", "load1_mr", "load2_mr", "load3_mr"]
measurement = get_measurement()
await measurement.delete_by_datetime(None, None)
# Warn-once state lives on the shared singleton; start each test fresh.
measurement._reported_warnings.clear()
record0 = MeasurementDataRecord(
date_time=datetime(2023, 1, 1, hour=0),
load0_mr=100,
load1_mr=200,
)
assert record0.load0_mr == 100
assert record0.load1_mr == 200
records = [
MeasurementDataRecord(
date_time=to_datetime("2023-01-01T00:00:00"),
load0_mr=100,
load1_mr=200,
),
MeasurementDataRecord(
date_time=to_datetime("2023-01-01T01:00:00"),
load0_mr=150,
load1_mr=250,
),
MeasurementDataRecord(
date_time=to_datetime("2023-01-01T02:00:00"),
load0_mr=200,
load1_mr=300,
),
MeasurementDataRecord(
date_time=to_datetime("2023-01-01T03:00:00"),
load0_mr=250,
load1_mr=350,
),
MeasurementDataRecord(
date_time=to_datetime("2023-01-01T04:00:00"),
load0_mr=300,
load1_mr=400,
),
MeasurementDataRecord(
date_time=to_datetime("2023-01-01T05:00:00"),
load0_mr=350,
load1_mr=450,
),
]
for record in records:
await measurement.insert_by_datetime(record)
return measurement
async def test_interval_count(self, measurement_eos):
"""Test interval count calculation."""
start = to_datetime("2023-01-01T00:00:00")
end = to_datetime("2023-01-01T03:00:00")
interval = duration(hours=1)
assert measurement_eos._interval_count(start, end, interval) == 3
async def test_interval_count_invalid_end_before_start(self, measurement_eos):
"""Test interval count raises ValueError when end_datetime is before start_datetime."""
start = to_datetime("2023-01-01T03:00:00")
end = to_datetime("2023-01-01T00:00:00")
interval = duration(hours=1)
with pytest.raises(ValueError, match="end_datetime must be after start_datetime"):
measurement_eos._interval_count(start, end, interval)
async def test_interval_count_invalid_non_positive_interval(self, measurement_eos):
"""Test interval count raises ValueError when interval is non-positive."""
start = to_datetime("2023-01-01T00:00:00")
end = to_datetime("2023-01-01T03:00:00")
with pytest.raises(ValueError, match="interval must be positive"):
measurement_eos._interval_count(start, end, duration(hours=0))
async def test_meter_energy_kwh_valid_input(self, measurement_eos):
"""Energy per interval is the difference of the readings at its boundaries."""
result = await measurement_eos.meter_energy_kwh(
["load0_mr", "load1_mr"],
to_datetime("2023-01-01T00:00:00"),
to_datetime("2023-01-01T05:00:00"),
to_duration("1 hour"),
)
np.testing.assert_array_equal(result["load0_mr"], [50, 50, 50, 50, 50])
np.testing.assert_array_equal(result["load1_mr"], [50, 50, 50, 50, 50])
async def test_meter_energy_kwh_interpolates_a_missing_reading(self, measurement_eos):
"""A reading missing at an interval boundary is interpolated from its neighbours."""
start_datetime = to_datetime("2023-01-01T00:00:00")
record = await measurement_eos.get_by_datetime(to_datetime("2023-01-01T05:00:00"))
assert record is not None
await measurement_eos.delete_by_datetime(
start_datetime=to_datetime("2023-01-01T05:00:00"),
end_datetime=to_datetime("2023-01-01T06:00:00"),
)
record.date_time = to_datetime("2023-01-01T06:00:00")
record.load1_mr = 500
await measurement_eos.insert_by_datetime(record)
result = await measurement_eos.meter_energy_kwh(
["load1_mr"], start_datetime, to_datetime("2023-01-01T06:00:00"), to_duration("1 hour")
)
np.testing.assert_array_equal(result["load1_mr"], [50.0, 50.0, 50.0, 50.0, 50.0, 50.0])
async def test_meter_energy_kwh_is_nan_outside_the_readings(self, measurement_eos):
"""Intervals before the first or after the last reading are unknown."""
result = await measurement_eos.meter_energy_kwh(
["load0_mr", "load2_mr"],
to_datetime("2022-12-31T23:00:00"),
to_datetime("2023-01-01T07:00:00"),
to_duration("1 hour"),
)
np.testing.assert_array_equal(
result["load0_mr"], [np.nan, 50, 50, 50, 50, 50, np.nan, np.nan]
)
assert np.isnan(result["load2_mr"]).all()
async def test_meter_energy_kwh_extends_a_partial_last_interval(self, measurement_eos):
"""A period that ends inside an interval still yields that full interval."""
result = await measurement_eos.meter_energy_kwh(
["load0_mr"],
to_datetime("2023-01-01T00:00:00"),
to_datetime("2023-01-01T02:20:00"),
to_duration("1 hour"),
)
np.testing.assert_array_equal(result["load0_mr"], [50, 50, 50])
async def test_meter_energy_kwh_negative_interval(self, measurement_eos):
"""A non-positive interval is rejected."""
with pytest.raises(ValueError, match="positive whole number of seconds"):
await measurement_eos.meter_energy_kwh(
["load0_mr"],
to_datetime("2023-01-01T00:00:00"),
to_datetime("2023-01-01T05:00:00"),
to_duration(-3600),
)
async def test_keys_first_and_last_datetime(self, measurement_eos):
"""First and last valid reading per key, each key on its own.
load1_mr reports two days longer than load0_mr, so the backward scan finds the
two last readings in different windows; a trailing non-finite value of
load0_mr is no reading.
"""
for hour in range(6, 54):
await measurement_eos.update_value(
to_datetime("2023-01-01T00:00:00").add(hours=hour), "load1_mr", 450 + hour
)
await measurement_eos.update_value(
to_datetime("2023-01-03T12:00:00"), "load0_mr", float("nan")
)
keys = ["load0_mr", "load1_mr", "load1_mr", "load2_mr"]
firsts = await measurement_eos.keys_first_datetime(keys)
lasts = await measurement_eos.keys_last_datetime(keys)
assert firsts == {
"load0_mr": to_datetime("2023-01-01T00:00:00"),
"load1_mr": to_datetime("2023-01-01T00:00:00"),
}
assert lasts == {
"load0_mr": to_datetime("2023-01-01T05:00:00"),
"load1_mr": to_datetime("2023-01-03T05:00:00"),
}
timezone = measurement_eos.config.general.timezone
assert all(stamp.timezone_name == timezone for stamp in [*firsts.values(), *lasts.values()])
async def test_conversion_failure_is_logged_once_per_streak(self, measurement_eos, caplog):
"""Error on the first failure, debug while it persists, error again after a success."""
def levels() -> set[str]:
levels = {r.levelname for r in caplog.records if "conversion failed" in r.getMessage()}
caplog.clear()
return levels
with caplog.at_level("DEBUG"):
measurement_eos.report_conversion_failure("consumer", "consumer: conversion failed")
assert levels() == {"ERROR"}
measurement_eos.report_conversion_failure("consumer", "consumer: conversion failed")
assert levels() == {"DEBUG"}
# Each consumer has its own streak.
measurement_eos.report_conversion_failure("other", "other: conversion failed")
assert levels() == {"ERROR"}
measurement_eos.clear_conversion_failure("consumer")
measurement_eos.report_conversion_failure("consumer", "consumer: conversion failed")
assert levels() == {"ERROR"}
async def test_keys_valid_datetimes(self, measurement_eos):
"""Stamps of valid readings in [start, end): invalid quality does not count."""
stamp = to_datetime("2023-01-01T02:00:00")
record = await measurement_eos.db_get_record(DatabaseTimestamp.from_datetime(stamp))
record.sample_quality["load0_mr"] = SampleQuality(status="invalid")
await measurement_eos.db_mark_dirty_record(record)
stamps = await measurement_eos.keys_valid_datetimes(
["load0_mr", "load_silent_mr"],
to_datetime("2023-01-01T01:00:00"),
to_datetime("2023-01-01T04:00:00"),
)
assert stamps == {
"load0_mr": [to_datetime("2023-01-01T01:00:00"), to_datetime("2023-01-01T03:00:00")],
"load_silent_mr": [],
}
async def test_load_total_kwh_warns_once_about_a_silent_meter(self, measurement_eos, caplog):
"""A configured meter that never reports is a warning once, not on every run."""
measurement_eos.config.measurement.load_emr_keys = ["load0_mr", "load_silent_mr"]
period = {
"start_datetime": to_datetime("2023-01-01T00:00:00"),
"end_datetime": to_datetime("2023-01-01T03:00:00"),
"interval": to_duration("1 hour"),
}
def silent_meter_warnings() -> int:
return sum(
record.levelname == "WARNING"
and "'load_silent_mr' gives no usable energy" in record.getMessage()
for record in caplog.records
)
with caplog.at_level("WARNING"):
await measurement_eos.load_total_kwh(**period)
first_run = silent_meter_warnings()
await measurement_eos.load_total_kwh(**period)
assert first_run > 0
assert silent_meter_warnings() == first_run
async def test_load_total_kwh_empty_store_without_period(self, measurement_eos):
"""No data and no period yields an empty result, not an error."""
await measurement_eos.delete_by_datetime(None, None)
result = await measurement_eos.load_total_kwh()
assert result.shape == (0,)
async def test_load_total_kwh(self, measurement_eos):
"""Test total load calculation."""
# Only these meters report; a silent configured meter makes the total unknown.
measurement_eos.config.measurement.load_emr_keys = ["load0_mr", "load1_mr"]
start_datetime = to_datetime("2023-01-01T03:00:00")
end_datetime = to_datetime("2023-01-01T05:00:00")
interval = duration(hours=1)
result = await measurement_eos.load_total_kwh(start_datetime=start_datetime, end_datetime=end_datetime, interval=interval)
# Expected total load per interval
expected = np.array([100, 100]) # Differences between consecutive meter readings
np.testing.assert_array_equal(result, expected)
async def test_load_total_kwh_no_data(self, measurement_eos):
"""Test total load calculation with no data."""
measurement_eos.records = []
start_datetime = to_datetime("2023-01-01T00:00:00")
end_datetime = to_datetime("2023-01-01T03:00:00")
interval = duration(hours=1)
result = await measurement_eos.load_total_kwh(start_datetime=start_datetime, end_datetime=end_datetime, interval=interval)
# No data: the load of every interval is unknown, not zero.
assert result.shape == (3,)
assert np.isnan(result).all()
async def test_load_total_kwh_partial_intervals(self, measurement_eos):
"""Test total load calculation with partial intervals."""
measurement_eos.config.measurement.load_emr_keys = ["load0_mr", "load1_mr"]
start_datetime = to_datetime("2023-01-01T00:30:00") # Start in the middle of an interval
end_datetime = to_datetime("2023-01-01T01:30:00") # End in the middle of another interval
interval = duration(hours=1)
result = await measurement_eos.load_total_kwh(start_datetime=start_datetime, end_datetime=end_datetime, interval=interval)
expected = np.array([100]) # Only one complete interval covered
np.testing.assert_array_equal(result, expected)
async def test_load_total_kwh_follows_a_jittered_meter(self, measurement_eos):
"""Hourly load energy is exact for a meter reporting at arbitrary stamps.
The meter reports every ~5 minutes off the hour. Load is 1 kW until noon and
3 kW afterwards; each hour must get exactly its own energy, also around the step.
"""
measurement_eos.config.measurement.load_emr_keys = ["load_jitter_mr"]
start = to_datetime("2023-02-01T00:00:00Z")
jitter = [0, 21, 47, 13, 34]
stamp = to_datetime("2023-01-31T23:57:10Z")
energy_kwh = 0.0
step = 0
while compare_datetimes(stamp, to_datetime("2023-02-02T00:15:00Z")).lt:
await measurement_eos.update_value(stamp, "load_jitter_mr", round(energy_kwh, 6))
following = stamp.add(minutes=5, seconds=jitter[step % len(jitter)])
noon = to_datetime("2023-02-01T12:00:00Z")
seconds_before_noon = max(0.0, min(following.timestamp(), noon.timestamp()) - stamp.timestamp())
seconds_after_noon = (following.timestamp() - stamp.timestamp()) - seconds_before_noon
energy_kwh += (1.0 * seconds_before_noon + 3.0 * seconds_after_noon) / 3600.0
stamp = following
step += 1
result = await measurement_eos.load_total_kwh(
start_datetime=start, end_datetime=start.add(days=1), interval=to_duration("1 hour")
)
# Away from the step every hour is exact. The step lies inside one ~5-minute
# reading interval, which a meter cannot resolve: hours 11 and 12 share it, but
# keep their sum (a bucket-mean conversion moves about half an hour across).
np.testing.assert_allclose(result[:11], 1.0, atol=1e-5)
np.testing.assert_allclose(result[13:], 3.0, atol=1e-5)
assert result[11] == pytest.approx(1.0, abs=0.05)
assert result[12] == pytest.approx(3.0, abs=0.05)
assert result[11] + result[12] == pytest.approx(4.0, abs=1e-5)
async def test_load_total_kwh_is_nan_without_full_coverage(self, measurement_eos):
"""An hour a load meter does not fully cover is unknown, not zero load."""
result = await measurement_eos.load_total_kwh(
start_datetime=to_datetime("2023-01-01T03:00:00"),
end_datetime=to_datetime("2023-01-01T07:00:00"),
interval=to_duration("1 hour"),
)
# load2_mr and load3_mr are configured but never report.
assert np.isnan(result).all()
measurement_eos.config.measurement.load_emr_keys = ["load0_mr", "load1_mr"]
result = await measurement_eos.load_total_kwh(
start_datetime=to_datetime("2023-01-01T03:00:00"),
end_datetime=to_datetime("2023-01-01T07:00:00"),
interval=to_duration("1 hour"),
)
np.testing.assert_array_equal(result, [100.0, 100.0, np.nan, np.nan])
class TestMeasurementFileRestore:
@pytest.fixture
def file_measurements(self, config_eos, tmp_path, monkeypatch):
measurement = get_measurement()
config_eos.measurement.load_emr_keys = ["meter"]
config_eos.general.data_folder_path = tmp_path
config_eos.database.provider = None
measurement._db_reset_state()
monkeypatch.setattr(DataSequence, "save", AsyncMock(return_value=False))
monkeypatch.setattr(DataSequence, "load", AsyncMock(return_value=False))
try:
yield measurement
finally:
measurement._db_reset_state()
@pytest.mark.asyncio
async def test_json_roundtrip_restores_records_into_existing_singleton(self, file_measurements):
measurement = file_measurements
await measurement.update_value(to_datetime("2026-09-16T08:00:00Z"), "meter", 123.5)
await measurement.update_value("2026-09-16T09:00:00Z", "meter", 124.0)
assert await measurement.save()
measurement._db_reset_state()
assert await measurement.load()
assert get_measurement() is measurement
assert [record["meter"] for record in measurement.records] == [123.5, 124.0]
restored_hours = []
for record in measurement.records:
assert record.date_time is not None
restored_hours.append(record.date_time.in_timezone("UTC").hour)
assert restored_hours == [8, 9]
# Reloading must update matching timestamps, without duplicating them.
assert await measurement.load()
assert len(measurement.records) == 2
@pytest.mark.asyncio
async def test_json_restore_preserves_other_in_memory_timestamps(self, file_measurements):
measurement = file_measurements
await measurement.update_value("2026-09-16T08:00:00Z", "meter", 123.5)
assert await measurement.save()
measurement._db_reset_state()
await measurement.update_value("2026-09-16T09:00:00Z", "meter", 124.0)
assert await measurement.load()
assert [record["meter"] for record in measurement.records] == [123.5, 124.0]
@pytest.mark.asyncio
@pytest.mark.parametrize("payload", [
"invalid json",
json.dumps({"records": [
{"date_time": "2026-09-16T08:00:00Z", "meter": 123.5},
{"date_time": "not a date", "meter": 124.0},
]}),
])
async def test_invalid_json_does_not_partially_restore(self, file_measurements, payload):
measurement = file_measurements
measurement._measurement_file_path().write_text(payload, encoding="utf-8")
assert await measurement.load() is False
assert measurement.records == []
@pytest.mark.asyncio
async def test_database_success_does_not_read_json(self, file_measurements, monkeypatch):
measurement = file_measurements
measurement._measurement_file_path().write_text("invalid json", encoding="utf-8")
monkeypatch.setattr(DataSequence, "load", AsyncMock(return_value=True))
assert await measurement.load()
@pytest.mark.asyncio
async def test_missing_json_reports_not_loaded(self, file_measurements):
assert await file_measurements.load() is False
CHANNELS = {
"house_power": dict(quantity="power", unit="W", integration_method="hold", max_gap_seconds=120),
"house_meter": dict(quantity="cumulative_energy", unit="kWh"),
"house_interval": dict(
quantity="interval_energy", unit="Wh", interval_seconds=900, timestamp_reference="start"
),
}
class TestMeasurementChannels:
@pytest.mark.parametrize(
"definition",
[
dict(quantity="power", unit="kWh", integration_method="hold", max_gap_seconds=60),
dict(quantity="power", unit="W"),
dict(quantity="power", unit="W", integration_method="hold", max_gap_seconds=0),
dict(quantity="cumulative_energy", unit="W"),
dict(quantity="cumulative_energy", unit="kWh", timestamp_reference="end"),
dict(quantity="interval_energy", unit="Wh", interval_seconds=900),
dict(
quantity="interval_energy", unit="Wh", interval_seconds=True, timestamp_reference="end"
),
],
)
def test_reject_ambiguous_channel(self, definition):
with pytest.raises(ValidationError):
MeasurementChannelSettings(**definition)
@pytest.mark.parametrize(
"legacy_field",
["load_emr_keys", "grid_import_emr_keys", "grid_export_emr_keys", "pv_production_emr_keys"],
)
def test_legacy_keys_keep_meter_semantics(self, legacy_field):
settings = MeasurementCommonSettings.model_validate(dict(**{legacy_field: ["legacy"]}, channels=CHANNELS))
assert settings.keys == sorted(["legacy", *CHANNELS])
compatible = MeasurementCommonSettings.model_validate(dict(
**{legacy_field: ["legacy"]}, channels={"legacy": CHANNELS["house_meter"]}
))
assert compatible.keys == ["legacy"]
with pytest.raises(ValidationError, match="must remain"):
MeasurementCommonSettings.model_validate(dict(
**{legacy_field: ["legacy"]}, channels={"legacy": CHANNELS["house_power"]}
))
@pytest.mark.parametrize("key", ["", " x", "date_time", "configured_data", "keys", "_private"])
def test_reject_reserved_key(self, key):
with pytest.raises(ValidationError):
MeasurementCommonSettings.model_validate(dict(channels={key: CHANNELS["house_meter"]}))
@pytest.mark.asyncio
async def test_existing_import_and_file_reload(self, config_eos, tmp_path, monkeypatch):
"""All three quantities retain their raw values through the existing file path."""
measurement = get_measurement()
previous_settings = config_eos.measurement
previous_records = measurement.records
previous_folder = config_eos.general.data_folder_path
try:
config_eos.measurement = MeasurementCommonSettings.model_validate(dict(channels=CHANNELS))
config_eos.general.data_folder_path = tmp_path
measurement._db_reset_state()
values = dict(house_power=800.0, house_meter=12345.6, house_interval=200.0)
for key, value in values.items():
(await measurement.update_value(to_datetime("2026-09-10T18:00:00Z"), key, value))
assert set(values).issubset(measurement.record_keys)
monkeypatch.setattr(DataSequence, "save", AsyncMock(return_value=False))
monkeypatch.setattr(DataSequence, "load", AsyncMock(return_value=False))
assert (await measurement.save())
measurement._db_reset_state()
assert (await measurement.load())
assert len(measurement.records) == 1
for key, value in values.items():
assert measurement.records[0][key] == value
restored = MeasurementDataRecord.model_validate_json(
measurement.records[0].model_dump_json()
)
assert restored.configured_data == values
settings = MeasurementCommonSettings.model_validate_json(
config_eos.measurement.model_dump_json()
)
assert settings.model_dump() == config_eos.measurement.model_dump()
finally:
measurement._db_reset_state()
measurement.records = previous_records
config_eos.measurement = previous_settings
config_eos.general.data_folder_path = previous_folder
@pytest.mark.asyncio
class TestMeasurementCommonPeriod:
"""Common period of a meter group and its warnings."""
@pytest_asyncio.fixture
async def measurement(self, config_eos):
# Configured meter keys are writable record keys of the store.
config_eos.measurement.load_emr_keys = ["meter_a_mr", "meter_b_mr"]
measurement = get_measurement()
await measurement.delete_by_datetime(None, None)
measurement._reported_warnings.clear()
yield measurement
await measurement.delete_by_datetime(None, None)
measurement._reported_warnings.clear()
@staticmethod
def warnings(caplog, text: str) -> int:
return sum(
record.levelname == "WARNING" and text in record.getMessage()
for record in caplog.records
)
async def test_silent_group_is_warned_again_after_it_reported(self, measurement, caplog):
keys = ["meter_a_mr", "meter_b_mr"]
start = to_datetime("2024-01-01T00:00:00Z")
with caplog.at_level("WARNING"):
assert await measurement.keys_common_period(keys, "test") is None
first = self.warnings(caplog, "have no valid readings")
for hour in range(3):
for key in keys:
await measurement.update_value(start.add(hours=hour), key, 10.0 + hour)
assert await measurement.keys_common_period(keys, "test") is not None
await measurement.delete_by_datetime(None, None)
assert await measurement.keys_common_period(keys, "test") is None
assert first > 0
assert self.warnings(caplog, "have no valid readings") > first
async def test_single_reading_is_no_replaced_meter(self, measurement, caplog):
await measurement.update_value(to_datetime("2024-01-01T00:00:00Z"), "meter_a_mr", 10.0)
with caplog.at_level("WARNING"):
assert await measurement.keys_common_period(["meter_a_mr"], "test") is None
assert self.warnings(caplog, "share no period") == 0
async def test_touching_replacement_is_a_replaced_meter(self, measurement, caplog):
"""A swap where the new meter starts at the old meter's last stamp is named."""
start = to_datetime("2024-01-01T00:00:00Z")
for hour in range(4):
await measurement.update_value(start.add(hours=hour), "meter_a_mr", 10.0 + hour)
await measurement.update_value(start.add(hours=3 + hour), "meter_b_mr", 50.0 + hour)
with caplog.at_level("WARNING"):
assert await measurement.keys_common_period(["meter_a_mr", "meter_b_mr"], "test") is None
assert self.warnings(caplog, "meter 'meter_a_mr' last reported at") > 0