Skip to content

02 — Running Tests

The one rule: tests run in a Linux container

pytest-homeassistant-custom-component imports fcntl, a Unix-only stdlib module. It cannot run on Windows Python — you get ModuleNotFoundError: No module named 'fcntl'. Every test run goes through a python:3.14-slim Docker container.

There is a runner for this:

scripts\test.bat

It runs pytest in the pre-baked eufy-vacuum-test image (the HA test deps baked in — see the locked-in image below), mounting the repo at /workspace and passing through whatever arguments you give it. No pip install per run.

@echo off
REM build the image once if it's missing, then reuse it
docker image inspect eufy-vacuum-test >nul 2>&1
if errorlevel 1 call "%~dp0build-test-image.bat" || exit /b 1
docker run --rm ^
  -v "%~dp0..:/workspace" ^
  -w /workspace ^
  eufy-vacuum-test ^
  python -m pytest %*

Examples

scripts\test.bat                                          REM default testpaths (unit + integration + core + adapters)
scripts\test.bat tests/integration/test_config_flow.py -v
scripts\test.bat --no-cov -k test_setup_flow
scripts\test.bat tests/unit                               REM just the unit layer
scripts\test.bat tests/adapters                           REM the adapter suite alone (it IS in the default now)
scripts\test.bat tests/replay                             REM the replay harness (the one path NOT in the default)
scripts\test.bat tests --no-cov -p no:cacheprovider --tb=short   REM the exact CI behavior gate

CI (.github/workflows/tests.yml) runs python -m pytest tests --no-cov -p no:cacheprovider --tb=short, which collects the whole tests/ tree: all five directories — tests/unit, tests/integration, tests/core, tests/adapters, tests/replay — and the seven ratchet files that sit directly under tests/. Since 2026-11-11 the default testpaths names four of those five directories and no loose files, so the inner loop and the gate disagree about tests/replay (28 cases) and those top-level ratchets (93) — 121 cases in all. The ratchets are the larger half, and test_docs_ratchet.py is one of them, so the inner loop cannot see the gate that requires a new test file to be documented in the same commit.

Running it by hand

The suite needs Linux: pytest_homeassistant_custom_component pulls in homeassistant.runner, which imports fcntl. On Linux or macOS, install requirements_test.txt and run pytest directly. On Windows, run it in a container.

Linux / macOS

pip install -r requirements_test.txt
python -m pytest tests --no-cov

Windows — and the two traps

  1. Use PowerShell, not Git Bash. Git Bash rewrites the -w /workspace argument (POSIX-path mangling turns /workspace into a Windows path), and the container fails to find the working directory.
  2. Quote the volume mount, and give it an absolute path.
docker run --rm `
  -v "${PWD}:/workspace" `
  -w /workspace `
  eufy-vacuum-test `
  python -m pytest tests -q --no-header --no-cov

${PWD} resolves to the repository root when the command is run from there. Substitute the absolute path if you invoke it from anywhere else.

