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
+31
-1
@@ -133,8 +133,38 @@ def pytest_addoption(parser):
|
||||
)
|
||||
|
||||
|
||||
SERVER_MARKER = "eos_server"
|
||||
|
||||
|
||||
def mark_server_tests(items: Sequence[pytest.Item]) -> None:
|
||||
"""Mark the tests that start a real EOS or EOSdash server.
|
||||
|
||||
The servers listen on fixed ports, so these tests must not run next to each other. A test
|
||||
belongs to them if it uses the ``xprocess`` fixture, directly or through the server fixtures,
|
||||
or if it already carries the ``eos_server`` marker (a test that binds the ports without a
|
||||
fixture). Each of them gets the marker, which ``-m eos_server`` selects, and the same
|
||||
``xdist_group``, which keeps them on one worker under ``pytest -n ... --dist loadgroup``.
|
||||
|
||||
Args:
|
||||
items: The collected test items.
|
||||
"""
|
||||
for item in items:
|
||||
uses_server = "xprocess" in getattr(item, "fixturenames", ())
|
||||
if uses_server and item.get_closest_marker(SERVER_MARKER) is None:
|
||||
item.add_marker(SERVER_MARKER)
|
||||
if item.get_closest_marker(SERVER_MARKER) is not None:
|
||||
item.add_marker(pytest.mark.xdist_group(SERVER_MARKER))
|
||||
|
||||
|
||||
@pytest.hookimpl(tryfirst=True)
|
||||
def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item]) -> None:
|
||||
"""Skip the browser tests unless --browser-test is given."""
|
||||
"""Mark the server tests, and skip the browser tests unless --browser-test is given.
|
||||
|
||||
Runs first: pytest-xdist reads the ``xdist_group`` marker in its own hook of this name. That
|
||||
plugin is registered after this file, so without ``tryfirst`` its hook runs before the marker
|
||||
is set here and the group has no effect.
|
||||
"""
|
||||
mark_server_tests(items)
|
||||
if config.getoption("--browser-test"):
|
||||
return
|
||||
skip_browser = pytest.mark.skip(reason="browser test: enable with --browser-test")
|
||||
|
||||
+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 == []
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Tests for the script that splits the pytest modules into CI shards."""
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _load_shard_module() -> ModuleType:
|
||||
"""Load the shard script directly from its source file.
|
||||
|
||||
Returns:
|
||||
The imported shard script module.
|
||||
|
||||
Raises:
|
||||
ImportError: If the module cannot be loaded.
|
||||
"""
|
||||
script_path = Path(__file__).resolve().parents[1] / "scripts" / "shard_test_files.py"
|
||||
spec = importlib.util.spec_from_file_location("shard_test_files", script_path)
|
||||
if spec is None or spec.loader is None:
|
||||
raise ImportError(f"Cannot load the shard script from {script_path}")
|
||||
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
_shard = _load_shard_module()
|
||||
|
||||
MODULES = [f"tests/test_m{index}.py" for index in range(11)]
|
||||
DURATIONS = {"tests/test_m0.py": 60.0, "tests/test_m1.py": 50.0, "tests/test_m2.py": 5.0}
|
||||
|
||||
|
||||
class TestSplit:
|
||||
"""Distribution of the test modules to the shards."""
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("shards", "durations"),
|
||||
[
|
||||
(1, DURATIONS),
|
||||
(2, {}),
|
||||
(4, DURATIONS),
|
||||
(20, DURATIONS),
|
||||
],
|
||||
)
|
||||
def test_every_module_is_in_exactly_one_shard(
|
||||
self, shards: int, durations: dict[str, float]
|
||||
) -> None:
|
||||
"""No module is dropped or run twice, with or without runtimes."""
|
||||
result = _shard.split(MODULES, durations, shards)
|
||||
|
||||
assert len(result) == shards
|
||||
assert sorted(module for shard in result for module in shard) == sorted(MODULES)
|
||||
|
||||
def test_heavy_modules_go_to_different_shards(self) -> None:
|
||||
"""The two modules that dominate the runtime do not share a shard."""
|
||||
result = _shard.split(MODULES, DURATIONS, 2)
|
||||
|
||||
assert ["tests/test_m0.py" in shard for shard in result] == [True, False]
|
||||
assert ["tests/test_m1.py" in shard for shard in result] == [False, True]
|
||||
|
||||
def test_split_does_not_depend_on_the_input_order(self) -> None:
|
||||
"""All jobs of a workflow run compute the same distribution."""
|
||||
assert _shard.split(MODULES, DURATIONS, 4) == _shard.split(
|
||||
list(reversed(MODULES)), DURATIONS, 4
|
||||
)
|
||||
|
||||
def test_non_positive_shard_count_is_rejected(self) -> None:
|
||||
with pytest.raises(ValueError, match="must be positive"):
|
||||
_shard.split(MODULES, DURATIONS, 0)
|
||||
|
||||
|
||||
class TestModuleList:
|
||||
"""The modules the script distributes."""
|
||||
|
||||
def test_modules_are_the_test_files_directly_in_tests(self) -> None:
|
||||
tests_dir = Path(__file__).resolve().parent
|
||||
modules = _shard.list_test_modules()
|
||||
|
||||
assert f"tests/{Path(__file__).name}" in modules
|
||||
assert "tests/conftest.py" not in modules
|
||||
assert modules == sorted(set(modules))
|
||||
for module in modules:
|
||||
path = tests_dir / Path(module).name
|
||||
assert module == f"tests/{path.name}"
|
||||
assert path.name.startswith("test_") and path.is_file()
|
||||
|
||||
|
||||
class TestDurations:
|
||||
"""The stored runtimes and their update from junit reports."""
|
||||
|
||||
def test_missing_file_counts_every_module_alike(self, tmp_path: Path) -> None:
|
||||
assert _shard.load_durations(tmp_path / "missing.json") == {}
|
||||
|
||||
def test_stored_runtimes_are_seconds_by_module_path(self) -> None:
|
||||
durations = _shard.load_durations()
|
||||
|
||||
assert durations
|
||||
assert all(
|
||||
name.startswith("tests/test_") and seconds >= 0 for name, seconds in durations.items()
|
||||
)
|
||||
|
||||
def test_junit_cases_are_summed_by_module(self, tmp_path: Path) -> None:
|
||||
report = tmp_path / "junit.xml"
|
||||
report.write_text(
|
||||
'<?xml version="1.0" encoding="utf-8"?>'
|
||||
'<testsuites><testsuite name="pytest">'
|
||||
'<testcase classname="tests.test_alpha.TestThing" name="test_a" time="1.25"/>'
|
||||
'<testcase classname="tests.test_alpha" name="test_b" time="0.5"/>'
|
||||
'<testcase classname="tests.test_beta.TestOther" name="test_c" time="2.004"/>'
|
||||
'<testcase classname="other.package" name="test_d" time="9"/>'
|
||||
"</testsuite></testsuites>",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
assert _shard.durations_from_junit([report]) == {
|
||||
"tests/test_alpha.py": 1.75,
|
||||
"tests/test_beta.py": 2.0,
|
||||
}
|
||||
@@ -207,11 +207,13 @@ class TestServerStartStop:
|
||||
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.eos_server
|
||||
@pytest.mark.asyncio
|
||||
async def test_server_start_eosdash(self, config_eos, monkeypatch, tmp_path):
|
||||
"""Test the EOSdash server startup from EOS.
|
||||
|
||||
Do not use any fixture as this will make pytest the owner of the EOSdash port.
|
||||
The test binds the fixed EOSdash port itself, hence the ``eos_server`` marker.
|
||||
|
||||
Tests that:
|
||||
1. EOSdash starts via the supervisor
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
"""The tests that start a real server are marked for selection and for pytest-xdist."""
|
||||
|
||||
from typing import Any, Optional, Union
|
||||
|
||||
import conftest
|
||||
import pytest
|
||||
|
||||
|
||||
class FakeItem:
|
||||
"""Minimal stand-in for a collected test item."""
|
||||
|
||||
def __init__(self, *fixturenames: str, marks: tuple[str, ...] = ()) -> None:
|
||||
self.fixturenames = fixturenames
|
||||
self.marks: dict[str, tuple[Any, ...]] = {name: () for name in marks}
|
||||
|
||||
def get_closest_marker(self, name: str) -> Optional[tuple[Any, ...]]:
|
||||
"""Return the arguments of the marker, or None if the item does not carry it."""
|
||||
return self.marks.get(name)
|
||||
|
||||
def add_marker(self, marker: Union[str, pytest.MarkDecorator]) -> None:
|
||||
"""Record the marker by its name, as pytest accepts a name or a decorator."""
|
||||
decorator = getattr(pytest.mark, marker) if isinstance(marker, str) else marker
|
||||
self.marks[decorator.name] = decorator.args
|
||||
|
||||
|
||||
def marks_after_marking(
|
||||
*fixturenames: str, marks: tuple[str, ...] = ()
|
||||
) -> dict[str, tuple[Any, ...]]:
|
||||
"""Run the server marking for one item and return the markers it carries then."""
|
||||
item = FakeItem(*fixturenames, marks=marks)
|
||||
conftest.mark_server_tests([item]) # type: ignore[list-item]
|
||||
return item.marks
|
||||
|
||||
|
||||
class TestServerMarker:
|
||||
"""Marking of the tests that start an EOS or EOSdash server."""
|
||||
|
||||
def test_test_using_xprocess_is_marked_and_grouped(self) -> None:
|
||||
"""A test that uses the xprocess fixture starts a server on the fixed ports."""
|
||||
assert marks_after_marking("config_eos", "xprocess") == {
|
||||
"eos_server": (),
|
||||
"xdist_group": ("eos_server",),
|
||||
}
|
||||
|
||||
def test_explicitly_marked_test_is_grouped(self) -> None:
|
||||
"""A test that binds the ports without a fixture carries the marker itself."""
|
||||
assert marks_after_marking("config_eos", marks=("eos_server",)) == {
|
||||
"eos_server": (),
|
||||
"xdist_group": ("eos_server",),
|
||||
}
|
||||
|
||||
def test_other_tests_are_left_alone(self) -> None:
|
||||
assert marks_after_marking("config_eos", "tmp_path") == {}
|
||||
|
||||
def test_marking_runs_before_other_collection_hooks(self, request: pytest.FixtureRequest) -> None:
|
||||
"""pytest-xdist reads the group in its own hook, which must run after the marking.
|
||||
|
||||
pluggy calls the plain hook implementations from the end of this list. The marking
|
||||
and everything behind it must be tryfirst, so that no ordinary implementation, such
|
||||
as the one of pytest-xdist on a worker, runs before it. Wrappers are left out: they
|
||||
surround all plain implementations whatever their order.
|
||||
"""
|
||||
hook = request.config.pluginmanager.hook.pytest_collection_modifyitems
|
||||
implementations = [
|
||||
implementation
|
||||
for implementation in hook.get_hookimpls()
|
||||
if not (implementation.hookwrapper or getattr(implementation, "wrapper", False))
|
||||
]
|
||||
marking = [
|
||||
implementation
|
||||
for implementation in implementations
|
||||
if implementation.function is conftest.pytest_collection_modifyitems
|
||||
]
|
||||
|
||||
assert len(marking) == 1
|
||||
called_first = implementations[implementations.index(marking[0]) :]
|
||||
assert all(implementation.tryfirst for implementation in called_first)
|
||||
|
||||
def test_no_unmarked_server_test_is_selected(self, request: pytest.FixtureRequest) -> None:
|
||||
"""Every selected test of this session that uses xprocess carries both markers.
|
||||
|
||||
A plain run checks all server tests this way. In a CI shard the session holds only
|
||||
the modules of that shard, and with working marking none of their server tests is
|
||||
selected; the test-count job checks the marking for the CI split.
|
||||
"""
|
||||
for item in request.session.items:
|
||||
if "xprocess" in getattr(item, "fixturenames", ()):
|
||||
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
|
||||
@@ -22,6 +22,7 @@ from akkudoktoreos.core.version import (
|
||||
_version_date_hash,
|
||||
collect_files,
|
||||
hash_files,
|
||||
version,
|
||||
)
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime
|
||||
|
||||
@@ -230,6 +231,28 @@ def test_version_date_hash() -> None:
|
||||
|
||||
|
||||
# --- Test version helpers ---
|
||||
@pytest.mark.parametrize(
|
||||
("version_string", "expected"),
|
||||
[
|
||||
("0.4.0", {"base": "0.4.0", "date": None, "hash": None}),
|
||||
("0.4.0.dev26111612", {"base": "0.4.0", "date": "26111612", "hash": None}),
|
||||
("0.4.0.dev26111612a96a65", {"base": "0.4.0", "date": "26111612", "hash": "a96a65"}),
|
||||
],
|
||||
)
|
||||
def test_version_parses_version_string(monkeypatch, version_string, expected):
|
||||
"""version() splits __version__ into base, date and hash."""
|
||||
monkeypatch.setattr("akkudoktoreos.core.version.__version__", version_string)
|
||||
|
||||
assert version() == {**expected, "version": version_string}
|
||||
|
||||
|
||||
def test_version_rejects_invalid_version_string(monkeypatch):
|
||||
monkeypatch.setattr("akkudoktoreos.core.version.__version__", "0.4")
|
||||
|
||||
with pytest.raises(ValueError, match="Invalid version format"):
|
||||
version()
|
||||
|
||||
|
||||
def test_version_non_dev(monkeypatch):
|
||||
"""If VERSION_BASE does not end with 'dev', no hash digits are appended."""
|
||||
monkeypatch.setattr("akkudoktoreos.core.version.VERSION_BASE", "0.2.0")
|
||||
|
||||
Reference in New Issue
Block a user