diff --git a/Makefile b/Makefile index 32ab851d..596c7cff 100644 --- a/Makefile +++ b/Makefile @@ -98,7 +98,7 @@ clean-bytecode: # Clean target to remove generated documentation and documentation artefacts clean-docs: - @echo "Searching and deleting all '_autosum' directories in docs..." + @echo "Searching and deleting all '_autosummary' directories in docs..." @find docs -type d -name '_autosummary' -exec rm -rf {} +; @echo "Cleaning docs build directories" rm -rf build/docs diff --git a/ai/skills/python-environment/SKILL.md b/ai/skills/python-environment/SKILL.md index 148b93f6..8d3835b5 100644 --- a/ai/skills/python-environment/SKILL.md +++ b/ai/skills/python-environment/SKILL.md @@ -48,6 +48,16 @@ pytest or mypy go missing). - Do not run commands that remove the workspace `.venv`, e.g. `make clean` (`rm -rf build .venv`) or `rm -rf .venv`. +## Running pytest + +- Keep pytest's cache plugin: never pass `-p no:cacheprovider`. The server + tests (pytest-xprocess) keep their processes in the cache; without it the + run stops with a usage error. To skip the server tests, deselect them with + `-m "not eos_server"`. +- Pytest's temporary files go to `TMPDIR`. In the sandbox `/tmp` is a 512 MB + tmpfs that a full run fills: point `TMPDIR` to a directory on disk, e.g. + `TMPDIR="$HOME/.cache/eos-pytest-tmp"`. + ## Verify - `uv run python -c "import sys; print(sys.prefix)"` prints the environment diff --git a/tests/conftest.py b/tests/conftest.py index e2d793f5..8ed3e9f8 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -159,6 +159,63 @@ def mark_server_tests(items: Sequence[pytest.Item]) -> None: item.add_marker(pytest.mark.xdist_group(SERVER_MARKER)) +SERVER_TESTS_NEED_CACHE = ( + "Tests that start an EOS or EOSdash server need the pytest cache (pytest-xprocess keeps its " + "processes there). Run without '-p no:cacheprovider', or deselect them with " + "'-m \"not eos_server\"'." +) + + +def _uses_server_without_cache(config: pytest.Config, item: pytest.Item) -> bool: + """Whether the item starts a server while the pytest cache is disabled.""" + return getattr(config, "cache", None) is None and "xprocess" in getattr( + item, "fixturenames", () + ) + + +def require_cache_for_server_tests(config: pytest.Config, items: Sequence[pytest.Item]) -> None: + """Stop the run if server tests are collected while the pytest cache is disabled. + + pytest-xprocess keeps the server processes in the pytest cache. With ``-p no:cacheprovider`` + every test using the ``xprocess`` fixture errors with ``'Config' object has no attribute + 'cache'``, which reads like an environment problem. A single usage error names the cause + instead. A pytest-xdist worker cannot report a usage error (it ends as an internal error + without the message); there ``fail_server_test_without_cache()`` fails each server test. + + Args: + config: The pytest configuration. + items: The test items left after deselection. + + Raises: + pytest.UsageError: A test uses ``xprocess`` and the cache is disabled. + """ + if hasattr(config, "workerinput"): + return + if any(_uses_server_without_cache(config, item) for item in items): + raise pytest.UsageError(SERVER_TESTS_NEED_CACHE) + + +def fail_server_test_without_cache(config: pytest.Config, item: pytest.Item) -> None: + """Fail a server test at setup while the pytest cache is disabled (pytest-xdist workers). + + Args: + config: The pytest configuration. + item: The test item about to run. + """ + if _uses_server_without_cache(config, item): + pytest.fail(SERVER_TESTS_NEED_CACHE, pytrace=False) + + +def pytest_runtest_setup(item: pytest.Item) -> None: + """Fail server tests that cannot run, with the cause (see ``require_cache_for_server_tests``).""" + fail_server_test_without_cache(item.config, item) + + +def pytest_collection_finish(session: pytest.Session) -> None: + """Check that the server tests left after deselection can run.""" + require_cache_for_server_tests(session.config, session.items) + + @pytest.hookimpl(tryfirst=True) def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item]) -> None: """Mark the server tests, and skip the browser tests unless --browser-test is given. diff --git a/tests/test_docsphinx.py b/tests/test_docsphinx.py index 314f38dd..703103bd 100644 --- a/tests/test_docsphinx.py +++ b/tests/test_docsphinx.py @@ -106,6 +106,23 @@ def sphinx_changed(version_and_hash) -> Optional[str]: return new_hash +def test_cleanup_removes_generated_autosummary(tmp_path: Path) -> None: + """The Sphinx test's cleanup finds the folders Sphinx generates, also nested ones. + + Outside the ``docs`` class, so the unit test run covers it. + """ + stale = tmp_path / "akkudoktoreos" / "_autosummary" + stale.mkdir(parents=True) + (stale / "akkudoktoreos.removed.rst").write_text("stale") + kept = tmp_path / "akkudoktoreos" / "summary.md" + kept.write_text("kept") + + TestSphinxDocumentation._cleanup_autosummary_dirs(tmp_path) + + assert not stale.exists() + assert kept.exists() + + @pytest.mark.docs class TestSphinxDocumentation: """Test class to verify Sphinx documentation generation. @@ -122,9 +139,16 @@ class TestSphinxDocumentation: str(SPHINX_JOBS), ] - def _cleanup_autosum_dirs(self): - """Delete all *_autosum folders inside docs/.""" - for folder in DIR_DOCS.rglob("*_autosum"): + @staticmethod + def _cleanup_autosummary_dirs(docs_dir: Path = DIR_DOCS) -> None: + """Delete all generated ``_autosummary`` folders inside ``docs_dir``. + + Stubs of renamed or removed modules otherwise survive and break the build. + + Args: + docs_dir: The documentation folder. + """ + for folder in list(docs_dir.rglob("_autosummary")): if folder.is_dir(): shutil.rmtree(folder) @@ -147,7 +171,7 @@ class TestSphinxDocumentation: pytest.skip("Skipping Sphinx test — not finalize") # Clean directories - self._cleanup_autosum_dirs() + self._cleanup_autosummary_dirs() self._cleanup_build_dir() # Set environment for sphinx run (sphinx will make eos create a config file) diff --git a/tests/test_geneticbatteryfullcharge.py b/tests/test_geneticbatteryfullcharge.py index 29ecb86b..f8f21873 100644 --- a/tests/test_geneticbatteryfullcharge.py +++ b/tests/test_geneticbatteryfullcharge.py @@ -57,7 +57,7 @@ async def resolve(request: GeneticRequest, warm_start: Any = None) -> GeneticOpt ems_eos = get_ems(init=True) # init once -NOW = to_datetime("2026-11-20T12:00:00+01:00") +NOW = to_datetime("2026-11-20T12:00:00", in_timezone="Europe/Berlin") def _daily(days: int, value: float, now: DateTime = NOW) -> list[tuple[DateTime, Any]]: diff --git a/tests/test_geneticparallelevaluation.py b/tests/test_geneticparallelevaluation.py index 5baaa8d7..2e3fc226 100644 --- a/tests/test_geneticparallelevaluation.py +++ b/tests/test_geneticparallelevaluation.py @@ -45,7 +45,10 @@ HOURS = 24 (2, 4, 1), ], ) -def test_auto_workers_keep_one_core_free(cores, cpu_limit, expected): +def test_auto_workers_keep_one_core_free(monkeypatch, cores, cpu_limit, expected): + # ``cpu_limit=None`` reads the host's cgroup limit; the cases without a limit must not + # depend on the machine the tests run on (a CPU quota in a container or sandbox). + monkeypatch.setattr(genetic_module, "_cgroup_cpu_limit", lambda: None) assert auto_evaluation_workers(cores=cores, cpu_limit=cpu_limit) == expected diff --git a/tests/test_servermarker.py b/tests/test_servermarker.py index 934b0138..d18192b5 100644 --- a/tests/test_servermarker.py +++ b/tests/test_servermarker.py @@ -88,3 +88,36 @@ class TestServerMarker: assert item.get_closest_marker("eos_server") is not None, item.nodeid group = item.get_closest_marker("xdist_group") assert group is not None and group.args == ("eos_server",), item.nodeid + + +def fake_config(**attributes: Any) -> pytest.Config: + """A stand-in for the pytest configuration with the given attributes, e.g. ``cache``.""" + return type("Config", (), attributes)() + + +class TestServerTestsNeedTheCache: + """pytest-xprocess keeps its state in the pytest cache; without it every server test errors.""" + + def test_server_tests_without_cache_stop_the_run(self) -> None: + """``-p no:cacheprovider`` turns into one clear usage error, not 19 cryptic ones.""" + with pytest.raises(pytest.UsageError, match="no:cacheprovider"): + conftest.require_cache_for_server_tests(fake_config(), [FakeItem("xprocess")]) # type: ignore[list-item] + + def test_server_tests_with_cache_run(self) -> None: + """With the cache, server tests run as usual.""" + config = fake_config(cache=object()) + conftest.require_cache_for_server_tests(config, [FakeItem("xprocess")]) # type: ignore[list-item] + conftest.fail_server_test_without_cache(config, FakeItem("xprocess")) # type: ignore[arg-type] + + def test_other_tests_run_without_cache(self) -> None: + """Tests that start no server do not need the cache.""" + config = fake_config() + conftest.require_cache_for_server_tests(config, [FakeItem("tmp_path")]) # type: ignore[list-item] + conftest.fail_server_test_without_cache(config, FakeItem("tmp_path")) # type: ignore[arg-type] + + def test_xdist_worker_fails_each_server_test_with_the_cause(self) -> None: + """A worker cannot report a usage error, so each server test fails with the message.""" + config = fake_config(workerinput={}) + conftest.require_cache_for_server_tests(config, [FakeItem("xprocess")]) # type: ignore[list-item] + with pytest.raises(pytest.fail.Exception, match="no:cacheprovider"): + conftest.fail_server_test_without_cache(config, FakeItem("xprocess")) # type: ignore[arg-type]