From e2726354c2802709d25db6c24d034f608121099a Mon Sep 17 00:00:00 2001 From: Christin Date: Wed, 18 Nov 2026 14:11:29 +0100 Subject: [PATCH] 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 Co-Authored-By: Claude Fable 5.2 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) --- ai/skills/testing/SKILL.md | 4 ++ tests/test_database.py | 35 ++------------ tests/test_devicesprofilestore.py | 4 ++ tests/test_devicessettingsbattery.py | 10 +++- tests/test_elecpriceenergycharts.py | 6 ++- tests/test_eosdashserver.py | 2 + tests/test_geneticoptimize.py | 4 +- tests/test_predictionabc.py | 12 +++-- tests/test_server.py | 68 ++++++++++++++++++++++------ tests/test_system.py | 16 ++++--- 10 files changed, 99 insertions(+), 62 deletions(-) diff --git a/ai/skills/testing/SKILL.md b/ai/skills/testing/SKILL.md index 2d4d746c..c8d40ada 100644 --- a/ai/skills/testing/SKILL.md +++ b/ai/skills/testing/SKILL.md @@ -20,6 +20,10 @@ description: Use when adding or updating pytest tests, fixing bugs, or changing - Prefer deterministic, isolated tests; mock external services/devices. - Cover boundary conditions and error paths. - Do not weaken tests to accommodate implementation defects. +- Keep each test case well under a second. No real-time sleeps or wait loops + (use synthetic timestamps), no full cartesian `parametrize` over independent + axes, and extend an existing parametrized test before writing a new one. + The CI log lists the 25 slowest tests (`--durations=25`). ## Verify diff --git a/tests/test_database.py b/tests/test_database.py index 853d12fe..7cfb258c 100644 --- a/tests/test_database.py +++ b/tests/test_database.py @@ -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 diff --git a/tests/test_devicesprofilestore.py b/tests/test_devicesprofilestore.py index b0d34bc7..2d8121eb 100644 --- a/tests/test_devicesprofilestore.py +++ b/tests/test_devicesprofilestore.py @@ -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) diff --git a/tests/test_devicessettingsbattery.py b/tests/test_devicessettingsbattery.py index 4e6bfd59..106d8b73 100644 --- a/tests/test_devicessettingsbattery.py +++ b/tests/test_devicessettingsbattery.py @@ -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 diff --git a/tests/test_elecpriceenergycharts.py b/tests/test_elecpriceenergycharts.py index 5e90988f..2b47b995 100644 --- a/tests/test_elecpriceenergycharts.py +++ b/tests/test_elecpriceenergycharts.py @@ -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") diff --git a/tests/test_eosdashserver.py b/tests/test_eosdashserver.py index 66400675..81e4b213 100644 --- a/tests/test_eosdashserver.py +++ b/tests/test_eosdashserver.py @@ -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 diff --git a/tests/test_geneticoptimize.py b/tests/test_geneticoptimize.py index 26ff1647..2785f168 100644 --- a/tests/test_geneticoptimize.py +++ b/tests/test_geneticoptimize.py @@ -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), ], diff --git a/tests/test_predictionabc.py b/tests/test_predictionabc.py index 82c06b66..6f339e85 100644 --- a/tests/test_predictionabc.py +++ b/tests/test_predictionabc.py @@ -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), diff --git a/tests/test_server.py b/tests/test_server.py index 4b14bc56..ec9d8f9a 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -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 diff --git a/tests/test_system.py b/tests/test_system.py index f8581726..99bacab4 100644 --- a/tests/test_system.py +++ b/tests/test_system.py @@ -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 # ----------------------------------------------------------------------