mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2026-11-25 15:06:20 +01:00
ci: run the tests in parallel jobs and speed up the Sphinx build
The single test job ran all tests one after the other on one runner,
including the Sphinx build and the Docker checks (11-19 min). It is now
split so that every test still runs exactly once:
- docs-test, docker-test: the Sphinx build (new marker "docs") and the
Docker / Home Assistant add-on checks ("docker") in jobs of their own.
- test-server: the tests that start EOS or EOSdash on the fixed ports.
The collection hook marks every test that uses the xprocess fixture
with "eos_server" and puts them into one xdist group, so
"pytest -n auto --dist loadgroup" also works locally. A test that
binds the ports without a fixture carries the marker itself.
- test-shard: all other tests in four shards of about equal runtime
(scripts/shard_test_files.py, runtimes in scripts/test_durations.json),
each with pytest-xdist.
- test-count: fails if these parts do not add up to the tests of one
plain run.
- test: keeps the name of the required check. It prints the combined
coverage report and fails if any of the jobs above failed.
COVERAGE_CORE=sysmon measures line coverage through sys.monitoring:
the report is the same, the test time drops by about a third. The
combined report misses 1-3 statements more than a single run, in lines
that only run when a test finds state left by an earlier test.
The Sphinx build spent 74 % of its time in one search of
PythonDomain.find_obj (sphinx-doc/sphinx#11282). The local extension
docs/_ext/pyxrefindex.py answers it from an index of name endings with
the same matches in the same order; a build has a byte-identical
objects.inv. It copies the logic of Sphinx 9.0.4 and is only active for
that version; TestPyXrefIndex compares it with the installed Sphinx and
fails after a Sphinx update until the version is raised. The
documentation test builds with -j (up to four jobs); its pages can
differ from a serial build in the target of ambiguous cross-references.
Read the Docs builds without -j. Sphinx build on GitHub runners:
427-480 s -> 180-233 s.
make test-ci runs the commands of these jobs one after the other.
On GitHub runners the tests are done after about 2 minutes; the
required check ends with docs-test after about 4-5 minutes.
Additional changes
Add pytest-xdist to the development dependencies
List the 25 slowest tests in each test job (--durations=25)
Test version() directly; it was covered only through the Sphinx test
Add a "Keep Tests Fast" tip, the server marker rule, the extension and
test-ci to the development guide and the testing skill
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
e2726354c2
commit
57905b2024
+202
-1
@@ -1,3 +1,4 @@
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
@@ -5,12 +6,17 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
from types import ModuleType, SimpleNamespace
|
||||
from typing import TYPE_CHECKING, Any, Optional, cast
|
||||
|
||||
import pytest
|
||||
|
||||
from akkudoktoreos.core.coreabc import singletons_init
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from sphinx.domains.python import PythonDomain
|
||||
from sphinx.environment import BuildEnvironment
|
||||
|
||||
DIR_PROJECT_ROOT = Path(__file__).absolute().parent.parent
|
||||
DIR_BUILD = DIR_PROJECT_ROOT / "build"
|
||||
DIR_BUILD_DOCS = DIR_PROJECT_ROOT / "build" / "docs"
|
||||
@@ -19,6 +25,12 @@ DIR_SRC = DIR_PROJECT_ROOT / "src"
|
||||
|
||||
HASH_FILE = DIR_BUILD / ".sphinx_hash.json"
|
||||
|
||||
# Parallel jobs of the Sphinx build. Sphinx reads the sources and writes the pages in several
|
||||
# processes; resolving the cross-references stays in the main process. With the EOS API
|
||||
# reference each process needs up to 1.4 GB of memory, so the number is limited. Sphinx builds
|
||||
# with one process where it cannot fork (Windows).
|
||||
SPHINX_JOBS = min(4, os.cpu_count() or 1)
|
||||
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
@@ -91,6 +103,7 @@ def sphinx_changed(version_and_hash) -> Optional[str]:
|
||||
return new_hash
|
||||
|
||||
|
||||
@pytest.mark.docs
|
||||
class TestSphinxDocumentation:
|
||||
"""Test class to verify Sphinx documentation generation.
|
||||
|
||||
@@ -102,6 +115,8 @@ class TestSphinxDocumentation:
|
||||
"html",
|
||||
str(DIR_DOCS),
|
||||
str(DIR_BUILD_DOCS),
|
||||
"-j",
|
||||
str(SPHINX_JOBS),
|
||||
]
|
||||
|
||||
def _cleanup_autosum_dirs(self):
|
||||
@@ -186,3 +201,189 @@ class TestSphinxDocumentation:
|
||||
# Update stored hash
|
||||
HASH_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
HASH_FILE.write_text(json.dumps({"hash": sphinx_changed}, indent=2))
|
||||
|
||||
|
||||
# --- Local Sphinx extension docs/_ext/pyxrefindex.py --------------------------------
|
||||
|
||||
PYXREFINDEX_FILE = DIR_DOCS / "_ext" / "pyxrefindex.py"
|
||||
|
||||
# (name, objtype, docname): ambiguous names in several modules and classes, all Python
|
||||
# object types, a top-level name without dots and an aliased duplicate.
|
||||
PYXREFINDEX_OBJECTS = [
|
||||
("eos", "module", "doc1"),
|
||||
("eos.core", "module", "doc1"),
|
||||
("eos.core.Config", "class", "doc1"),
|
||||
("eos.core.Config.load", "method", "doc1"),
|
||||
("eos.core.Config.from_file", "classmethod", "doc1"),
|
||||
("eos.core.Config.value", "attribute", "doc1"),
|
||||
("eos.core.Config.size", "property", "doc1"),
|
||||
("eos.core.Settings", "class", "doc1"),
|
||||
("eos.core.Settings.type", "attribute", "doc1"),
|
||||
("eos.core.helper", "function", "doc1"),
|
||||
("eos.core.make", "staticmethod", "doc1"),
|
||||
("eos.core.LIMIT", "data", "doc1"),
|
||||
("eos.core.Alias", "type", "doc1"),
|
||||
("eos.core.Error", "exception", "doc1"),
|
||||
("eos.devices.Battery", "class", "doc2"),
|
||||
("eos.devices.Battery.load", "method", "doc2"),
|
||||
("eos.devices.Battery.value", "property", "doc2"),
|
||||
("eos.devices.Settings", "class", "doc2"),
|
||||
("eos.devices.Settings.type", "attribute", "doc2"),
|
||||
("eos.devices.helper", "data", "doc2"),
|
||||
("Top", "class", "doc2"),
|
||||
("Top.load", "method", "doc2"),
|
||||
]
|
||||
|
||||
|
||||
class PyXrefIndexEnvironment:
|
||||
"""The part of a Sphinx build environment that the Python domain uses in these tests.
|
||||
|
||||
A real Sphinx application would register its directives and roles in docutils for the
|
||||
rest of the test process.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.domaindata: dict[str, dict[str, Any]] = {}
|
||||
self.current_document = SimpleNamespace(docname="")
|
||||
|
||||
|
||||
def _load_pyxrefindex(monkeypatch: pytest.MonkeyPatch) -> ModuleType:
|
||||
"""Import docs/_ext/pyxrefindex.py as module ``pyxrefindex``."""
|
||||
spec = importlib.util.spec_from_file_location("pyxrefindex", PYXREFINDEX_FILE)
|
||||
assert spec is not None and spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
monkeypatch.setitem(sys.modules, "pyxrefindex", module)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
class TestPyXrefIndex:
|
||||
"""The indexed Python domain finds the same objects as Sphinx's own search.
|
||||
|
||||
Fast tests without a documentation build. They fail when a Sphinx update
|
||||
changes ``PythonDomain.find_obj`` so that the index no longer matches it.
|
||||
"""
|
||||
|
||||
@pytest.fixture
|
||||
def pyxrefindex(self, monkeypatch: pytest.MonkeyPatch) -> ModuleType:
|
||||
return _load_pyxrefindex(monkeypatch)
|
||||
|
||||
@pytest.fixture
|
||||
def domains(self, pyxrefindex: ModuleType) -> tuple["PythonDomain", "PythonDomain"]:
|
||||
"""Return (Sphinx's PythonDomain, indexed domain) that share their objects."""
|
||||
from sphinx.domains.python import PythonDomain
|
||||
|
||||
env = PyXrefIndexEnvironment()
|
||||
original = PythonDomain(cast("BuildEnvironment", env))
|
||||
indexed = pyxrefindex.IndexedPythonDomain(env)
|
||||
assert original.data is indexed.data
|
||||
for name, objtype, docname in PYXREFINDEX_OBJECTS:
|
||||
env.current_document.docname = docname
|
||||
indexed.note_object(name, objtype, f"id-{name}")
|
||||
env.current_document.docname = "doc1"
|
||||
indexed.note_object("eos.core.Config.load", "method", "alias", aliased=True)
|
||||
return original, indexed
|
||||
|
||||
@staticmethod
|
||||
def _queries() -> list[str]:
|
||||
names = {""}
|
||||
for name, _, _ in PYXREFINDEX_OBJECTS:
|
||||
parts = name.split(".")
|
||||
for i in range(len(parts)):
|
||||
names.add(".".join(parts[i:]))
|
||||
names |= {f"{n}()" for n in list(names)}
|
||||
names |= {"missing", "Config.missing", ".load", "load.", "..load", "core.Settings.type"}
|
||||
return sorted(names)
|
||||
|
||||
def test_find_obj_matches_sphinx(self, domains: tuple["PythonDomain", "PythonDomain"]) -> None:
|
||||
original, indexed = domains
|
||||
roles = [None, "unknown", *sorted({r for t in original.object_types.values() for r in t.roles})]
|
||||
ambiguous = 0
|
||||
for searchmode in (0, 1):
|
||||
for modname in (None, "eos.core", "eos.devices"):
|
||||
for classname in (None, "Config", "Settings"):
|
||||
for role in roles:
|
||||
for name in self._queries():
|
||||
args = (original.env, modname, classname, name, role, searchmode)
|
||||
expected = original.find_obj(*args) # type: ignore[arg-type]
|
||||
assert indexed.find_obj(*args) == expected, args[1:] # type: ignore[arg-type]
|
||||
ambiguous += len(expected) > 1
|
||||
# The objects really exercise the fuzzy search with several matches.
|
||||
assert ambiguous > 0
|
||||
|
||||
def test_index_follows_object_changes(self, domains: tuple["PythonDomain", "PythonDomain"]) -> None:
|
||||
from sphinx.domains.python import ObjectEntry
|
||||
|
||||
original, indexed = domains
|
||||
env = indexed.env
|
||||
|
||||
def methods_named(name: str) -> list[str]:
|
||||
"""Names the indexed search finds; they must be those of Sphinx's search."""
|
||||
found = [n for n, _ in indexed.find_obj(env, None, None, name, "meth", 1)] # type: ignore[arg-type]
|
||||
assert found == [n for n, _ in original.find_obj(env, None, None, name, "meth", 1)] # type: ignore[arg-type]
|
||||
return found
|
||||
|
||||
assert methods_named("load") == ["eos.core.Config.load", "eos.devices.Battery.load", "Top.load"]
|
||||
|
||||
env.current_document.docname = "doc3"
|
||||
indexed.note_object("eos.extra.Thing.load", "method", "id-thing")
|
||||
assert methods_named("load")[-1] == "eos.extra.Thing.load"
|
||||
|
||||
indexed.clear_doc("doc2")
|
||||
assert methods_named("load") == ["eos.core.Config.load", "eos.extra.Thing.load"]
|
||||
|
||||
entry = ObjectEntry("doc4", "id-merged", "method", False)
|
||||
indexed.merge_domaindata({"doc4"}, {"objects": {"eos.merged.M.load": entry}, "modules": {}})
|
||||
assert methods_named("load")[-1] == "eos.merged.M.load"
|
||||
|
||||
# In the next three steps the number of objects is the same before and after, so the
|
||||
# index is only right if clear_doc, note_object and merge_domaindata each drop it.
|
||||
del indexed.objects["eos.merged.M.load"]
|
||||
indexed.objects["eos.swapped.S.load"] = ObjectEntry("doc5", "id-swapped", "method", False)
|
||||
indexed.clear_doc("doc-without-objects")
|
||||
assert methods_named("load")[-1] == "eos.swapped.S.load"
|
||||
|
||||
del indexed.objects["eos.swapped.S.load"]
|
||||
env.current_document.docname = "doc6"
|
||||
indexed.note_object("eos.noted.N.load", "method", "id-noted")
|
||||
assert methods_named("load")[-1] == "eos.noted.N.load"
|
||||
|
||||
del indexed.objects["eos.noted.N.load"]
|
||||
other = ObjectEntry("doc7", "id-other", "method", False)
|
||||
indexed.merge_domaindata({"doc7"}, {"objects": {"eos.other.O.load": other}, "modules": {}})
|
||||
assert methods_named("load")[-1] == "eos.other.O.load"
|
||||
|
||||
# A direct change of the objects that changes their number is noticed as well.
|
||||
indexed.objects["eos.direct.D.load"] = ObjectEntry("doc8", "id-direct", "method", False)
|
||||
assert methods_named("load")[-1] == "eos.direct.D.load"
|
||||
|
||||
def test_verified_sphinx_version(self, pyxrefindex: ModuleType) -> None:
|
||||
"""Raise VERIFIED_SPHINX_VERSION only after these tests pass with the new Sphinx."""
|
||||
import sphinx
|
||||
|
||||
assert tuple(sphinx.version_info[:3]) == pyxrefindex.VERIFIED_SPHINX_VERSION, (
|
||||
"Sphinx was updated. Set VERIFIED_SPHINX_VERSION in docs/_ext/pyxrefindex.py to the "
|
||||
"new version and keep it only if the other tests of this class pass."
|
||||
)
|
||||
|
||||
def test_setup_keeps_sphinx_domain_for_other_versions(
|
||||
self, pyxrefindex: ModuleType, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
import sphinx
|
||||
|
||||
class App:
|
||||
def __init__(self) -> None:
|
||||
self.domains: list[type] = []
|
||||
|
||||
def add_domain(self, domain: type, override: bool = False) -> None:
|
||||
assert override, "Sphinx refuses to replace the Python domain without override"
|
||||
self.domains.append(domain)
|
||||
|
||||
app = App()
|
||||
assert pyxrefindex.setup(app)["parallel_read_safe"] is True
|
||||
assert app.domains == [pyxrefindex.IndexedPythonDomain]
|
||||
|
||||
monkeypatch.setattr(sphinx, "version_info", (99, 0, 0, "final", 0))
|
||||
app = App()
|
||||
pyxrefindex.setup(app)
|
||||
assert app.domains == []
|
||||
|
||||
Reference in New Issue
Block a user