mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2026-11-25 15:06:20 +01:00
test: make slow and order-dependent tests fast and independent
Slow tests: - TestPerformance inserted 10 000 records three times per backend. One test per backend now times insert, save and load on the same records, with the same assertions. - test_measurement_realtime_stream slept one second per update, 20 s per backend. The updates use synthetic timestamps one second apart in the recent past, without a pause, and send the same duplicates, out-of-order and burst writes. - test_readers_never_see_a_partial_document: the readers spun on the cache and kept the writer waiting for the GIL (~50 s). They now yield with time.sleep(0) after each lookup (~0.5 s); a non-atomic save still fails the test 10 of 10 times. - test_devicessettingsbattery.py compiled the same plain profile before each of its 235 tests. A module-scoped fixture compiles it once; a compiled profile is frozen and may be shared (20.8 s -> 9.4 s). - The --finalize case of test_geneticoptimize.py runs 250 instead of 400 generations. For this input and seed the best fitness is final in generation 213, and the solutions after 250 and 400 generations are identical field by field. The test checks the keys and the consistency of the result, not the schedule, so it detects the same as before (127 s -> 80 s on GitHub runners). test_genetic0optimize.py keeps 400. Tests that depended on another test of the same process, found by running them in another order and under pytest-xdist: - TestPredictionContainer::test_len relied on a class flag that a TestPredictionProvider fixture set and never reset. Both fixtures now set the flags with monkeypatch. - The EnergyCharts status code test got a cached response from an earlier test; it now calls _request_forecast(force_update=True) and asserts that the request was made. - test_ingress_safe_links did not wait for EOSdash, which EOS starts after its own startup. - test_forward_stream_truncates_very_long_line found the log queue left behind by test_server_start_eosdash (no worker, closed event loop). It installs its own queue now, and test_server_start_eosdash no longer leaves its queue behind. Dropping lines from a full queue was only covered through that left-over queue and gets a test of its own. Refs #1553 Co-authored-by: SchaafAlexander <86607129+SchaafAlexander@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Signed-off-by: SchaafAlexander <86607129+SchaafAlexander@users.noreply.github.com> Assisted-by: Claude Code (claude-opus-5-5) Assisted-by: Claude Code (claude-fable-5-2)
This commit is contained in:
committed by
Bobby Noelte
co-authored by
SchaafAlexander
Claude Opus 5.5
parent
ce7fb96faf
commit
e2726354c2
+4
-31
@@ -834,7 +834,8 @@ class TestIntegration:
|
||||
class TestPerformance:
|
||||
"""Throughput benchmarks — not correctness tests."""
|
||||
|
||||
async def test_insert_throughput(self, config_eos, async_database_instance):
|
||||
async def test_insert_save_load_throughput(self, config_eos, async_database_instance):
|
||||
"""Insert, save and load the same records; each phase is timed on its own."""
|
||||
sequence = SampleDataSequence()
|
||||
await _reset_sequence_state(sequence)
|
||||
base_time = to_datetime("2024-01-01T00:00:00Z")
|
||||
@@ -854,42 +855,14 @@ class TestPerformance:
|
||||
|
||||
assert len(sequence.records) == n
|
||||
|
||||
async def test_save_throughput(self, config_eos, async_database_instance):
|
||||
sequence = SampleDataSequence()
|
||||
await _reset_sequence_state(sequence)
|
||||
base_time = to_datetime("2024-01-01T00:00:00Z")
|
||||
n = 10_000
|
||||
|
||||
for i in range(n):
|
||||
await sequence.db_insert_record(
|
||||
SampleDataRecord(
|
||||
date_time=base_time.add(minutes=i),
|
||||
temperature=20.0 + (i % 100) * 0.1,
|
||||
)
|
||||
)
|
||||
|
||||
start = time.perf_counter()
|
||||
saved = await sequence.db_save_records()
|
||||
save_duration = time.perf_counter() - start
|
||||
|
||||
assert saved == n
|
||||
print(f"\nSaved {n} records in {save_duration:.2f}s "
|
||||
print(f"Saved {n} records in {save_duration:.2f}s "
|
||||
f"({n / save_duration:.0f} rec/s)")
|
||||
|
||||
async def test_load_throughput(self, config_eos, async_database_instance):
|
||||
sequence = SampleDataSequence()
|
||||
await _reset_sequence_state(sequence)
|
||||
base_time = to_datetime("2024-01-01T00:00:00Z")
|
||||
n = 10_000
|
||||
|
||||
for i in range(n):
|
||||
await sequence.db_insert_record(
|
||||
SampleDataRecord(
|
||||
date_time=base_time.add(minutes=i),
|
||||
temperature=20.0 + (i % 100) * 0.1,
|
||||
)
|
||||
)
|
||||
await sequence.db_save_records()
|
||||
await _reset_sequence_state(sequence)
|
||||
|
||||
start = time.perf_counter()
|
||||
@@ -897,7 +870,7 @@ class TestPerformance:
|
||||
load_duration = time.perf_counter() - start
|
||||
|
||||
assert loaded == n
|
||||
print(f"\nLoaded {n} records in {load_duration:.2f}s "
|
||||
print(f"Loaded {n} records in {load_duration:.2f}s "
|
||||
f"({n / load_duration:.0f} rec/s)")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -413,6 +413,10 @@ class TestConcurrency:
|
||||
except BaseException as exc: # noqa: BLE001 - collect for the assertion
|
||||
errors.append(exc)
|
||||
return
|
||||
# Give up the GIL after each lookup. Cached lookups never block, so four
|
||||
# spinning readers kept the writer waiting for the GIL after every file
|
||||
# operation (~50 s instead of ~0.5 s). A non-atomic save is still caught.
|
||||
time.sleep(0)
|
||||
|
||||
threads = [threading.Thread(target=write)] + [
|
||||
threading.Thread(target=read) for _ in range(4)
|
||||
|
||||
@@ -276,10 +276,16 @@ def broken_profile_loader(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(get_profile_store(), "get", missing)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def _plain_profile() -> BatteryProfile:
|
||||
"""Compile the plain profile once; a compiled profile is frozen and may be shared."""
|
||||
return make_profile()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _plain_default_profile(install_profile) -> None:
|
||||
def _plain_default_profile(install_profile, _plain_profile: BatteryProfile) -> None:
|
||||
"""Install the plain profile that settings use unless a test installs another."""
|
||||
install_profile(make_profile())
|
||||
install_profile(_plain_profile)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
@@ -768,11 +768,13 @@ class TestElecPriceEnergyCharts:
|
||||
requests.exceptions.HTTPError if exception else None
|
||||
)
|
||||
mock_get.return_value = mock_response
|
||||
# force_update: bypass the file cache, the request must be made in every case.
|
||||
if exception:
|
||||
with pytest.raises(exception):
|
||||
provider._request_forecast()
|
||||
provider._request_forecast(force_update=True)
|
||||
else:
|
||||
provider._request_forecast()
|
||||
provider._request_forecast(force_update=True)
|
||||
mock_get.assert_called_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch("requests.get")
|
||||
|
||||
@@ -133,6 +133,8 @@ class TestEOSDash:
|
||||
|
||||
def test_ingress_safe_links(self, server_setup_for_class, monkeypatch, tmp_path):
|
||||
base = server_setup_for_class["eosdash_server"]
|
||||
# The fixture waits for EOS only; EOS starts EOSdash after its own startup.
|
||||
self._assert_server_alive(base, server_setup_for_class["timeout"])
|
||||
|
||||
with patch("akkudoktoreos.server.dash.context.ROOT_PATH", "/api/hassio_ingress/TOKEN/"):
|
||||
eos_dir = tmp_path
|
||||
|
||||
@@ -45,7 +45,9 @@ def compare_dict(actual: dict[str, Any], expected: dict[str, Any]):
|
||||
[
|
||||
("optimize_input_1.json", "optimize_result_1.json", 3, 0),
|
||||
("optimize_input_2.json", "optimize_result_2.json", 3, 0),
|
||||
("optimize_input_2.json", "optimize_result_2_full.json", 400, 0),
|
||||
# 250 generations reach the same solution as 400 for this input and seed:
|
||||
# the best fitness no longer changes after generation 213.
|
||||
("optimize_input_2.json", "optimize_result_2_full.json", 250, 0),
|
||||
("optimize_input_1.json", "optimize_result_1_be.json", 3, 1),
|
||||
("optimize_input_2.json", "optimize_result_2_be.json", 3, 1),
|
||||
],
|
||||
|
||||
@@ -132,10 +132,11 @@ class TestPredictionABC:
|
||||
class TestPredictionProvider:
|
||||
# Fixtures and helper functions
|
||||
@pytest.fixture
|
||||
def provider(self):
|
||||
def provider(self, monkeypatch):
|
||||
"""Fixture to provide an instance of TestPredictionProvider for testing."""
|
||||
DerivedPredictionProvider.provider_enabled = True
|
||||
DerivedPredictionProvider.provider_updated = False
|
||||
# monkeypatch restores the class flags, so later tests do not inherit them.
|
||||
monkeypatch.setattr(DerivedPredictionProvider, "provider_enabled", True)
|
||||
monkeypatch.setattr(DerivedPredictionProvider, "provider_updated", False)
|
||||
return DerivedPredictionProvider()
|
||||
|
||||
@pytest.fixture
|
||||
@@ -247,7 +248,10 @@ class TestPredictionContainer:
|
||||
return container
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def container_with_providers(self):
|
||||
async def container_with_providers(self, monkeypatch):
|
||||
# The container only counts enabled providers. Enable it here instead of relying
|
||||
# on a TestPredictionProvider test having run before in the same process.
|
||||
monkeypatch.setattr(DerivedPredictionProvider, "provider_enabled", True)
|
||||
records = [
|
||||
# Test records - include 'prediction_value' key
|
||||
self.create_test_record(datetime(2023, 11, 5), 1),
|
||||
|
||||
+53
-15
@@ -115,21 +115,19 @@ class TestServerStartStop:
|
||||
monkeypatch.setenv("EOS_CONFIG_DIR", str(eos_dir))
|
||||
|
||||
# Import after env vars are set
|
||||
from akkudoktoreos.server.rest import starteosdash
|
||||
from akkudoktoreos.server.rest.starteosdash import (
|
||||
EOSDASH_LOG_MAX_LINE_BYTES,
|
||||
_eosdash_log_worker,
|
||||
eosdash_log_queue,
|
||||
forward_stream,
|
||||
)
|
||||
|
||||
# ---- Ensure queue + worker are initialized ----
|
||||
if eosdash_log_queue is None:
|
||||
from akkudoktoreos.server.rest import starteosdash
|
||||
|
||||
starteosdash.eosdash_log_queue = asyncio.Queue(maxsize=10)
|
||||
worker_task = asyncio.create_task(_eosdash_log_worker())
|
||||
else:
|
||||
worker_task = None
|
||||
# ---- Queue + worker of this test ----
|
||||
# A queue left behind by an earlier test of this process (test_server_start_eosdash)
|
||||
# has no worker and belongs to a closed event loop. monkeypatch restores the value.
|
||||
log_queue: asyncio.Queue = asyncio.Queue(maxsize=10)
|
||||
monkeypatch.setattr(starteosdash, "eosdash_log_queue", log_queue)
|
||||
worker_task = asyncio.create_task(_eosdash_log_worker())
|
||||
|
||||
long_message = "X" * (EOSDASH_LOG_MAX_LINE_BYTES + 10_000)
|
||||
raw_line = f"INFO some.module:123 some_func - {long_message}\n"
|
||||
@@ -157,12 +155,8 @@ class TestServerStartStop:
|
||||
logger.remove(logger_id)
|
||||
|
||||
# Clean shutdown of worker (important for pytest)
|
||||
if worker_task:
|
||||
from akkudoktoreos.server.rest import starteosdash
|
||||
|
||||
if starteosdash.eosdash_log_queue:
|
||||
starteosdash.eosdash_log_queue.put_nowait(None)
|
||||
await worker_task
|
||||
log_queue.put_nowait(None)
|
||||
await worker_task
|
||||
|
||||
# ---- Assert ----
|
||||
assert len(records) == 1, "Expected exactly one log record"
|
||||
@@ -173,6 +167,46 @@ class TestServerStartStop:
|
||||
assert msg.endswith("[TRUNCATED]"), "Expected truncation marker"
|
||||
assert len(msg) <= EOSDASH_LOG_MAX_LINE_BYTES + 20
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_forward_stream_drops_lines_when_queue_is_full(self, monkeypatch, tmp_path):
|
||||
"""Lines that do not fit into the log queue are dropped with a single warning."""
|
||||
|
||||
eos_dir = tmp_path
|
||||
monkeypatch.setenv("EOS_DIR", str(eos_dir))
|
||||
monkeypatch.setenv("EOS_CONFIG_DIR", str(eos_dir))
|
||||
|
||||
# Import after env vars are set
|
||||
from akkudoktoreos.server.rest import starteosdash
|
||||
from akkudoktoreos.server.rest.starteosdash import forward_stream
|
||||
|
||||
# A queue for one entry and no worker: the second and the third line find it full.
|
||||
log_queue: asyncio.Queue = asyncio.Queue(maxsize=1)
|
||||
monkeypatch.setattr(starteosdash, "eosdash_log_queue", log_queue)
|
||||
monkeypatch.setattr(starteosdash, "eosdash_last_drop_warning", float("-inf"))
|
||||
|
||||
reader = asyncio.StreamReader()
|
||||
reader.feed_data(
|
||||
b"INFO | some/module.py:123 | some_func | first\n"
|
||||
b"INFO | some/module.py:124 | some_func | second\n"
|
||||
b"a line without log metadata\n"
|
||||
)
|
||||
reader.feed_eof()
|
||||
|
||||
records = []
|
||||
|
||||
def sink(message):
|
||||
records.append(message.record)
|
||||
|
||||
logger_id = logger.add(sink, level="WARNING")
|
||||
try:
|
||||
await forward_stream(reader)
|
||||
finally:
|
||||
logger.remove(logger_id)
|
||||
|
||||
assert log_queue.qsize() == 1
|
||||
drop_warnings = [record for record in records if "queue full" in record["message"]]
|
||||
assert len(drop_warnings) == 1, "Expected one rate-limited warning for two dropped lines"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_server_start_eosdash(self, config_eos, monkeypatch, tmp_path):
|
||||
"""Test the EOSdash server startup from EOS.
|
||||
@@ -192,6 +226,10 @@ class TestServerStartStop:
|
||||
# Import with environment vars set to prevent creation of EOS.config.json in wrong dir.
|
||||
from akkudoktoreos.server.rest import starteosdash
|
||||
|
||||
# The supervisor creates the log queue in this test's event loop. monkeypatch
|
||||
# removes it again, so no later test of the process finds a queue of a closed loop.
|
||||
monkeypatch.setattr(starteosdash, "eosdash_log_queue", None)
|
||||
|
||||
config_eos.server.host = get_default_host()
|
||||
config_eos.server.port = 8503
|
||||
config_eos.server.eosdash_host = config_eos.server.host
|
||||
|
||||
@@ -653,7 +653,11 @@ class TestSystem:
|
||||
|
||||
@pytest.mark.parametrize("db_provider", ["LMDB", "SQLite", None])
|
||||
def test_measurement_realtime_stream(self, db_provider, server_setup_for_class):
|
||||
"""Simulate real production stream: 1 Hz updates with jitter, duplicates, and out-of-order timestamps."""
|
||||
"""Simulate real production stream: 1 Hz updates with jitter, duplicates, and out-of-order timestamps.
|
||||
|
||||
The 1 Hz timestamps are synthetic (one second apart, in the recent past),
|
||||
so the test does not have to wait a real second between updates.
|
||||
"""
|
||||
|
||||
server = server_setup_for_class["server"]
|
||||
|
||||
@@ -681,13 +685,14 @@ class TestSystem:
|
||||
# ----------------------------------------------------------------------
|
||||
# 2. Real-time simulation
|
||||
# ----------------------------------------------------------------------
|
||||
start = to_datetime().replace(microsecond=0)
|
||||
n_updates = 20
|
||||
start = to_datetime().replace(microsecond=0).subtract(seconds=n_updates + 10)
|
||||
|
||||
sent_timestamps = []
|
||||
errors = []
|
||||
|
||||
for i in range(20): # run ~20 seconds
|
||||
now = to_datetime().replace(microsecond=0)
|
||||
for i in range(n_updates):
|
||||
now = start.add(seconds=i)
|
||||
|
||||
# --- main timestamp ---
|
||||
ts = str(now)
|
||||
@@ -774,9 +779,6 @@ class TestSystem:
|
||||
response = requests.post(f"{server}/v1/admin/database/save")
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
|
||||
# small delay to simulate real system (~1 Hz)
|
||||
time.sleep(1)
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 3. Assertions
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
Reference in New Issue
Block a user