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:
Christin
2026-11-20 07:15:33 +01:00
committed by Bobby Noelte
co-authored by SchaafAlexander Claude Opus 5.5
parent e2726354c2
commit 57905b2024
16 changed files with 1284 additions and 8 deletions
+239 -3
View File
@@ -8,9 +8,34 @@ on:
push: push:
branches: [main] branches: [main]
# The tests run in several jobs at the same time, and every test runs exactly once:
# test-shard the tests without a real server, in four shards of about equal runtime
# (scripts/shard_test_files.py), each on all cores with pytest-xdist
# test-server the tests that start an EOS or EOSdash server on the fixed ports
# (marker 'eos_server'), one after the other
# test-count checks that these parts add up to the tests of one plain run
# test prints the coverage report of all parts and fails if one of the jobs above,
# 'docs-test' or 'docker-test' failed. It is the required check, and on main
# the single test job ran the docs and Docker tests as well.
# The Sphinx build ('docs') and the Docker checks ('docker') have their own jobs below.
env:
# Line coverage through sys.monitoring instead of the default sys.settrace
# tracer: the report stays the same, the tracing overhead mostly goes away.
# Branch coverage (--cov-branch) needs Python 3.14 with this core.
COVERAGE_CORE: sysmon
jobs: jobs:
test: test-shard:
runs-on: ubuntu-latest runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
# The number of shards also appears in the calls of scripts/shard_test_files.py
# in this job and in test-count.
shard: [0, 1, 2, 3]
env:
COVERAGE_FILE: covdata.shard${{ matrix.shard }}
steps: steps:
- name: Checkout code - name: Checkout code
@@ -31,17 +56,228 @@ jobs:
uv sync --extra dev uv sync --extra dev
- name: Run tests - name: Run tests
# --durations lists the slowest tests of the shard. The junit report holds the
# runtimes that scripts/shard_test_files.py --update reads.
run: | run: |
uv run pytest --finalize --check-config-side-effect -vs --cov src --cov-report term-missing FILES=$(uv run python scripts/shard_test_files.py 4 ${{ matrix.shard }})
test -n "$FILES"
uv run pytest --finalize --check-config-side-effect -m "not eos_server and not docs and not docker" -n auto -v --durations=25 --cov src --cov-report= --junitxml=junit-shard-${{ matrix.shard }}.xml $FILES
- name: Upload coverage data
if: always()
uses: actions/upload-artifact@v7
with:
name: covdata-shard-${{ matrix.shard }}
path: covdata.shard${{ matrix.shard }}
if-no-files-found: warn
retention-days: 1
- name: Upload junit report
if: always()
uses: actions/upload-artifact@v7
with:
name: junit-shard-${{ matrix.shard }}
path: junit-shard-${{ matrix.shard }}.xml
if-no-files-found: ignore
retention-days: 7
- name: Upload test artifacts - name: Upload test artifacts
if: failure() if: failure()
uses: actions/upload-artifact@v7 uses: actions/upload-artifact@v7
with: with:
name: optimize-results name: optimize-results-shard-${{ matrix.shard }}
path: tests/testdata/**/new_optimize_result* path: tests/testdata/**/new_optimize_result*
if-no-files-found: ignore if-no-files-found: ignore
test-server:
# These tests start real servers on fixed ports, so they run one after the other
# and on a machine of their own.
runs-on: ubuntu-latest
env:
COVERAGE_FILE: covdata.server
steps:
- name: Checkout code
uses: actions/checkout@v7
- name: Set up Python
uses: actions/setup-python@v7
with:
python-version: "3.13.15"
- name: Install uv
run: |
python -m pip install --upgrade pip
pip install uv
- name: Sync environment with uv
run: |
uv sync --extra dev
- name: Run server tests
run: |
uv run pytest --finalize --check-config-side-effect -m "eos_server and not docs and not docker" -vs --durations=25 --cov src --cov-report=
- name: Upload coverage data
if: always()
uses: actions/upload-artifact@v7
with:
name: covdata-server
path: covdata.server
if-no-files-found: warn
retention-days: 1
test-count:
# No test may get lost between the parts: the server tests and the tests of the four
# shards must add up to the tests of one plain run. The marker of the server tests is
# derived from the xprocess fixture; if that stopped working, they would run inside
# the shards, so one of them is checked by name.
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v7
- name: Set up Python
uses: actions/setup-python@v7
with:
python-version: "3.13.15"
- name: Install uv
run: |
python -m pip install --upgrade pip
pip install uv
- name: Sync environment with uv
run: |
uv sync --extra dev
- name: Count the collected tests
run: |
count() {
# A collection error must fail the job, not just skew the numbers.
local output
output=$(uv run pytest --collect-only -q --finalize "$@") || return 1
echo "$output" | tail -n 1 | grep -oE '^[0-9]+'
}
total=$(count -m "not docs and not docker")
server=$(count -m "eos_server and not docs and not docker")
sum=$server
for shard in 0 1 2 3; do
files=$(uv run python scripts/shard_test_files.py 4 $shard)
part=$(count -m "not eos_server and not docs and not docker" $files)
echo "shard $shard: $part tests"
sum=$((sum + part))
done
echo "plain run: $total tests, server: $server tests, sum of all parts: $sum tests"
test "$total" -gt 0
test "$server" -gt 0
test "$sum" -eq "$total"
uv run pytest --collect-only -q --finalize -m "eos_server" tests/test_server.py | grep -q "TestServer::test_server_setup_for_class"
test:
# The result of all test jobs under the name of the former single test job. The
# coverage report is printed even if a job failed; the last step then fails this job.
needs: [test-shard, test-server, test-count, docs-test, docker-test]
if: always()
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v7
- name: Set up Python
uses: actions/setup-python@v7
with:
python-version: "3.13.15"
- name: Install uv
run: |
python -m pip install --upgrade pip
pip install uv
- name: Sync environment with uv
run: |
uv sync --extra dev
- name: Download coverage data
uses: actions/download-artifact@v8
with:
pattern: covdata-*
path: covdata
merge-multiple: true
- name: Coverage report
run: |
uv run coverage combine covdata/covdata.*
uv run coverage report -m
- name: Check the test jobs
if: always()
run: |
echo "test-shard: ${{ needs.test-shard.result }}"
echo "test-server: ${{ needs.test-server.result }}"
echo "test-count: ${{ needs.test-count.result }}"
echo "docs-test: ${{ needs.docs-test.result }}"
echo "docker-test: ${{ needs.docker-test.result }}"
test "${{ needs.test-shard.result }}" = "success"
test "${{ needs.test-server.result }}" = "success"
test "${{ needs.test-count.result }}" = "success"
test "${{ needs.docs-test.result }}" = "success"
test "${{ needs.docker-test.result }}" = "success"
docs-test:
# Full Sphinx HTML build (tests marked 'docs'), split off the test job.
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v7
- name: Set up Python
uses: actions/setup-python@v7
with:
python-version: "3.13.15"
- name: Install uv
run: |
python -m pip install --upgrade pip
pip install uv
- name: Sync environment with uv
run: |
uv sync --extra dev
- name: Run Sphinx build test
run: |
uv run pytest --finalize --check-config-side-effect -m docs -vs
docker-test:
# Docker image and Home Assistant add-on builder checks (tests marked 'docker').
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v7
- name: Set up Python
uses: actions/setup-python@v7
with:
python-version: "3.13.15"
- name: Install uv
run: |
python -m pip install --upgrade pip
pip install uv
- name: Sync environment with uv
run: |
uv sync --extra dev
- name: Run Docker tests
run: |
uv run pytest --finalize --check-config-side-effect -m docker -vs
browser-test: browser-test:
# EOSdash in headless Chromium (tests marked 'browser', enabled by --browser-test). # EOSdash in headless Chromium (tests marked 'browser', enabled by --browser-test).
runs-on: ubuntu-latest runs-on: ubuntu-latest
+12 -3
View File
@@ -40,7 +40,8 @@ help:
@echo " test - Run tests." @echo " test - Run tests."
@echo " test-finalize - Run all tests (e.g. to finalize a commit)." @echo " test-finalize - Run all tests (e.g. to finalize a commit)."
@echo " test-system - Run tests with system tests enabled." @echo " test-system - Run tests with system tests enabled."
@echo " test-ci - Run tests as CI does. No user config file allowed." @echo " test-ci - Run tests as CI does (server tests, other tests in parallel, docs, Docker)."
@echo " No user config file allowed."
@echo " test-browser - Run the EOSdash browser tests in headless Chromium (installs Chromium)." @echo " test-browser - Run the EOSdash browser tests in headless Chromium (installs Chromium)."
@echo " test-profile - Run single test optimization with profiling." @echo " test-profile - Run single test optimization with profiling."
@echo " dist - Create distribution (in dist/)." @echo " dist - Create distribution (in dist/)."
@@ -135,10 +136,18 @@ test:
@echo "Running tests..." @echo "Running tests..."
$(PYTEST) -vs --cov src --cov-report term-missing $(PYTEST) -vs --cov src --cov-report term-missing
# Target to run tests as done by CI on Github. # Target to run tests as done by CI on Github (.github/workflows/pytest.yml), one part after
# the other: the server tests (test-server), the other tests on all cores (test-shard, without
# splitting them into shards), the Sphinx build (docs-test) and the Docker checks (docker-test).
# Every test runs once. The coverage report covers the first two parts, like the test job.
# The browser tests (browser-test) have their own target test-browser.
test-ci: export COVERAGE_CORE := sysmon
test-ci: test-ci:
@echo "Running tests as CI..." @echo "Running tests as CI..."
$(PYTEST) --finalize --check-config-side-effect -vs --cov src --cov-report term-missing $(PYTEST) --finalize --check-config-side-effect -m "eos_server and not docs and not docker" -vs --durations=25 --cov src --cov-report=
$(PYTEST) --finalize --check-config-side-effect -m "not eos_server and not docs and not docker" -n auto -v --durations=25 --cov src --cov-append --cov-report term-missing
$(PYTEST) --finalize --check-config-side-effect -m docs -vs
$(PYTEST) --finalize --check-config-side-effect -m docker -vs
# Target to run the EOSdash browser tests in headless Chromium. # Target to run the EOSdash browser tests in headless Chromium.
# The browser is installed for the user (~/.cache/ms-playwright), not in the virtual environment. # The browser is installed for the user (~/.cache/ms-playwright), not in the virtual environment.
+5
View File
@@ -24,6 +24,11 @@ description: Use when adding or updating pytest tests, fixing bugs, or changing
(use synthetic timestamps), no full cartesian `parametrize` over independent (use synthetic timestamps), no full cartesian `parametrize` over independent
axes, and extend an existing parametrized test before writing a new one. axes, and extend an existing parametrized test before writing a new one.
The CI log lists the 25 slowest tests (`--durations=25`). The CI log lists the 25 slowest tests (`--durations=25`).
- A test that starts an EOS or EOSdash server on the fixed ports uses the server
fixtures (`server_setup_for_class`, `server_setup_for_function`), which mark it
`eos_server` through the `xprocess` fixture. If a test must bind these ports
without them, mark it `@pytest.mark.eos_server` itself: CI runs these tests in
their own job, all others in parallel.
## Verify ## Verify
+176
View File
@@ -0,0 +1,176 @@
"""Speed up Python cross-reference resolution with a suffix index.
Sphinx resolves most Python cross-references in "fuzzy" search mode (every
reference created from a type annotation carries ``refspecific``). For a name
that is not found exactly, ``PythonDomain.find_obj`` then scans *all* known
objects for names ending in ``.<name>`` (sphinx/domains/python/__init__.py,
fuzzy branch of ``find_obj``). With the EOS API reference (about 22,000 objects
and 150,000 references) this linear scan takes about three quarters of the whole
documentation build, see https://github.com/sphinx-doc/sphinx/issues/11282.
This extension replaces the Python domain with a subclass that answers the
fuzzy search from an index instead of a scan. ``oname.endswith("." + name)``
holds exactly when ``name`` follows one of the dots in ``oname``, so the index
maps every such suffix to the object names, in the iteration order of the
domain's objects. The search therefore returns the same matches in the same
order as Sphinx, including the first match that Sphinx picks for an ambiguous
name. The rendered documentation does not change.
The subclass copies the logic of ``find_obj`` from the Sphinx version in
``VERIFIED_SPHINX_VERSION``. For any other Sphinx version the extension does
nothing and logs a note; ``TestPyXrefIndex`` in ``tests/test_docsphinx.py``
checks the equivalence against the installed Sphinx and must pass before the
version is raised.
"""
from collections.abc import Set
from typing import Any
import sphinx
from sphinx.application import Sphinx
from sphinx.domains.python import ObjectEntry, PythonDomain
from sphinx.environment import BuildEnvironment
from sphinx.util import logging
logger = logging.getLogger(__name__)
#: Sphinx version whose ``PythonDomain.find_obj`` this extension reproduces.
VERIFIED_SPHINX_VERSION: tuple[int, int, int] = (9, 0, 4)
class IndexedPythonDomain(PythonDomain):
"""Python domain whose fuzzy object search uses a suffix index.
The index is built on the first fuzzy search and dropped whenever the
domain changes its objects (``note_object``, ``clear_doc``,
``merge_domaindata``); Sphinx changes them nowhere else. As a second line
of defence the index is rebuilt when the number of objects differs from
the indexed one. A direct change of the objects mapping that keeps their
number is not noticed.
"""
_suffix_index: tuple[int, dict[str, list[str]]] | None = None
def _drop_suffix_index(self) -> None:
"""Forget the suffix index; the next fuzzy search rebuilds it."""
self._suffix_index = None
def _suffixes(self) -> dict[str, list[str]]:
"""Return the suffix index of the current objects.
Returns:
Mapping of every text that follows a dot in an object name to the
object names with that ending, in the order of ``self.objects``.
"""
objects = self.objects
if self._suffix_index is not None and self._suffix_index[0] == len(objects):
return self._suffix_index[1]
index: dict[str, list[str]] = {}
for oname in objects:
pos = oname.find(".")
while pos != -1:
index.setdefault(oname[pos + 1 :], []).append(oname)
pos = oname.find(".", pos + 1)
self._suffix_index = (len(objects), index)
return index
def note_object(
self,
name: str,
objtype: str,
node_id: str,
aliased: bool = False,
location: Any = None,
) -> None:
"""Note a Python object for cross-reference and drop the index."""
self._drop_suffix_index()
super().note_object(name, objtype, node_id, aliased=aliased, location=location)
def clear_doc(self, docname: str) -> None:
"""Remove the objects of ``docname`` and drop the index."""
self._drop_suffix_index()
super().clear_doc(docname)
def merge_domaindata(self, docnames: Set[str], otherdata: dict[str, Any]) -> None:
"""Merge objects from a parallel read process and drop the index."""
self._drop_suffix_index()
super().merge_domaindata(docnames, otherdata)
def find_obj(
self,
env: BuildEnvironment,
modname: str,
classname: str,
name: str,
type: str | None,
searchmode: int = 0,
) -> list[tuple[str, ObjectEntry]]:
"""Find a Python object like ``PythonDomain.find_obj``.
Only the fuzzy branch of search mode 1 differs: it looks the name up in
the suffix index instead of scanning all objects.
Args:
env: The build environment.
modname: Module of the reference, if any.
classname: Class of the reference, if any.
name: Target name of the reference.
type: Role of the reference, or ``None`` for any object type.
searchmode: 1 for references marked ``refspecific``, else 0.
Returns:
Matching ``(name, object entry)`` pairs, in Sphinx's order.
"""
if searchmode != 1:
return super().find_obj(env, modname, classname, name, type, searchmode)
name = name.removesuffix("()")
if not name:
return []
if type is None:
objtypes: list[str] | None = list(self.object_types)
else:
objtypes = self.objtypes_for_role(type)
if objtypes is None:
return []
objects = self.objects
if modname and classname:
fullname = f"{modname}.{classname}.{name}"
if fullname in objects and objects[fullname].objtype in objtypes:
return [(fullname, objects[fullname])]
if (
modname
and f"{modname}.{name}" in objects
and objects[f"{modname}.{name}"].objtype in objtypes
):
return [(f"{modname}.{name}", objects[f"{modname}.{name}"])]
if name in objects and objects[name].objtype in objtypes:
return [(name, objects[name])]
return [
(oname, objects[oname])
for oname in self._suffixes().get(name, ())
if objects[oname].objtype in objtypes
]
def setup(app: Sphinx) -> dict[str, Any]:
"""Install the indexed Python domain if the Sphinx version is verified.
Args:
app: The Sphinx application.
Returns:
Extension metadata; the extension is safe for parallel builds.
"""
if tuple(sphinx.version_info[:3]) == VERIFIED_SPHINX_VERSION:
app.add_domain(IndexedPythonDomain, override=True)
else:
logger.info(
"pyxrefindex: Sphinx %s is not the verified version %s; "
"using the unindexed Python cross-reference search.",
sphinx.__display_version__,
".".join(map(str, VERIFIED_SPHINX_VERSION)),
)
return {"parallel_read_safe": True, "parallel_write_safe": True}
+3
View File
@@ -11,6 +11,8 @@ from pathlib import Path
PROJECT_ROOT = Path(__file__).parent.parent PROJECT_ROOT = Path(__file__).parent.parent
SRC_DIR = PROJECT_ROOT / "src" SRC_DIR = PROJECT_ROOT / "src"
sys.path.insert(0, str(SRC_DIR)) sys.path.insert(0, str(SRC_DIR))
# Local Sphinx extensions
sys.path.insert(0, str(Path(__file__).parent / "_ext"))
# Tell akkudoktoreos that it is imported for the documentation build # Tell akkudoktoreos that it is imported for the documentation build
# (see ConfigEOS.documentation_mode()). # (see ConfigEOS.documentation_mode()).
@@ -38,6 +40,7 @@ extensions = [
"myst_parser", "myst_parser",
"sphinx_tabs.tabs", "sphinx_tabs.tabs",
"sphinxcontrib.mermaid", "sphinxcontrib.mermaid",
"pyxrefindex", # faster Python cross-reference search, see docs/_ext/pyxrefindex.py
] ]
templates_path = ["_templates"] templates_path = ["_templates"]
+64
View File
@@ -600,6 +600,70 @@ Ensure your changes do not break existing functionality:
make test make test
``` ```
### Keep Tests Fast
Keep each test case well under a second:
- Do not wait in real time (no `sleep` or wait loops); use synthetic timestamps instead.
- Do not `parametrize` the full cartesian product of independent axes.
- Extend an existing parametrized test before writing a new one.
The CI logs of the `test-shard` and `test-server` jobs list their 25 slowest tests
(`--durations=25`). The Sphinx documentation build and the Docker checks run in their own CI
jobs. Run them locally with `uv run pytest --finalize -m docs` and
`uv run pytest --finalize -m docker` (the Docker checks need a running Docker engine).
The Sphinx build resolves Python cross-references through the local extension
`docs/_ext/pyxrefindex.py`. It answers a search that Sphinx runs over all documented objects from
an index; the generated pages stay the same (see
[sphinx-doc/sphinx#11282](https://github.com/sphinx-doc/sphinx/issues/11282)). The extension is
only active for the Sphinx version it was verified with. After a Sphinx update, `TestPyXrefIndex`
in `tests/test_docsphinx.py` fails until the version in the extension is raised.
The documentation test builds with up to four parallel jobs (`sphinx-build -j`), and so do
`make docs` and `make read-docs`, which run this test. A parallel build can link a cross-reference
with an ambiguous name to another object of the same name than a build with one process.
CI runs every test exactly once, spread over several jobs:
- `test-shard`: the tests that do not start a server, in four shards of about equal runtime, each
with pytest-xdist on all cores of its runner.
- `test-server`: the tests with the `eos_server` marker, one after the other.
- `test-count`: fails if these parts do not add up to the tests of one plain run, or if the
marker of the server tests is no longer derived from the fixture.
- `test`: prints the coverage report of all parts. It is the required check and fails if one of
these jobs, `docs-test` or `docker-test` failed.
`make test-ci` runs the tests of the jobs `test-server`, `test-shard`, `docs-test` and
`docker-test` locally, with the markers and options of these jobs and one part after the other:
the server tests, the other tests with pytest-xdist on all cores (not split into shards), the
Sphinx build and the Docker checks. It prints the coverage report of the first two parts and stops
at the first part that fails. The browser tests of the `browser-test` job have their own target,
`make test-browser`.
The coverage report of the `test` job is combined from the parts. It differs from the report of
one plain run in a few lines, and not in exactly the same ones in every run: lines that are only
executed when a test finds state left by an earlier test of the same process. With pytest-xdist
the order of the tests in a worker changes from run to run. When the layout was introduced, three
runs missed 4523 to 4525 statements out of 26154, one plain run 4522.
`scripts/shard_test_files.py` distributes the test modules to the shards by the runtimes in
`scripts/test_durations.json`. Outdated runtimes only cost balance; a module without an entry
counts one second. To rebalance, download the `junit-shard-*` artifacts of a CI run and call
`uv run python scripts/shard_test_files.py --update junit-shard-*.xml`.
CI measures coverage with the `sys.monitoring` core of coverage.py (`COVERAGE_CORE=sysmon`).
The report is the same as with the default tracer, but a coverage run takes about a third less
time. Set the variable for local coverage runs as well. On Python 3.13 this core does not measure
branch coverage: with `--cov-branch`, coverage.py falls back to the default tracer.
Run the tests in parallel with `uv run pytest -n auto --dist loadgroup` (pytest-xdist). The tests
that start a real EOS or EOSdash server listen on fixed ports and must not run next to each
other. They carry the `eos_server` marker, set automatically for every test that uses the
`xprocess` fixture, and share one xdist group, which `--dist loadgroup` keeps on one worker.
Without `--dist loadgroup` these tests collide. Give a test that binds the ports without the
fixture the marker itself (`@pytest.mark.eos_server`).
### Follow Coding Standards ### Follow Coding Standards
Keep your code consistent with existing style and conventions. Keep your code consistent with existing style and conventions.
+3
View File
@@ -84,6 +84,7 @@ dev = [
"pytest==9.1.1", "pytest==9.1.1",
"pytest-asyncio==1.4.1", "pytest-asyncio==1.4.1",
"pytest-cov==7.1.0", "pytest-cov==7.1.0",
"pytest-xdist==3.8.0",
"pytest-xprocess==1.0.2", "pytest-xprocess==1.0.2",
"coverage==7.16.2", "coverage==7.16.2",
"pypdf==7.0.0", "pypdf==7.0.0",
@@ -165,7 +166,9 @@ pythonpath = [ "src", ]
testpaths = [ "tests", ] testpaths = [ "tests", ]
markers = [ markers = [
"docker: marks tests that require a local Docker engine", "docker: marks tests that require a local Docker engine",
"docs: marks the Sphinx documentation build test",
"browser: marks EOSdash tests that run in a headless browser (enable with --browser-test)", "browser: marks EOSdash tests that run in a headless browser (enable with --browser-test)",
"eos_server: marks tests that start an EOS or EOSdash server on the fixed ports (set for all tests using the xprocess fixture)",
] ]
filterwarnings = [ filterwarnings = [
# Treat pandas 4 deprecations in EOS code as errors; upstream callers remain visible. # Treat pandas 4 deprecations in EOS code as errors; upstream callers remain visible.
+154
View File
@@ -0,0 +1,154 @@
#!/usr/bin/env python3
"""Split the pytest modules into shards of about equal runtime.
CI runs the tests that do not start a server in several jobs ("shards"), see
``.github/workflows/pytest.yml``. This script prints the test modules of one shard::
python scripts/shard_test_files.py 4 0
The modules are distributed by their measured runtime, heaviest first, each to the shard
with the smallest load so far. The runtimes are stored in ``scripts/test_durations.json``
(seconds per module). A module without an entry counts one second. Every module ends up
in exactly one shard whatever the runtimes say, so stale runtimes cost balance only.
Update the runtimes from the junit reports of the shards of a CI run. Pass the reports of
all shards: the file is rewritten from them, and a module that is in none of them counts
one second again::
python scripts/shard_test_files.py --update junit-shard-*.xml
"""
import argparse
import json
import re
import sys
import xml.etree.ElementTree as ET
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]
DURATIONS_FILE = Path(__file__).resolve().with_name("test_durations.json")
DEFAULT_DURATION = 1.0
_JUNIT_MODULE = re.compile(r"^tests\.(test_[a-z0-9]+)")
def list_test_modules(repo_root: Path = REPO_ROOT) -> list[str]:
"""List the pytest modules directly in ``tests/``.
Subdirectories are not searched; there are none with test modules. The ``test-count``
job of ``pytest.yml`` fails if pytest collects a test that no shard runs.
Args:
repo_root: The root directory of the repository.
Returns:
The module paths relative to the repository root, sorted, with forward slashes.
"""
return sorted(
path.relative_to(repo_root).as_posix() for path in (repo_root / "tests").glob("test_*.py")
)
def load_durations(path: Path = DURATIONS_FILE) -> dict[str, float]:
"""Read the stored runtimes.
Args:
path: The JSON file with the seconds per module.
Returns:
The runtimes by module path; empty if the file does not exist.
"""
if not path.exists():
return {}
with path.open(encoding="utf-8") as fd:
return {str(name): float(seconds) for name, seconds in json.load(fd).items()}
def split(modules: list[str], durations: dict[str, float], shards: int) -> list[list[str]]:
"""Distribute the modules to shards of about equal runtime.
Args:
modules: The module paths to distribute.
durations: The runtime in seconds by module path.
shards: The number of shards.
Returns:
One list of module paths per shard. Every module is in exactly one of them.
Raises:
ValueError: If the number of shards is not positive.
"""
if shards < 1:
raise ValueError(f"The number of shards must be positive, got {shards}.")
load = [0.0] * shards
result: list[list[str]] = [[] for _ in range(shards)]
# Heaviest first; the module name breaks ties, so the result is deterministic.
for module in sorted(modules, key=lambda name: (-durations.get(name, DEFAULT_DURATION), name)):
lightest = min(range(shards), key=lambda index: (load[index], index))
result[lightest].append(module)
load[lightest] += durations.get(module, DEFAULT_DURATION)
return result
def durations_from_junit(reports: list[Path]) -> dict[str, float]:
"""Sum the test times of junit reports by pytest module.
Args:
reports: The junit XML files written by ``pytest --junitxml``.
Returns:
The runtime in seconds by module path, rounded to two decimals.
"""
seconds: dict[str, float] = {}
for report in reports:
for case in ET.parse(report).getroot().iter("testcase"):
match = _JUNIT_MODULE.match(case.get("classname", ""))
if match:
module = f"tests/{match.group(1)}.py"
seconds[module] = seconds.get(module, 0.0) + float(case.get("time") or 0.0)
return {module: round(value, 2) for module, value in sorted(seconds.items())}
def main(argv: list[str] | None = None) -> int:
"""Print the modules of one shard, or update the stored runtimes.
Args:
argv: The command line arguments; ``sys.argv[1:]`` if omitted.
Returns:
The process exit code.
"""
parser = argparse.ArgumentParser(
description="Split the pytest modules into shards of about equal runtime."
)
parser.add_argument("shards", nargs="?", type=int, help="number of shards")
parser.add_argument("index", nargs="?", type=int, help="shard to print, counted from 0")
parser.add_argument(
"--update",
nargs="+",
type=Path,
metavar="JUNIT_XML",
help="rewrite the stored runtimes from these junit reports",
)
args = parser.parse_args(argv)
if args.update:
durations = durations_from_junit(args.update)
if not durations:
parser.error("the junit reports contain no test of a tests/test_*.py module")
with DURATIONS_FILE.open("w", encoding="utf-8", newline="\n") as fd:
json.dump(durations, fd, indent=1)
fd.write("\n")
print(f"Wrote the runtimes of {len(durations)} modules to {DURATIONS_FILE}.")
return 0
if args.shards is None or args.index is None:
parser.error("give the number of shards and the index of the shard to print")
if not 0 <= args.index < args.shards:
parser.error(f"the shard index must be between 0 and {args.shards - 1}")
print(" ".join(split(list_test_modules(), load_durations(), args.shards)[args.index]))
return 0
if __name__ == "__main__":
sys.exit(main())
+136
View File
@@ -0,0 +1,136 @@
{
"tests/test_adapter.py": 0.13,
"tests/test_adapternodered.py": 0.22,
"tests/test_ai.py": 1.49,
"tests/test_cache.py": 5.97,
"tests/test_config.py": 1.38,
"tests/test_configabc.py": 4.69,
"tests/test_configmigrate.py": 0.93,
"tests/test_dataabccompact.py": 9.99,
"tests/test_dataabccontainer.py": 0.45,
"tests/test_dataabcprovider.py": 0.35,
"tests/test_dataabcrecord.py": 0.68,
"tests/test_dataabcsequence.py": 1.31,
"tests/test_dataabcsequencedb.py": 2.11,
"tests/test_database.py": 14.1,
"tests/test_databaseabc.py": 6.83,
"tests/test_datetimeutil.py": 7.63,
"tests/test_dependencywarnings.py": 0.19,
"tests/test_devicesprofilebattery.py": 4.47,
"tests/test_devicesprofilecurve.py": 0.36,
"tests/test_devicesprofileinverter.py": 0.57,
"tests/test_devicesprofilestore.py": 1.88,
"tests/test_devicessettingsbattery.py": 9.8,
"tests/test_devicessettingsinverter.py": 0.61,
"tests/test_doc.py": 0.08,
"tests/test_docstringrst.py": 4.41,
"tests/test_elecfeefixed.py": 0.68,
"tests/test_elecpriceabc.py": 0.14,
"tests/test_elecpriceakkudoktor.py": 0.45,
"tests/test_elecpriceenergycharts.py": 59.62,
"tests/test_elecpricefixed.py": 0.34,
"tests/test_elecpriceimport.py": 0.36,
"tests/test_elecpricesmard.py": 0.06,
"tests/test_elecpricetibber.py": 0.68,
"tests/test_emplan.py": 0.29,
"tests/test_emsnotify.py": 1.09,
"tests/test_eosdashcomponents.py": 0.15,
"tests/test_eosdashconfig.py": 0.12,
"tests/test_eosdashprediction.py": 1.48,
"tests/test_eosdashprofile.py": 20.24,
"tests/test_eosdashserver.py": 0.17,
"tests/test_eosdashsettings.py": 0.77,
"tests/test_eosdashwizard.py": 1.54,
"tests/test_feedintariffabc.py": 0.14,
"tests/test_feedintariffakkudoktor.py": 0.1,
"tests/test_feedintariffdvhubonline.py": 0.25,
"tests/test_feedintariffenergycharts.py": 69.21,
"tests/test_feedintarifffixed.py": 0.05,
"tests/test_feedintariffsmard.py": 0.03,
"tests/test_feedintarifftibber.py": 0.15,
"tests/test_footer.py": 0.06,
"tests/test_genetic0battery.py": 0.48,
"tests/test_genetic0inverter.py": 0.24,
"tests/test_genetic0inverterefficiency.py": 0.6,
"tests/test_genetic0optimize.py": 56.09,
"tests/test_genetic0params.py": 0.5,
"tests/test_genetic0runresult.py": 1.16,
"tests/test_genetic0simulation.py": 0.12,
"tests/test_genetic0translations.py": 0.09,
"tests/test_genetic0visualize.py": 1.82,
"tests/test_geneticacchargetotallimit.py": 0.29,
"tests/test_geneticbattery.py": 1.73,
"tests/test_geneticbatteryfullcharge.py": 3.49,
"tests/test_geneticcompletedevices.py": 1.06,
"tests/test_geneticcompleteoptimization.py": 5.75,
"tests/test_geneticcompletesimulation.py": 0.16,
"tests/test_geneticcompletesolution.py": 0.41,
"tests/test_geneticcompletetail.py": 7.59,
"tests/test_geneticcompletetimegrid.py": 1.62,
"tests/test_geneticconfigfrozenperrun.py": 0.73,
"tests/test_geneticconfigoptimizerequest.py": 3.87,
"tests/test_geneticendtoenddevices.py": 14.53,
"tests/test_geneticfitnesscachelimit.py": 3.08,
"tests/test_geneticforecastcoverage.py": 0.08,
"tests/test_genetichomeappliance.py": 1.02,
"tests/test_geneticinverter.py": 0.54,
"tests/test_geneticoptimize.py": 51.97,
"tests/test_geneticparallelevaluation.py": 10.87,
"tests/test_geneticparamsfeedin.py": 1.27,
"tests/test_geneticpdfapi.py": 1.62,
"tests/test_geneticseeding.py": 1.54,
"tests/test_geneticsimulation.py": 0.12,
"tests/test_geneticsimulation2.py": 0.07,
"tests/test_geneticvisualize.py": 9.89,
"tests/test_genticinverterefficiency.py": 0.61,
"tests/test_genticinverterefficiencycurve.py": 1.43,
"tests/test_gridinterpolator.py": 1.23,
"tests/test_heatpump.py": 0.06,
"tests/test_homeassistant.py": 0.52,
"tests/test_interpolator.py": 0.29,
"tests/test_lazyimports.py": 3.18,
"tests/test_loadakkudoktor.py": 0.98,
"tests/test_loadvrm.py": 0.1,
"tests/test_logging.py": 0.05,
"tests/test_measurement.py": 1.6,
"tests/test_measurementbatterycapacity.py": 0.57,
"tests/test_measurementenergy.py": 0.44,
"tests/test_measurementhousehold.py": 0.6,
"tests/test_optimizationcompatibility.py": 0.14,
"tests/test_prediction.py": 0.24,
"tests/test_predictionabc.py": 0.73,
"tests/test_priceabc.py": 0.2,
"tests/test_pvakkuadapt.py": 6.54,
"tests/test_pvakkuadaptquality.py": 0.26,
"tests/test_pvakkuadaptresponse.py": 0.12,
"tests/test_pvakkuadapttrend.py": 0.37,
"tests/test_pvforecast.py": 0.13,
"tests/test_pvforecastakkudoktor.py": 0.75,
"tests/test_pvforecastakkudoktorlocal.py": 13.08,
"tests/test_pvforecastakkudoktorlocalsnow.py": 3.05,
"tests/test_pvforecastforecastsolar.py": 0.8,
"tests/test_pvforecasthomeassistant.py": 0.24,
"tests/test_pvforecastimport.py": 0.39,
"tests/test_pvforecastpvlib.py": 1.47,
"tests/test_pvforecastpvnode.py": 0.31,
"tests/test_pvforecastsolcast.py": 0.25,
"tests/test_pvforecastvrm.py": 0.11,
"tests/test_pydantic.py": 0.99,
"tests/test_resterror.py": 0.33,
"tests/test_retentionmanager.py": 1.22,
"tests/test_scriptlintfilenames.py": 0.56,
"tests/test_server.py": 4.32,
"tests/test_servercleanup.py": 0.4,
"tests/test_serverendpoint.py": 0.03,
"tests/test_serverports.py": 0.5,
"tests/test_serverrestprofile.py": 1.78,
"tests/test_stringutil.py": 0.45,
"tests/test_terminalvalue.py": 0.21,
"tests/test_typingmodels.py": 0.45,
"tests/test_typingmypytooling.py": 25.45,
"tests/test_version.py": 0.94,
"tests/test_weatherbrightsky.py": 0.23,
"tests/test_weatherclearoutside.py": 0.61,
"tests/test_weatherimport.py": 0.38,
"tests/test_weatheropenmeteo.py": 0.43
}
+31 -1
View File
@@ -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: 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"): if config.getoption("--browser-test"):
return return
skip_browser = pytest.mark.skip(reason="browser test: enable with --browser-test") skip_browser = pytest.mark.skip(reason="browser test: enable with --browser-test")
+202 -1
View File
@@ -1,3 +1,4 @@
import importlib.util
import json import json
import os import os
import shutil import shutil
@@ -5,12 +6,17 @@ import subprocess
import sys import sys
import tempfile import tempfile
from pathlib import Path from pathlib import Path
from typing import Optional from types import ModuleType, SimpleNamespace
from typing import TYPE_CHECKING, Any, Optional, cast
import pytest import pytest
from akkudoktoreos.core.coreabc import singletons_init 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_PROJECT_ROOT = Path(__file__).absolute().parent.parent
DIR_BUILD = DIR_PROJECT_ROOT / "build" DIR_BUILD = DIR_PROJECT_ROOT / "build"
DIR_BUILD_DOCS = DIR_PROJECT_ROOT / "build" / "docs" 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" 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 os
import subprocess import subprocess
@@ -91,6 +103,7 @@ def sphinx_changed(version_and_hash) -> Optional[str]:
return new_hash return new_hash
@pytest.mark.docs
class TestSphinxDocumentation: class TestSphinxDocumentation:
"""Test class to verify Sphinx documentation generation. """Test class to verify Sphinx documentation generation.
@@ -102,6 +115,8 @@ class TestSphinxDocumentation:
"html", "html",
str(DIR_DOCS), str(DIR_DOCS),
str(DIR_BUILD_DOCS), str(DIR_BUILD_DOCS),
"-j",
str(SPHINX_JOBS),
] ]
def _cleanup_autosum_dirs(self): def _cleanup_autosum_dirs(self):
@@ -186,3 +201,189 @@ class TestSphinxDocumentation:
# Update stored hash # Update stored hash
HASH_FILE.parent.mkdir(parents=True, exist_ok=True) HASH_FILE.parent.mkdir(parents=True, exist_ok=True)
HASH_FILE.write_text(json.dumps({"hash": sphinx_changed}, indent=2)) 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 == []
+120
View File
@@ -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,
}
+2
View File
@@ -207,11 +207,13 @@ class TestServerStartStop:
drop_warnings = [record for record in records if "queue full" in record["message"]] 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" assert len(drop_warnings) == 1, "Expected one rate-limited warning for two dropped lines"
@pytest.mark.eos_server
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_server_start_eosdash(self, config_eos, monkeypatch, tmp_path): async def test_server_start_eosdash(self, config_eos, monkeypatch, tmp_path):
"""Test the EOSdash server startup from EOS. """Test the EOSdash server startup from EOS.
Do not use any fixture as this will make pytest the owner of the EOSdash port. 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: Tests that:
1. EOSdash starts via the supervisor 1. EOSdash starts via the supervisor
+90
View File
@@ -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
+23
View File
@@ -22,6 +22,7 @@ from akkudoktoreos.core.version import (
_version_date_hash, _version_date_hash,
collect_files, collect_files,
hash_files, hash_files,
version,
) )
from akkudoktoreos.utils.datetimeutil import to_datetime from akkudoktoreos.utils.datetimeutil import to_datetime
@@ -230,6 +231,28 @@ def test_version_date_hash() -> None:
# --- Test version helpers --- # --- 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): def test_version_non_dev(monkeypatch):
"""If VERSION_BASE does not end with 'dev', no hash digits are appended.""" """If VERSION_BASE does not end with 'dev', no hash digits are appended."""
monkeypatch.setattr("akkudoktoreos.core.version.VERSION_BASE", "0.2.0") monkeypatch.setattr("akkudoktoreos.core.version.VERSION_BASE", "0.2.0")
Generated
+24
View File
@@ -73,6 +73,7 @@ dev = [
{ name = "pytest" }, { name = "pytest" },
{ name = "pytest-asyncio" }, { name = "pytest-asyncio" },
{ name = "pytest-cov" }, { name = "pytest-cov" },
{ name = "pytest-xdist" },
{ name = "pytest-xprocess" }, { name = "pytest-xprocess" },
{ name = "scipy-stubs" }, { name = "scipy-stubs" },
{ name = "sphinx" }, { name = "sphinx" },
@@ -127,6 +128,7 @@ requires-dist = [
{ name = "pytest", marker = "extra == 'dev'", specifier = "==9.1.1" }, { name = "pytest", marker = "extra == 'dev'", specifier = "==9.1.1" },
{ name = "pytest-asyncio", marker = "extra == 'dev'", specifier = "==1.4.1" }, { name = "pytest-asyncio", marker = "extra == 'dev'", specifier = "==1.4.1" },
{ name = "pytest-cov", marker = "extra == 'dev'", specifier = "==7.1.0" }, { name = "pytest-cov", marker = "extra == 'dev'", specifier = "==7.1.0" },
{ name = "pytest-xdist", marker = "extra == 'dev'", specifier = "==3.8.0" },
{ name = "pytest-xprocess", marker = "extra == 'dev'", specifier = "==1.0.2" }, { name = "pytest-xprocess", marker = "extra == 'dev'", specifier = "==1.0.2" },
{ name = "python-fasthtml", specifier = "==0.14.14" }, { name = "python-fasthtml", specifier = "==0.14.14" },
{ name = "requests", specifier = "==2.34.2" }, { name = "requests", specifier = "==2.34.2" },
@@ -1033,6 +1035,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/de/15/545e2b6cf2e3be84bc1ed85613edd75b8aea69807a71c26f4ca6a9258e82/email_validator-2.3.0-py3-none-any.whl", hash = "sha256:80f13f623413e6b197ae73bb10bf4eb0908faf509ad8362c5edeb0be7fd450b4", size = 35604, upload-time = "2025-08-26T13:09:05.858Z" }, { url = "https://files.pythonhosted.org/packages/de/15/545e2b6cf2e3be84bc1ed85613edd75b8aea69807a71c26f4ca6a9258e82/email_validator-2.3.0-py3-none-any.whl", hash = "sha256:80f13f623413e6b197ae73bb10bf4eb0908faf509ad8362c5edeb0be7fd450b4", size = 35604, upload-time = "2025-08-26T13:09:05.858Z" },
] ]
[[package]]
name = "execnet"
version = "2.1.2"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/bf/89/780e11f9588d9e7128a3f87788354c7946a9cbb1401ad38a48c4db9a4f07/execnet-2.1.2.tar.gz", hash = "sha256:63d83bfdd9a23e35b9c6a3261412324f964c2ec8dcd8d3c6916ee9373e0befcd", size = 166622, upload-time = "2025-11-12T09:56:37.75Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/ab/84/02fc1827e8cdded4aa65baef11296a9bbe595c474f0d6d758af082d849fd/execnet-2.1.2-py3-none-any.whl", hash = "sha256:67fba928dd5a544b783f6056f449e5e3931a5c378b128bc18501f7ea79e296ec", size = 40708, upload-time = "2025-11-12T09:56:36.333Z" },
]
[[package]] [[package]]
name = "fastapi" name = "fastapi"
version = "0.162.0" version = "0.162.0"
@@ -3268,6 +3279,19 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/9d/7a/d968e294073affff457b041c2be9868a40c1c71f4a35fcc1e45e5493067b/pytest_cov-7.1.0-py3-none-any.whl", hash = "sha256:a0461110b7865f9a271aa1b51e516c9a95de9d696734a2f71e3e78f46e1d4678", size = 22876, upload-time = "2026-03-21T20:11:14.438Z" }, { url = "https://files.pythonhosted.org/packages/9d/7a/d968e294073affff457b041c2be9868a40c1c71f4a35fcc1e45e5493067b/pytest_cov-7.1.0-py3-none-any.whl", hash = "sha256:a0461110b7865f9a271aa1b51e516c9a95de9d696734a2f71e3e78f46e1d4678", size = 22876, upload-time = "2026-03-21T20:11:14.438Z" },
] ]
[[package]]
name = "pytest-xdist"
version = "3.8.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "execnet" },
{ name = "pytest" },
]
sdist = { url = "https://files.pythonhosted.org/packages/78/b4/439b179d1ff526791eb921115fca8e44e596a13efeda518b9d845a619450/pytest_xdist-3.8.0.tar.gz", hash = "sha256:7e578125ec9bc6050861aa93f2d59f1d8d085595d6551c2c90b6f4fad8d3a9f1", size = 88069, upload-time = "2025-07-01T13:30:59.346Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/ca/31/d4e37e9e550c2b92a9cbc2e4d0b7420a27224968580b5a447f420847c975/pytest_xdist-3.8.0-py3-none-any.whl", hash = "sha256:202ca578cfeb7370784a8c33d6d05bc6e13b4f25b5053c30a152269fd10f0b88", size = 46396, upload-time = "2025-07-01T13:30:56.632Z" },
]
[[package]] [[package]]
name = "pytest-xprocess" name = "pytest-xprocess"
version = "1.0.2" version = "1.0.2"