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 # ----------------------------------------------------------------------