Files
EOS/tests/test_geneticpdfapi.py
T
Bobby NoelteandClaude Opus 5.5 40d0fab9d2 refactor(genetic0): refactor GENETIC0 to consolidated optimizer architecture
Pin the conversion, plan and visualization of golden runs.
Drive GENETIC0 through the optimizer registry.
Move GENETIC0 into one directory with role-named modules.
Prepare every run input once, run from the parameters.
Fall back on bad inputs instead of cancelling the run.
Simulate from frozen device dataclasses, not settings.
Convert and visualize from the parameters and result only.
Serve GENETIC0 from its own router, return a frozen result.

Additional changes
- Fix the run start of the golden runs and add a run across the DST switch.
- Configure a home appliance so the conversion covers it.
- Pass the warm start to the legacy preparation instead of reading the EMS.
- Replace EnergyManagement.genetic0_solution() by optimizer_result(name).
- Cover the warm start of the parameter preparation.
- Rename Genetic0OptimizationParameters to Genetic0Request, Genetic0CommonSettings to Genetic0Settings.
- Say in ADR 0007 and the skill that a move relabels baseline entries one to one.
- Record the renamed OpenAPI schemas in CHANGELOG.md and the upgrade guide.
- Add the observation time to the optimizer interface.
- Cache the load interpolator by its backend instead of in the EMS run cache.
- Add replay files that reproduce each golden result from its parameters.
- Stop writing demo providers, demo devices and defaults into the configuration.
- Count a NaN state of charge as invalid.
- Remove the unused electricity fee check.
- Record the fallbacks in CHANGELOG.md instead of the former demo providers.
- Leave out a battery that is not linked to the inverter.
- Count infinite forecast values as missing.
- Extend a prediction.hours that leaves fewer than two hours after the start hour.
- Do not charge from the grid without any known price.
- Without an inverter, buy the whole load from the grid instead of planning it at no cost.
- Keep the zone of the run start in the replay files.
- Correct the DVhub documentation that said a missing tariff cancels the run.
- Rename the request models to <Name><Thing>Request.
- Move the settings' to_genetic0_*() converters into the preparation.
- Remove the solution's unreachable configuration fallbacks.
- Record the renamed OpenAPI schemas in CHANGELOG.md and the upgrade guide.
- Add EnergyManagement.optimizer_run() and render the PDF from the run's own start.
- Read the presentation series from the earlier of the run's start hours.
- Render the PDF report for runs of any length, not only 48 hours.
- Add the generic OptimizerProblem, rendered like EOSProblem.
- Move Genetic0ParametersBaseModel into genetic0request.py.

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

79 lines
3.3 KiB
Python

"""The report endpoint selects retained results and renders outside the event loop."""
import threading
from io import BytesIO
from pathlib import Path
from types import SimpleNamespace
import pytest
from fastapi.testclient import TestClient
from pypdf import PdfReader
from akkudoktoreos.optimization.genetic import geneticvisualize
from akkudoktoreos.optimization.genetic.geneticsolution import GeneticSolution
from akkudoktoreos.server import eos
from akkudoktoreos.utils.datetimeutil import to_datetime
@pytest.fixture
def retained_result():
path = Path(__file__).parent / "testdata/genetic/optimize_result_1.json"
solution = GeneticSolution.model_validate_json(path.read_text())
solution.start_solution_datetime = to_datetime("2026-09-16T10:00:00+02:00")
return solution
def test_missing_algorithm_report_returns_404(config_eos, monkeypatch):
monkeypatch.setattr(eos, "get_ems", lambda: SimpleNamespace(genetic_solution=lambda: None))
response = TestClient(eos.app).get("/v1/energy-management/optimization/solution/GENETIC/pdf")
assert response.status_code == 404
assert response.headers["content-type"].startswith("application/problem+json")
def test_retained_algorithm_result_renders_real_pdf(config_eos, monkeypatch, retained_result):
solution = retained_result
monkeypatch.setattr(eos, "get_ems", lambda: SimpleNamespace(genetic_solution=lambda: solution))
# A later run and changed configuration must not retime the retained report.
from akkudoktoreos.core.coreabc import get_ems
from akkudoktoreos.optimization.genetic import geneticvisualize
get_ems().set_start_datetime(to_datetime("2027-01-01T00:00:00+01:00"))
config_eos.optimization.genetic.interval_sec = 900
monkeypatch.setattr(
geneticvisualize, "get_ems", lambda: pytest.fail("Report must retain its own time grid")
)
before = solution.model_dump_json()
response = TestClient(eos.app).get("/v1/energy-management/optimization/solution/GENETIC/pdf")
assert response.status_code == 200
assert response.headers["content-type"] == "application/pdf"
assert "genetic" in response.headers["content-disposition"]
assert response.content.startswith(b"%PDF-")
assert len(PdfReader(BytesIO(response.content)).pages) >= 4
assert solution.model_dump_json() == before
@pytest.mark.asyncio
async def test_render_is_offloaded_and_uses_an_owned_copy(config_eos, monkeypatch, retained_result):
solution = retained_result
caller_thread = threading.get_ident()
captured = []
monkeypatch.setattr(
eos,
"get_ems",
lambda: SimpleNamespace(genetic_solution=lambda: solution),
)
original_controls = list(solution.ac_charge)
def render(*, solution):
captured.append((threading.get_ident(), solution))
solution.ac_charge[0] = 0.123
return b"%PDF-isolated-render"
# The PDF stack is imported on first use, so patch it at its source.
monkeypatch.setattr(geneticvisualize, "genetic_prepare_visualize", render)
response = await eos.fastapi_energy_management_optimization_solution_genetic_pdf_get()
assert response.body == b"%PDF-isolated-render"
assert captured[0][0] != caller_thread
assert captured[0][1] is not solution
assert solution.ac_charge == original_controls