Files
voculinux/tests/test_cross_distro_compatibility.py
T
Jatin K MalikandGitHub fa4da40e7b test(coverage): improve test coverage from 57% to 80%+ (#327)
* test(coverage): improve test coverage from 57% to 80%+

Add 30 new test files with 861 additional test cases to improve
overall test coverage from 57% to 80%+ (statement coverage).

Key modules covered:
- recognition_manager.py: 43% → 69% (audio device detection, transcription,
  model download, engine initialization, buffer management)
- text_injector.py: improved coverage for X11/Wayland text injection,
  environment detection, clipboard fallback, shortcut injection
- ibus_engine.py: 22% → 73% (engine lifecycle, text injection, socket server)
- evdev_backend.py: 11% → 78% (device detection, key event handling)
- pynput_backend.py: 43% → 76% (start/stop, key handling, callbacks)
- keyboard_backends/__init__.py: 54% → improved (backend creation, env detection)
- whispercpp_model_info.py: 32% → improved (GPU detection, model recommendations)
- about_dialog.py, first_run_dialog.py, main.py, single_instance.py,
  common_types.py, config_manager.py, autostart_manager.py: various improvements

All 1433 tests pass with proper test isolation to prevent mock pollution
between test modules.

* test(quality): audit and fix test quality issues

Code review audit identified and fixed the following issues:

- Remove bare try/except blocks that swallow all errors (7 tests fixed
  in recognition_manager_deep, replaced with proper assertions or deleted)
- Delete source code inspection tests that read .py files as strings
  instead of testing behavior (deleted test_about_dialog_coverage.py and
  test_first_run_dialog_coverage.py entirely - ~35 useless tests removed)
- Add meaningful assertions replacing weak assertIsNotNone/assertIsInstance
  checks (common_types_coverage, ibus_engine_coverage, keyboard_backends_extra)
- Fix tests that mock the system under test instead of its dependencies
  (text_injector_extra now mocks subprocess.run instead of injection methods)
- Add missing assertions to tests with no verification
  (ibus_engine focus_out, log window info, copy to clipboard)
- Verify download tests check requests.get was called with correct URLs
  (coverage_boost download tests)
- Fix pytest warning by renaming test_audio_input import to avoid
  pytest collecting it as a test function

All 1356 tests pass with 0 failures and 0 warnings.
Statement coverage: 80.3% (3257/4054 lines covered).

* style(tests): fix black formatting and isort import ordering

Auto-format all new test files with black and isort to pass CI lint checks.

* fix(tests): resolve CI hangs and rename test files for clarity

- Fix CI hangs by properly mocking gi/GTK/IBus in all test files
- Fix sys.modules pollution in recognition manager tests by using tmp_path
- Add pytest-timeout to prevent future hangs
- Rename 28 test files to use descriptive, consistent names mapping to source modules

* fix(tests): resolve Python 3.13 CI failures

- Fix _load_stdlib_module() in test_recognition_manager_downloads.py to
  handle stdlib modules that are packages (directories with __init__.py)
  rather than single .py files. In Python 3.13, zipfile became a package,
  causing FileNotFoundError during test collection (exit code 2).

- Fix invalid escape sequence '$' in test_cross_distro_compatibility.py
  by using a raw string. Python 3.13 reports this as SyntaxWarning and
  Python 3.14 will make it a SyntaxError.

* fix(tests): use direct import for zipfile instead of _load_stdlib_module

The _load_stdlib_module approach fails on Python 3.13 where zipfile is a
package (zipfile/__init__.py). Loading it via spec_from_file_location with
a custom name breaks relative imports inside the package (e.g.
'from ._path import ...' resolves to '_stdlib_zipfile._path' which doesn't
exist).

Simply import zipfile at module level before any test mocks can pollute
sys.modules — this is safe because the module-level code runs during test
collection, before any test fixtures or patches are applied.

* fix(tests): mock gi/GTK in conftest to prevent CI hangs

On CI, real PyGObject is installed and module-level imports in vocalinux
source files (ibus_engine, tray_indicator, settings_dialog, etc.) trigger
GTK initialization or IBus daemon connections that hang indefinitely in
headless environments. pytest-timeout's signal-based timeout cannot
interrupt these C-level blocking calls.

Fix by mocking gi and gi.repository in conftest.py (which runs before any
test module is collected), ensuring all test files are protected regardless
of whether they remember to mock individually.

Also add timeout-minutes: 10 to the CI test job as a safety net so that
any remaining hangs fail fast instead of running indefinitely.

* fix(tests): unconditionally mock gi in conftest for CI

The previous 'if gi not in sys.modules' guard was ineffective on CI
because PyGObject is installed via pip, so the real gi module is already
loaded. This caused GTK initialization and IBus daemon connections that
hang indefinitely in headless CI environments.

Now unconditionally replace gi and gi.repository with mocks during test
collection, regardless of whether the real package is installed.

* fix(tests): reduce timeout to 10s and use thread-based timeout

Use timeout_method=thread instead of signal (default) so that
pytest-timeout can interrupt C-level blocking calls (GTK operations,
socket accepts, subprocess waits) that the signal-based method cannot
handle. Also reduce per-test timeout from 30s to 10s since no legitimate
unit test should take longer, and hanging tests were consuming the entire
CI job timeout budget.

* fix(tests): set global socket timeout to prevent blocking on CI

Tests in test_ibus_engine.py create real Unix sockets with daemon threads
that block on socket.accept(). When tests fail or timeout, these threads
remain blocked indefinitely, preventing pytest from completing. The
thread-based timeout catches the hang but cannot terminate the blocking
accept() call.

Set socket.setdefaulttimeout(5) in conftest.py so all socket operations
(accept, connect, recv) will raise socket.timeout after 5 seconds instead
of blocking forever.

* fix(tests): add cleanup fixture for IBus socket server threads

Add autouse fixture that stops any leftover VocalinuxEngine socket server
threads after each test. Tests that trigger _start_socket_server() spawn
daemon threads blocking on socket.accept() that persist after the test
completes, eventually causing pytest-timeout to kill the process.

The cleanup fixture sets _server_running=False and closes the server
socket, which unblocks the accept() call and allows the daemon thread
to terminate.

* fix(tests): reduce socket timeout to 0.1s to avoid slowing tests

The 5-second socket timeout caused socket operations in daemon threads
to block for 5 seconds per iteration before timing out, significantly
slowing the test suite on CI. Reduce to 0.1s so blocking socket calls
fail fast without noticeably impacting test execution time.

* fix(tests): use 2s socket timeout and increase CI timeout to 15min

The 0.1s socket timeout was too aggressive and caused legitimate test
socket operations to fail. Use 2s which is long enough for test sockets
to work but short enough to unblock daemon threads.

Increase CI job timeout to 15 minutes to accommodate the socket timeout
overhead from daemon threads that retry every 2 seconds.

* fix(tests): block known-blocking daemon threads to prevent CI hangs

Instead of using socket timeouts (which either break tests or are too
slow), prevent specific known-blocking daemon threads from starting:
- ibus_engine.server_thread: blocks on socket.accept()
- evdev_backend._monitor_devices: blocks on select.select()

These threads are identified by their target function name and skipped
during Thread.start(). The thread is marked as started/stopped so
join() calls in cleanup code don't raise RuntimeError.

Test-created daemon threads (e.g. mock socket servers) are unaffected
since they use different target function names.

* fix(tests): patch Thread.join for Python 3.13 compatibility

Python 3.13 changed threading internals — join() now uses _handle.join()
which raises 'thread not started' for threads that were never actually
started. Instead of trying to fake internal state, patch join() to be a
no-op for threads that were skipped by our _safe_thread_start guard.

This fixes the 2 remaining test_evdev_backend_ext failures on Python 3.13.
2026-03-17 14:05:16 -07:00

196 lines
8.2 KiB
Python

"""
Test cross-distro compatibility features.
This module tests the cross-distribution compatibility features including:
- Dynamic GI_TYPELIB_PATH detection
- Wrapper script generation with correct paths
- Desktop entry configuration
"""
import os
from pathlib import Path
import pytest
def get_repo_root() -> Path:
"""Get the repository root directory."""
# Start from current file and traverse up to find repo root
current = Path(__file__).resolve()
for parent in [current] + list(current.parents):
# Check for common repo indicators
if (parent / ".git").exists() or (parent / "install.sh").exists():
return parent
# Also check if we're in a 'vocalinux' subdirectory (CI structure)
if parent.name == "vocalinux" and (parent.parent / "vocalinux" / "install.sh").exists():
return parent.parent / "vocalinux"
# Fallback: use parent of tests directory
return current.parent.parent.parent
REPO_ROOT = get_repo_root()
class TestCrossDistroCompatibility:
"""Test cross-distro compatibility features."""
@pytest.fixture
def install_sh_content(self):
"""Fixture to load install.sh content."""
install_sh_path = REPO_ROOT / "install.sh"
if not install_sh_path.exists():
pytest.skip(f"install.sh not found at {install_sh_path}")
return install_sh_path.read_text()
@pytest.fixture
def workflow_content(self):
"""Fixture to load workflow content."""
workflow_path = REPO_ROOT / ".github" / "workflows" / "unified-pipeline.yml"
if not workflow_path.exists():
pytest.skip(f"Workflow file not found at {workflow_path}")
return workflow_path.read_text()
def test_detect_typelib_path_function_exists(self, install_sh_content):
"""Test that detect_typelib_path function exists in install.sh."""
assert (
"detect_typelib_path()" in install_sh_content
), "detect_typelib_path function should exist"
assert (
"pkg-config --variable=typelibdir" in install_sh_content
), "Should use pkg-config for detection"
def test_no_hardcoded_gi_typelib_path_in_verification(self, install_sh_content):
"""Test that package verification uses dynamic GI_TYPELIB_PATH."""
# The verification function should use the detected path, not hardcoded
assert (
"verify_package_installed()" in install_sh_content
), "verify_package_installed function should exist"
# Check that it uses GI_TYPELIB_DETECTED variable
verify_section = install_sh_content[
install_sh_content.find("verify_package_installed()") : install_sh_content.find(
"verify_package_installed()"
)
+ 500
]
assert (
"GI_TYPELIB_DETECTED" in verify_section or '"$GI_TYPELIB_DETECTED"' in verify_section
), "verify_package_installed should use GI_TYPELIB_DETECTED variable"
def test_wrapper_script_uses_detected_path(self, install_sh_content):
"""Test that wrapper scripts use the detected GI_TYPELIB_PATH."""
# Check that wrapper script creation uses GI_TYPELIB_DETECTED
assert (
"export GI_TYPELIB_PATH=$GI_TYPELIB_DETECTED" in install_sh_content
), "Wrapper script should export GI_TYPELIB_PATH with detected value"
def test_desktop_entry_uses_detected_path(self, install_sh_content):
"""Test that desktop entry uses detected GI_TYPELIB_PATH."""
# The sed command for desktop entry should use the detected path
assert (
"GI_TYPELIB_PATH=$GI_TYPELIB_DETECTED" in install_sh_content
or r"GI_TYPELIB_PATH=${GI_TYPELIB_DETECTED}" in install_sh_content
), "Desktop entry sed command should use GI_TYPELIB_DETECTED"
# Should NOT have hardcoded /usr/lib/girepository-1.0 in desktop entry section
desktop_start = install_sh_content.find("install_desktop_entry()")
if desktop_start == -1:
pytest.skip("install_desktop_entry function not found")
desktop_section = install_sh_content[desktop_start : desktop_start + 1000]
if "sed -i" in desktop_section and "vocalinux.desktop" in desktop_section:
assert (
"/usr/lib/girepository-1.0"
not in desktop_section.split("sed -i")[1].split("vocalinux.desktop")[0]
), "Desktop entry should not hardcode /usr/lib/girepository-1.0 path"
def test_detect_typelib_path_with_pkgconfig(self, install_sh_content):
"""Test that detect_typelib_path uses pkg-config when available."""
# Extract the detect_typelib_path function
func_start = install_sh_content.find("detect_typelib_path() {")
if func_start == -1:
pytest.skip("detect_typelib_path function not found")
func_end = install_sh_content.find("}", func_start)
func_content = install_sh_content[func_start:func_end]
# Should check for pkg-config first
assert "pkg-config" in func_content, "Should check for pkg-config"
assert "gobject-introspection-1.0" in func_content, "Should query gobject-introspection-1.0"
def test_detect_typelib_path_fallback_paths(self, install_sh_content):
"""Test that detect_typelib_path has fallback paths for various distros."""
# Should have fallback paths for different distros
expected_paths = [
"/usr/lib/x86_64-linux-gnu/girepository-1.0", # Ubuntu/Debian x86_64
"/usr/lib/aarch64-linux-gnu/girepository-1.0", # ARM64
"/usr/lib64/girepository-1.0", # Fedora/RHEL
"/usr/lib/girepository-1.0", # Arch and fallback
]
for path in expected_paths:
assert path in install_sh_content, f"Should have fallback path: {path}"
def test_ci_workflow_uses_dynamic_detection(self, workflow_content):
"""Test that CI workflow uses dynamic GI_TYPELIB_PATH detection."""
# Should use pkg-config or dynamic detection
assert (
"pkg-config --variable=typelibdir" in workflow_content
), "CI workflow should use pkg-config for GI_TYPELIB_PATH"
class TestResourceManagerCrossDistro:
"""Test ResourceManager cross-distro path handling."""
def test_resource_manager_has_xdg_support(self):
"""Test that ResourceManager supports XDG directories."""
from vocalinux.utils.resource_manager import ResourceManager
rm = ResourceManager()
resources_dir = rm.resources_dir
# Should be a valid path string
assert isinstance(resources_dir, str), "resources_dir should be a string"
assert len(resources_dir) > 0, "resources_dir should not be empty"
class TestRecognitionManagerCrossDistro:
"""Test RecognitionManager cross-distro model path handling."""
def test_system_model_paths_exists(self):
"""Test that system model paths configuration exists."""
from vocalinux.speech_recognition.recognition_manager import SYSTEM_MODELS_DIRS
# Should be a list of paths
assert isinstance(SYSTEM_MODELS_DIRS, list), "SYSTEM_MODELS_DIRS should be a list"
assert len(SYSTEM_MODELS_DIRS) > 0, "SYSTEM_MODELS_DIRS should not be empty"
# Should include XDG paths
has_xdg = any("/share/" in path for path in SYSTEM_MODELS_DIRS)
assert has_xdg, "SYSTEM_MODELS_DIRS should include XDG paths"
class TestDocumentation:
"""Test that documentation is accurate."""
def test_distro_compatibility_documentation_exists(self):
"""Test that DISTRO_COMPATIBILITY.md exists and is accurate."""
docs_path = REPO_ROOT / "docs" / "DISTRO_COMPATIBILITY.md"
if not docs_path.exists():
pytest.skip(f"DISTRO_COMPATIBILITY.md not found at {docs_path}")
content = docs_path.read_text()
# Should mention the dynamic path detection
assert (
"pkg-config" in content or "detect_typelib_path" in content
), "Should document dynamic path detection"
# Should mention supported distros
expected_distros = ["Ubuntu", "Debian", "Fedora", "Arch", "openSUSE"]
for distro in expected_distros:
assert distro in content, f"Should mention {distro} support"
if __name__ == "__main__":
pytest.main([__file__, "-v"])