Files
voculinux/tests/test_installer_python_selection.py
T
Sergey SilaevandGitHub 582d494633 chore(build): uv tooling, a Python 3.11 floor, and verified model downloads (epic #701, phases 2.5 & 5) (#713)
* chore(build): migrate justfile tooling to uv

All recipes now run through 'uv run' against .venv, with a shared
DEV_EXTRAS variable (dev + vad) because uv syncs the environment
exactly and would otherwise uninstall the dev tools between
recipes. 'deps' installs dev+vad; new 'deps-all' covers every
extra. 'build' switches to 'uv build'; 'version' uses --no-sync.

Bump [tool.uv] required-version to >=0.12,<0.13 for uv 0.12.x, and
raise the mypy python_version target to 3.12: mypy 1.19 in the lock
cannot target 3.9 and numpy 2.x stubs need a 3.12 target to parse
(mypy is not run in CI or pre-commit; this only affects 'just
typecheck').

* fix(tests): isolate test runs from real XDG state; fix Arch model-path crash

Local test runs failed en masse (185 failures) while CI stayed
green: tests picked up the developer's real ~/.local/share/vocalinux
models via the default XDG paths and switched IBus/keyboard code
paths through the desktop session env (XDG_CURRENT_DESKTOP/
XDG_SESSION_TYPE on GNOME/Wayland, issue #478 branches). conftest
now points XDG base dirs at a throwaway session-wide directory and
clears session variables at import time, mirroring a fresh CI
runner (paths like MODELS_DIR freeze at first import during
collection, so fixture-time isolation is too late).

Also guard the Arch branch of _get_system_model_paths(): it removed
/usr/local/share/vocalinux/models unconditionally and crashed with
ValueError on Arch hosts when a custom XDG_DATA_DIRS never added
that path. Add regression tests, and make the lock-file test assert
the actual $XDG_DATA_HOME/vocalinux contract instead of the
hardcoded ~/.local/share default.

* fix(tests): keep the IBus engine double a plain class

Python 3.14's unittest.mock re-instantiates a user subclass when it builds
child mocks (klass(name=...)). VocalinuxEngine inherits from whatever
IBus.Engine resolves to, and the test module bound that to the MagicMock
class itself, so every engine instantiation raised

    TypeError: VocalinuxEngine.__init__() got an unexpected keyword argument 'name'

on 3.14 while passing on 3.13. Replace it with a plain stand-in class that
still hands out per-instance MagicMocks for the IBus API surface the engine
touches.

The same pattern remains in test_ibus_engine.py, test_ibus_engine_utils.py,
test_ibus_active_engine_guard.py and test_ibus_xkb_wayland.py; those never
instantiate the engine, so they are unaffected for now.

* fix(install): build the venv from the system Python

install.sh looked up a bare `python3` from PATH. Started from an activated
virtualenv — a shell left in uv's .venv after `just deps` — it built venv/
from that interpreter, where distro PyGObject is invisible even with
--system-site-packages, and the run aborted with

    Distro PyGObject (python3-gi / python3-gobject) is not importable in the venv.

A mismatched venv/ then survived every retry, because the installer reuses
whatever venv it finds.

- drop an inherited VIRTUAL_ENV (and its bin from PATH) before any
  interpreter lookup
- select the interpreter explicitly: $SYSTEM_PYTHON (default
  /usr/bin/python3) or PATH python3, preferring one that can import gi,
  and create the venv with it instead of `python3`
- recreate venv/ when it was built by a different interpreter
- name the interpreter in the PyGObject guard's error

Documents the two environments (uv's .venv for tooling, venv/ for the
installed app) in CONTRIBUTING, the justfile header and AGENTS.md, and adds
the mismatch symptom to the INSTALL troubleshooting section.

* chore(python): raise the supported floor to 3.11

requires-python promised 3.9 while the CI matrix ran 3.9/3.10/3.11/3.13,
the classifiers advertised up to 3.14, mypy targeted 3.12 and install.sh
enforced 3.9 — five different answers to "which Python does this support".

Settle on 3.11 everywhere: pyproject (requires-python, classifiers, black
targets), install.sh's MIN_VERSION, check-system-deps.sh, the distro package
map, the CI matrix (now 3.11-3.14, matching the classifiers), the release and
nightly workflows, and the docs.

mypy now targets the floor instead of 3.12, so type checking covers what we
promise; numpy 2.x ships stubs in 3.12 syntax that a 3.11 target cannot
parse, so its imports are skipped. (mypy has 71 pre-existing errors either
way; no CI job gates on it.)

uv.lock and the requirements/* exports are regenerated — dropping 3.9/3.10
removes most of the version-conditional resolution branches.

tests/test_python_version_policy.py pins the invariant: install.sh's floor,
requires-python, the classifiers and the CI matrix must agree.

* ci: run lint and tests from uv.lock

The lock file and the hash-pinned exports were not enforced anywhere: CI
still built a venv by hand and installed unpinned `PyGObject` plus
`-e ".[dev,vad]"`, so the tool versions it checked against had nothing to do
with the ones `just lint` uses locally.

Both Python jobs now use astral-sh/setup-uv and run through `uv sync
--locked` / `uv run --locked`, which also fails the build when uv.lock drifts
from pyproject.toml.

Partially covers phase 5 of #701 (tests install from the lock, lock freshness
gate); trusted publishing, artifact checksums and action SHA pinning are
still open there.

* ci: lint from a dedicated dependency group

The lint job failed on this branch: `uv run --extra dev` syncs the whole
project, so it tried to build pyaudio from source on a runner that installs
no system dependencies.

    src/pyaudio/device_api.c:9:10: fatal error: portaudio.h: No such file or directory

Move black/isort/flake8 out of the `dev` extra into a `lint` dependency
group. CI runs `uv run --locked --only-group lint`, which installs the three
pure-Python tools and skips the project entirely — no portaudio or
girepository headers needed. `just deps` and DEV_EXTRAS request the group
alongside the dev extras, so the local environment still carries test and
lint tooling at once and `just lint` matches CI version for version.

pre-commit is unaffected: its hooks pin their own tool versions upstream.

* fix(install): never configure an engine the venv cannot import

vosk became an optional extra in #705, but the installer still writes
`"engine": "vosk"` into config.json on the whisper.cpp fallback path even
when installing the extra only produced a warning. config.json also survives
reinstalls — every writer guards on "file does not exist" — so an engine
picked by an earlier attempt outlives the venv that supported it. Either way
Vocalinux dies at startup:

    ModuleNotFoundError: No module named 'vosk'

- the fallback now writes the vosk config only when `import vosk` actually
  succeeds, and otherwise leaves the engine configuration alone
- a new verify_configured_engine() runs near the end of the install: if
  config.json selects vosk and the venv cannot import it, it says so and
  prints both fixes instead of leaving a broken install behind

* feat(models): verify every model download against a pinned digest

Pins a sha256/md5 per downloadable speech model in
src/vocalinux/utils/model_checksums.txt and verifies against it in both
install.sh and the runtime downloaders, before the file is moved into place.
Verification fails closed. Covers phase 2.5 of #701; see the PR for details.

* docs(agents): rebase AGENTS.md onto the #727 rewrite

* fix(install): hash models that are already on disk instead of trusting them

* refactor(models): one download path per engine, and fix Whisper's

* docs(install): drop distros that cannot meet the 3.11 floor

* docs: retire the distros and Python versions the 3.11 floor rules out

* fix(install): abort instead of warning when Python is below the floor

* fix(install): fall back to the system Python, not the one on PATH

* fix(install): match an existing venv by installation, not by X.Y

* fix(install): repair a config naming an engine the venv cannot import

* fix(models): pin VOSK by the sha256 of bytes we fetched, not upstream's md5

* fix(justfile): request the dev set in every recipe that syncs

* test(version): scan the docs and website trees for a stale Python floor

* docs: correct the stale model-checksum and distro claims

* fix(models): stamp the VOSK tree the app extracts, as the installer does

* fix(install): replace an unverified VOSK model only once its successor is ready

* docs(install): align the Fedora floor with the rest of the tree

* test(install): drop an f-string with no placeholders

* test(models): stub the downloader probe the VOSK installer test relies on

* docs: drop the long dashes from two model-checksum comments

* fix(install): gate on the interpreter, not on the distro release label

* fix(justfile): export the lint group into requirements/dev.txt

* fix(models): unpack the VOSK tree into staging and stamp it before the swap

* fix(whisper): adopt a checkpoint an earlier release stored under the catalog name

* docs(settings): state what a stray Whisper copy really means for deletion

* fix(models): hash a whisper.cpp model found on disk before it reaches ctypes

* docs(contributing): stop telling readers to uninstall their linters

* fix(install): stop warning off distros the project documents as supported

* docs(distros): file the supported derivatives under supported
2026-08-24 00:25:06 -07:00

355 lines
14 KiB
Python

"""Behavioral tests for the installer's Python interpreter selection.
Regression cover for the "Distro PyGObject is not importable in the venv"
failure: running install.sh from an activated virtualenv (e.g. uv's .venv left
active after `just deps`) made it build venv/ from that interpreter, where the
distro's gi is invisible.
"""
import re
import subprocess
from pathlib import Path
import pytest
INSTALL_SH = Path(__file__).resolve().parents[1] / "install.sh"
PRELUDE = """
set -uo pipefail
print_info() { echo "INFO: $*"; }
print_warning() { echo "WARNING: $*"; }
print_error() { echo "ERROR: $*"; }
print_success() { echo "SUCCESS: $*"; }
command_exists() { command -v "$1" >/dev/null 2>&1; }
"""
def _source(*functions: str) -> str:
"""Source the named function definitions out of install.sh."""
return "\n".join(
f"source <(sed -n '/^{name}() {{$/,/^}}$/p' \"{INSTALL_SH}\")" for name in functions
)
def _run(script: str) -> subprocess.CompletedProcess:
return subprocess.run(
["bash", "-c", PRELUDE + script], capture_output=True, text=True, timeout=30
)
def _fake_python(path: Path, version: str, has_gi: bool, base_prefix: str = "") -> Path:
"""Create a stub interpreter answering the probes install.sh runs.
``base_prefix`` defaults to the stub's own directory, so two stubs are
distinct installations unless they are told to share one.
"""
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(
"#!/bin/bash\n"
'if [[ "$*" == *"sys.version_info"* ]]; then\n'
f' echo "{version}"\n'
" exit 0\n"
"fi\n"
'if [[ "$*" == *"sys.base_prefix"* ]]; then\n'
f' echo "{base_prefix or path.parent}"\n'
" exit 0\n"
"fi\n"
'if [[ "$*" == *"import gi"* ]]; then\n'
f" exit {0 if has_gi else 1}\n"
"fi\n"
"exit 0\n"
)
path.chmod(0o755)
return path
class TestDeactivateInheritedVirtualenv:
def test_removes_active_venv_from_path(self, tmp_path):
venv = tmp_path / "venv"
(venv / "bin").mkdir(parents=True)
script = f"""
{_source("deactivate_inherited_virtualenv")}
export VIRTUAL_ENV="{venv}"
export PATH="{venv}/bin:/usr/bin:/bin"
deactivate_inherited_virtualenv
echo "PATH=$PATH"
echo "VIRTUAL_ENV=${{VIRTUAL_ENV:-<unset>}}"
"""
result = _run(script)
assert "PATH=/usr/bin:/bin" in result.stdout
assert "VIRTUAL_ENV=<unset>" in result.stdout
def test_removes_trailing_slash_venv_and_repeats(self, tmp_path):
venv = tmp_path / "venv"
(venv / "bin").mkdir(parents=True)
script = f"""
{_source("deactivate_inherited_virtualenv")}
export VIRTUAL_ENV="{venv}/"
export PATH="{venv}/bin:/usr/bin:{venv}/bin:/bin"
deactivate_inherited_virtualenv
echo "PATH=$PATH"
"""
result = _run(script)
assert "PATH=/usr/bin:/bin" in result.stdout
def test_no_active_venv_leaves_path_alone(self):
script = f"""
{_source("deactivate_inherited_virtualenv")}
unset VIRTUAL_ENV
export PATH="/usr/bin:/bin"
deactivate_inherited_virtualenv
echo "PATH=$PATH"
"""
result = _run(script)
assert "PATH=/usr/bin:/bin" in result.stdout
assert "WARNING" not in result.stdout
class TestSelectPythonInterpreter:
@staticmethod
def _select(path_python: Path, system_python: Path, min_version: str = "3.9") -> str:
script = f"""
PYTHON_CMD="python3"
SYSTEM_PYTHON="{system_python}"
{_source("python_version_of", "python_version_at_least", "python_has_gi", "select_python_interpreter")}
# Keep the system bin dirs: the fake interpreters shadow python3, while
# sort/head that select_python_interpreter relies on stay reachable.
export PATH="{path_python.parent}:/usr/bin:/bin"
select_python_interpreter "{min_version}" && echo "SELECTED=$PYTHON_CMD" || echo "SELECT_FAILED"
"""
return _run(script).stdout
def test_prefers_system_python_when_path_python_lacks_gi(self, tmp_path):
# The reported failure: PATH points at uv's 3.13 venv without gi while
# the distro built PyGObject for the system 3.14.
path_python = _fake_python(tmp_path / "pathbin" / "python3", "3.13", has_gi=False)
system_python = _fake_python(tmp_path / "usrbin" / "python3", "3.14", has_gi=True)
assert f"SELECTED={system_python}" in self._select(path_python, system_python)
def test_keeps_path_python_when_it_has_gi(self, tmp_path):
path_python = _fake_python(tmp_path / "pathbin" / "python3", "3.14", has_gi=True)
system_python = _fake_python(tmp_path / "usrbin" / "python3", "3.14", has_gi=True)
assert f"SELECTED={path_python}" in self._select(path_python, system_python)
def test_falls_back_to_the_system_python_when_no_candidate_has_gi(self, tmp_path):
# gi is usually installed later in the same run, so the fallback has to
# pick the interpreter that PyGObject will land on. Picking the PATH one
# here is exactly the venv-cannot-import-gi bug this file covers.
path_python = _fake_python(tmp_path / "pathbin" / "python3", "3.13", has_gi=False)
system_python = _fake_python(tmp_path / "usrbin" / "python3", "3.14", has_gi=False)
stdout = self._select(path_python, system_python)
assert f"SELECTED={system_python}" in stdout
def test_falls_back_to_path_python_when_the_system_one_is_too_old(self, tmp_path):
"""Preferring the system interpreter must not override the floor."""
path_python = _fake_python(tmp_path / "pathbin" / "python3", "3.12", has_gi=False)
system_python = _fake_python(tmp_path / "usrbin" / "python3", "3.9", has_gi=False)
stdout = self._select(path_python, system_python, min_version="3.11")
assert f"SELECTED={path_python}" in stdout
assert "SELECTED=python3" not in stdout
def test_skips_python_below_minimum_version(self, tmp_path):
too_old = _fake_python(tmp_path / "pathbin" / "python3", "3.6", has_gi=True)
system_python = _fake_python(tmp_path / "usrbin" / "python3", "3.14", has_gi=False)
assert f"SELECTED={system_python}" in self._select(too_old, system_python)
def test_reports_failure_when_no_python_exists(self, tmp_path):
empty_bin = tmp_path / "empty"
empty_bin.mkdir()
script = f"""
PYTHON_CMD="python3"
SYSTEM_PYTHON="{tmp_path}/missing-python3"
{_source("python_version_of", "python_version_at_least", "python_has_gi", "select_python_interpreter")}
export PATH="{empty_bin}"
select_python_interpreter "3.9" && echo "SELECTED=$PYTHON_CMD" || echo "SELECT_FAILED"
"""
assert "SELECT_FAILED" in _run(script).stdout
class TestVenvMatchesSelectedPython:
def test_venv_built_from_the_selected_interpreter(self, tmp_path):
base = str(tmp_path / "usr")
venv_python = _fake_python(
tmp_path / "venv" / "bin" / "python", "3.14", has_gi=True, base_prefix=base
)
selected = _fake_python(tmp_path / "usr" / "python3", "3.14", has_gi=True, base_prefix=base)
script = f"""
VENV_DIR="{venv_python.parents[1]}"
PYTHON_CMD="{selected}"
{_source("python_base_prefix", "venv_matches_selected_python")}
venv_matches_selected_python && echo "MATCH" || echo "MISMATCH"
"""
result = _run(script)
assert "MATCH" in result.stdout
def test_stale_venv_from_other_interpreter(self, tmp_path):
venv_python = _fake_python(tmp_path / "venv" / "bin" / "python", "3.13", has_gi=False)
selected = _fake_python(tmp_path / "usr" / "python3", "3.14", has_gi=True)
script = f"""
VENV_DIR="{venv_python.parents[1]}"
PYTHON_CMD="{selected}"
{_source("python_base_prefix", "venv_matches_selected_python")}
venv_matches_selected_python && echo "MATCH" || echo "MISMATCH"
"""
result = _run(script)
assert "MISMATCH" in result.stdout
def test_same_version_from_a_different_installation_is_stale(self, tmp_path):
"""A distro 3.12 and a pyenv/uv 3.12 are not interchangeable."""
venv_python = _fake_python(
tmp_path / "venv" / "bin" / "python",
"3.12",
has_gi=False,
base_prefix=str(tmp_path / "pyenv"),
)
selected = _fake_python(
tmp_path / "usr" / "python3", "3.12", has_gi=True, base_prefix="/usr"
)
script = f"""
VENV_DIR="{venv_python.parents[1]}"
PYTHON_CMD="{selected}"
{_source("python_base_prefix", "venv_matches_selected_python")}
venv_matches_selected_python && echo "MATCH" || echo "MISMATCH"
"""
result = _run(script)
assert "MISMATCH" in result.stdout
def test_missing_venv_python(self, tmp_path):
selected = _fake_python(tmp_path / "usr" / "python3", "3.14", has_gi=True)
script = f"""
VENV_DIR="{tmp_path}/nonexistent"
PYTHON_CMD="{selected}"
{_source("python_base_prefix", "venv_matches_selected_python")}
venv_matches_selected_python && echo "MATCH" || echo "MISMATCH"
"""
result = _run(script)
assert "MISMATCH" in result.stdout
class TestTheFloorIsTheInterpreterNotTheReleaseLabel:
"""Any distro that ships a new enough Python must be installable.
The installer used to reject the Ubuntu family on `VERSION_ID` alone. That
label is not the requirement and derivatives do not share Ubuntu's numbering:
Linux Mint 22 and elementary OS 8 are built on Ubuntu 24.04 and ship Python
3.12, yet report "22" and "8", which sort below "24.04".
"""
# The two shapes that matter, both handed an interpreter at 3.12: a label
# that sorts below the base release, and one that is not a release number at
# all. Pop!_OS and Kubuntu need no case of their own — they use Ubuntu's
# numbering, so they were never the ones being turned away.
DERIVATIVES = [
("linuxmint", "22"),
("elementary", "8"),
]
#: Family name in install.sh -> how docs/DISTRO_COMPATIBILITY.md spells it.
SUPPORTED_FAMILIES = {
"ubuntu": "Ubuntu",
"debian": "Debian",
"fedora": "Fedora",
"arch": "Arch Linux",
"suse": "openSUSE",
}
def test_a_documented_family_is_never_met_with_untested(self):
"""Fedora, Arch and openSUSE used to get the Ubuntu/Debian-only warning.
That warning ends in a y/n prompt which exits on "n", so a distro the
project documents as supported, and in Fedora's case builds in the distro
matrix, could be talked out of installing.
"""
source = INSTALL_SH.read_text(encoding="utf-8")
block = source[source.index("# Check compatibility") :]
block = block[: block.index("\nesac\n")]
arms = set()
for line in block.splitlines():
match = re.fullmatch(r"\s*([a-z|]+)\)", line)
if match:
arms.update(match.group(1).split("|"))
assert arms == set(self.SUPPORTED_FAMILIES), f"unexpected support tiers: {sorted(arms)}"
def test_the_installer_and_the_compatibility_doc_agree(self):
doc = (INSTALL_SH.parent / "docs" / "DISTRO_COMPATIBILITY.md").read_text(encoding="utf-8")
supported = doc[: doc.index("## Experimental Support")]
missing = [
name for name in self.SUPPORTED_FAMILIES.values() if f"| {name} |" not in supported
]
assert not missing, f"install.sh calls these supported, the doc does not: {missing}"
def test_no_supported_distro_is_filed_under_experimental(self):
"""The two tables have to mean what their headings say.
Linux Mint, Pop!_OS, elementary, Zorin, Manjaro and EndeavourOS sat in
"Experimental Support" while marked "Good Support", which is where the
installer's own idea of who is supported drifted from the document.
"""
doc = (INSTALL_SH.parent / "docs" / "DISTRO_COMPATIBILITY.md").read_text(encoding="utf-8")
experimental = doc[doc.index("## Experimental Support") : doc.index("## Not Supported")]
misfiled = [
line.split("|")[1].strip()
for line in experimental.splitlines()
if line.startswith("|") and "✅" in line
]
assert not misfiled, f"listed as supported but filed as experimental: {misfiled}"
def test_no_release_number_gate_survives_in_the_installer(self):
source = INSTALL_SH.read_text(encoding="utf-8")
assert "check_ubuntu_version" not in source
assert "requires Ubuntu" not in source, "the installer must not gate on a release label"
@staticmethod
def _check(interpreter: Path) -> str:
script = f"""
PYTHON_CMD="python3"
SYSTEM_PYTHON="{interpreter}"
{_source("python_version_of", "python_version_at_least", "python_has_gi",
"select_python_interpreter", "check_python_version")}
export PATH="{interpreter.parent}:/usr/bin:/bin"
check_python_version && echo "ACCEPTED" || echo "REJECTED"
"""
return _run(script).stdout
@pytest.mark.parametrize("distro_id,version_id", DERIVATIVES)
def test_a_derivative_with_a_new_enough_python_is_accepted(
self, tmp_path, distro_id, version_id
):
"""What the distro calls itself must not decide this; its Python must."""
interpreter = _fake_python(
tmp_path / f"{distro_id}-{version_id}" / "python3", "3.12", has_gi=True
)
assert "ACCEPTED" in self._check(interpreter)
def test_an_interpreter_below_the_floor_is_still_rejected(self, tmp_path):
"""Dropping the label gate must not drop the real one."""
interpreter = _fake_python(tmp_path / "jammy" / "python3", "3.10", has_gi=True)
assert "REJECTED" in self._check(interpreter)
def test_the_floor_itself_is_accepted(self, tmp_path):
interpreter = _fake_python(tmp_path / "floor" / "python3", "3.11", has_gi=True)
assert "ACCEPTED" in self._check(interpreter)
def test_installer_never_creates_venv_with_bare_python3():
source = INSTALL_SH.read_text(encoding="utf-8")
for line in source.splitlines():
stripped = line.strip()
if stripped.startswith("python3 -m venv") or stripped.startswith("python3 -m virtualenv"):
raise AssertionError(f"venv must be created via $PYTHON_CMD: {stripped}")