(If you haven't built the image yet, run scripts\build-test-image.bat first, or swap eufy-vacuum-test for python:3.14-slim and prefix the command with pip install -q -r requirements_test.txt && for a one-off zero-setup run.)

Common flag recipes

Goal Flags
Fast iteration on one file, no coverage tests/integration/test_x.py -q --no-header --no-cov
Run one test by name -k test_name_substring
Stop at first failure -x
Short tracebacks --tb=short
Coverage for specific modules only see Narrowing coverage to one module — a command-line --cov cannot do it
Disable pytest cache (clean container) -p no:cacheprovider

--no-cov is worth using during iteration — coverage instrumentation slows the run and clutters the output. The default addopts always turns coverage on, so pass --no-cov to suppress it.

Reading coverage

The default run prints a term-missing table (uncovered line numbers per file) only — no HTML report is written. The addopts in pytest.ini enable just --cov-report=term-missing and --cov-branch. To get an HTML report, ask for one explicitly: pass --cov-report=html:htmlcov_scratch for a disposable report, or --cov-report=html:htmlcov for the canonical regen. (Keeping htmlcov/ explicit-only means an incidental or sub-agent coverage run can never clobber it.) Both htmlcov/ and the .coverage data file are gitignored, as is any coverage*.json. That pattern was coverage.json exactly until 2026-11-07, so an ad-hoc --cov-report=json:coverage_mymodule.json left a multi-MB untracked file sitting one git add -A from the repo.

Refreshing the numbers in these docs

The coverage percentages and test counts scattered through the testing docs (per-module tables, the per-subsystem Cov column, the headline figures) are maintained by a script so they don't drift. Run it inside the container:

docker run --rm -v "<repo>:/workspace" -w /workspace eufy-vacuum-test \
  python scripts/update_test_docs.py

It runs coverage, then rewrites only the numeric fields in place — prose, module lists, and gap notes are never touched. Add --dry-run to preview, or --no-run to reuse an existing coverage.json. Review the diff before committing.

Per-file vs combined coverage

A module's coverage number depends on which test files you run. Example: the pure-function helpers at the top of learning/job_finalizer.py are covered by tests/unit/test_learning_job_finalizer.py. If you run only the integration file, those lines show as missed and the percentage drops. To get the true number for a module, run all files that exercise it:

scripts\test.bat tests/integration/test_learning_services.py tests/unit/test_learning_job_finalizer.py

The default term-missing table is already per-file, so the row for learning/job_finalizer.py is the number you want — you do not need a --cov flag to single it out, and as the next section explains, one would not work anyway.

Narrowing coverage to one module

A command-line --cov does not narrow anything. The flag is action="append", so it ADDS a source to the one pytest.ini already sets — measured 2026-11-07, the table still listed 205 files. .coveragerc sets source as well, so there are two package-wide sources to displace, not one.

Three forms, and what each actually does — all measured:

Form Effect
--cov=custom_components/eufy_vacuum/learning valid (a directory)
--cov=.../learning/external_run.py runs, but collects nothing: "No data to report" — a single file is not a usable source
--cov=custom_components.eufy_vacuum.learning.external_run refused at startup. Dotted sources reload NumPy and redden 46 unrelated tests

That last one is the trap, and tests/conftest.py now refuses it with an explanation instead of letting it produce a screenful of unrelated failures. Coverage resolves a source with no path separator by importing it (importlib.util.find_spec), which imports the package tree mid-session. NumPy is then imported a second time — it says so itself, "The NumPy module was reloaded" — and its compiled reduce still compares against the _NoValue sentinel it cached on the first import, so every ndarray.sum() raises TypeError: float() argument must be a string or a real number, not '_NoValueType'.

The casualties are the numpy-backed mapping and segmentor tests, which have nothing to do with the module being measured — that mismatch is what makes the trap expensive. The Python-level sentinel stays self-consistent across the reload (numpy._NoValue is numpy._globals._NoValue holds either way), so the obvious probe for a duplicate module reports nothing wrong. Mechanism recorded at tests/conftest.py#CNP337CY (offending_cov_sources), pinned by tests/unit/test_cov_source_guard.py (COVG-1..8).

A slash-bearing source is never refused, even when it is wrong: the two forms above that collect nothing are a documentation problem, not something to fail a run over.

To genuinely measure one subtree, drop both package-wide sources:

docker run --rm -v "<repo>:/workspace" -w /workspace eufy-vacuum-test \
  python -m pytest tests/integration/test_manager_external_finalize.py \
  -o addopts="" --cov-config=/dev/null --cov-branch \
  --cov=custom_components/eufy_vacuum/learning --cov-report=term-missing

-o addopts="" drops the pytest.ini source and --cov-config=/dev/null drops .coveragerc's. Measured: 5040 statements instead of 29985, with a per-file row for every module under learning/. Usually not worth the trouble — the whole-package table is already per-file, and coverage.json carries the same data per module.

The image-processing stack (numpy / scipy / Pillow)

The mapping segmentor pipeline depends on numpy, scipy, and Pillow:

  • numpy arrives transitively through Home Assistant core, so it is always present.
  • scipy and Pillow are explicit entries in requirements_test.txt — they are not pulled in by HA core. Without them the scipy/Pillow-dependent mapping code (segment_primitives transforms, mask_edge_band, estimate_alignment, the eufy_cv segmentor) can't be exercised.

Even so, scipy-only code paths should guard with pytest.importorskip("scipy.ndimage") so a test file degrades to a skip rather than an error if the stack is ever stripped from the environment:

def test_mask_edge_band(np):
    pytest.importorskip("scipy.ndimage")
    ...

The locked-in image (no pip install per run)

Installing requirements_test.txt fresh in the container costs ~1-2 min — far longer than the suite itself (well under a minute). So the deps are baked into a local image once and reused:

File Role
scripts/test.Dockerfile python:3.14-slim + pip install -r requirements_test.txt
scripts/build-test-image.bat builds/rebuilds the eufy-vacuum-test image
scripts/test.bat runs pytest in that image (auto-builds it on first run)

Lifecycle:

  1. First run — scripts\test.bat sees no eufy-vacuum-test image and builds it once (the only slow run).
  2. Every run after — reuses the image, so a test run is just pytest with no install step.
  3. When the RESOLVED versions drift — rebuild with scripts\build-test-image.bat (or delete the image and let test.bat rebuild it). Not "when requirements_test.txt changes": every requirement in it is a >= floor and CI pip-installs fresh on every job, so the file can sit untouched for weeks while a baked image and CI diverge by a whole Home Assistant version. That is how a local 4921-PASSED once stood against a RED CI run. Check what the image actually holds before trusting a local green:
docker run --rm eufy-vacuum-test python -c "from importlib.metadata import version; print(version('homeassistant'), version('pytest-homeassistant-custom-component'))"

The script passes --pull --no-cache, and that is load-bearing: on an unchanged requirements file Docker otherwise serves the cached pip layer and reports a successful rebuild that changed nothing — measured 2026-10-26, where a plain rebuild left the image on homeassistant 2026.10.2 / pytest-homeassistant-custom-component 0.13.373 while a fresh install resolved 2026.10.4 / 0.13.375.

Grade the image against a fresh resolve, not against PyPI's newest. pytest-homeassistant-custom-component pins homeassistant, pytest, pytest-asyncio and numpy exactly, so "pytest 9.1.1 is out" is not drift — 0.13.375 pins 9.0.3, and that is what CI installs too. Pillow is not pinned there and still resolves to 12.3.0 rather than 13.0.0 on python:3.14-slim (wheel availability). Comparing the image to PyPI latest therefore reports drift that does not exist, and hides the two packages that do move.

The image is ~1.4 GB and lives only on your machine — it is not committed; only the Dockerfile + scripts are. Anyone who clones the repo gets the same baked environment from the first scripts\test.bat.

Iterating tightly? Run a single file (scripts\test.bat tests/unit/test_x.py --no-cov) — the image is already warm, so the only cost is the test itself.