Files
voculinux/tests/test_main_args_deps.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

430 lines
16 KiB
Python

"""
Additional coverage tests for main.py module.
Tests for parse_args(), main(), and VocalinuxApp class (if present).
Covers normal startup, debug mode, version flag, keyboard interrupt, and exception handling.
"""
import os
import sys
import unittest
from unittest.mock import MagicMock, call, patch
import pytest
# Autouse fixture to prevent sys.modules pollution between tests
@pytest.fixture(autouse=True)
def _restore_sys_modules():
saved = dict(sys.modules)
yield
added = set(sys.modules.keys()) - set(saved.keys())
for k in added:
del sys.modules[k]
for k, v in saved.items():
if k not in sys.modules or sys.modules[k] is not v:
sys.modules[k] = v
class TestParseArguments(unittest.TestCase):
"""Tests for parse_arguments() function."""
def test_parse_args_defaults(self):
"""Test parsing arguments with defaults."""
with patch.object(sys, "argv", ["vocalinux"]):
from vocalinux.main import parse_arguments
args = parse_arguments()
assert args.debug is False
assert args.model is None
assert args.language is None
assert args.engine is None
assert args.wayland is False
assert args.start_minimized is False
def test_parse_args_debug_flag(self):
"""Test parsing with debug flag."""
with patch.object(sys, "argv", ["vocalinux", "--debug"]):
from vocalinux.main import parse_arguments
args = parse_arguments()
assert args.debug is True
def test_parse_args_model_argument(self):
"""Test parsing with model argument."""
with patch.object(sys, "argv", ["vocalinux", "--model", "small"]):
from vocalinux.main import parse_arguments
args = parse_arguments()
assert args.model == "small"
def test_parse_args_language_argument(self):
"""Test parsing with language argument."""
with patch.object(sys, "argv", ["vocalinux", "--language", "en-us"]):
from vocalinux.main import parse_arguments
args = parse_arguments()
assert args.language == "en-us"
def test_parse_args_engine_argument(self):
"""Test parsing with engine argument."""
with patch.object(sys, "argv", ["vocalinux", "--engine", "whisper_cpp"]):
from vocalinux.main import parse_arguments
args = parse_arguments()
assert args.engine == "whisper_cpp"
def test_parse_args_wayland_flag(self):
"""Test parsing with wayland flag."""
with patch.object(sys, "argv", ["vocalinux", "--wayland"]):
from vocalinux.main import parse_arguments
args = parse_arguments()
assert args.wayland is True
def test_parse_args_start_minimized_flag(self):
"""Test parsing with start-minimized flag."""
with patch.object(sys, "argv", ["vocalinux", "--start-minimized"]):
from vocalinux.main import parse_arguments
args = parse_arguments()
assert args.start_minimized is True
def test_parse_args_multiple_arguments(self):
"""Test parsing with multiple arguments."""
with patch.object(
sys,
"argv",
[
"vocalinux",
"--debug",
"--model",
"large",
"--language",
"es",
"--engine",
"vosk",
"--wayland",
],
):
from vocalinux.main import parse_arguments
args = parse_arguments()
assert args.debug is True
assert args.model == "large"
assert args.language == "es"
assert args.engine == "vosk"
assert args.wayland is True
class TestCheckDependencies(unittest.TestCase):
"""Tests for check_dependencies() function."""
def test_check_dependencies_success(self):
"""Test successful dependency check with all deps mocked as available."""
from vocalinux.main import check_dependencies
mock_gi = MagicMock()
mock_gi_repo = MagicMock()
with patch("vocalinux.main.logging"):
with patch.dict(
sys.modules,
{
"gi": mock_gi,
"gi.repository": mock_gi_repo,
"pynput": MagicMock(),
"requests": MagicMock(),
},
):
result = check_dependencies()
assert result is True
def test_check_dependencies_missing_gtk(self):
"""Test dependency check with missing GTK."""
from vocalinux.main import check_dependencies
with patch("vocalinux.main.logging"):
with patch("builtins.__import__", side_effect=ImportError("No module")):
# Just verify the function doesn't crash
result = check_dependencies()
assert result is False
class TestCheckDisplayAvailable(unittest.TestCase):
"""Tests for check_display_available() function."""
@patch("vocalinux.main.logging")
def test_check_display_available_success(self, mock_logging):
"""Test successful display check - mocks gi to avoid real Gdk calls."""
from vocalinux.main import check_display_available
mock_gi = MagicMock()
mock_gdk = MagicMock()
mock_gdk.Display.get_default.return_value = MagicMock() # display exists
mock_gi_repo = MagicMock(Gdk=mock_gdk)
with patch.dict(sys.modules, {"gi": mock_gi, "gi.repository": mock_gi_repo}):
result = check_display_available()
assert result is True
@patch("vocalinux.main.logging")
def test_check_display_available_no_display(self, mock_logging):
"""Test display check when no display is available."""
from vocalinux.main import check_display_available
mock_gi = MagicMock()
mock_gdk = MagicMock()
mock_gdk.Display.get_default.return_value = None # no display
mock_gi_repo = MagicMock(Gdk=mock_gdk)
with patch.dict(sys.modules, {"gi": mock_gi, "gi.repository": mock_gi_repo}):
result = check_display_available()
assert result is False
class TestMainFunction(unittest.TestCase):
"""Tests for the main() function."""
@patch("vocalinux.main.logging")
@patch("vocalinux.main.check_dependencies")
@patch("vocalinux.main.check_display_available")
@patch("vocalinux.main.parse_arguments")
@patch("vocalinux.main.atexit")
def test_main_single_instance_already_running(
self,
mock_atexit,
mock_parse_args,
mock_check_display,
mock_check_deps,
mock_logging,
):
"""Test main() when another instance is already running."""
from vocalinux.main import main
# Mock single_instance module since it's imported inside main()
mock_single_instance = MagicMock()
mock_single_instance.acquire_lock.return_value = False
with patch.dict(sys.modules, {"vocalinux.single_instance": mock_single_instance}):
# Should exit with status 1
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 1
@patch("vocalinux.main.check_display_available")
@patch("vocalinux.main.logging")
@patch("vocalinux.main.check_dependencies")
@patch("vocalinux.main.parse_arguments")
@patch("vocalinux.main.atexit")
def test_main_missing_dependencies(
self, mock_atexit, mock_parse_args, mock_check_deps, mock_logging, mock_check_display
):
"""Test main() when dependencies are missing."""
from vocalinux.main import main
# Set up mocks
mock_check_deps.return_value = False
mock_parse_args.return_value = MagicMock(debug=False)
# Mock single_instance module since it's imported inside main()
mock_single_instance = MagicMock()
mock_single_instance.acquire_lock.return_value = True
with patch.dict(sys.modules, {"vocalinux.single_instance": mock_single_instance}):
# Should exit with status 1
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 1
@patch("vocalinux.main.logging")
@patch("vocalinux.main.check_dependencies")
@patch("vocalinux.main.check_display_available")
@patch("vocalinux.main.parse_arguments")
@patch("vocalinux.main.atexit")
def test_main_no_display_available(
self, mock_atexit, mock_parse_args, mock_check_display, mock_check_deps, mock_logging
):
"""Test main() when no display is available."""
from vocalinux.main import main
# Set up mocks
mock_check_deps.return_value = True
mock_check_display.return_value = False
mock_parse_args.return_value = MagicMock(debug=False)
# Mock single_instance module since it's imported inside main()
mock_single_instance = MagicMock()
mock_single_instance.acquire_lock.return_value = True
with patch.dict(sys.modules, {"vocalinux.single_instance": mock_single_instance}):
# Should exit with status 1
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 1
@patch("vocalinux.main.logging")
@patch("vocalinux.main.check_dependencies")
@patch("vocalinux.main.check_display_available")
@patch("vocalinux.main.parse_arguments")
@patch("vocalinux.main.atexit")
def test_main_debug_mode_enabled(
self,
mock_atexit,
mock_parse_args,
mock_check_display,
mock_check_deps,
mock_logging,
):
"""Test main() with debug mode enabled."""
from vocalinux.main import main
# Set up mocks
mock_check_deps.return_value = True
mock_check_display.return_value = True
mock_args = MagicMock()
mock_args.debug = True
mock_args.wayland = False
mock_args.start_minimized = False
mock_parse_args.return_value = mock_args
# Mock single_instance module since it's imported inside main()
mock_single_instance = MagicMock()
mock_single_instance.acquire_lock.return_value = True
# Create proper mock for ConfigManager with get_settings() returning valid data
mock_config_manager = MagicMock()
mock_config_manager.return_value.get_settings.return_value = {
"speech_recognition": {
"engine": "whisper",
"model_size": "medium",
"language": "en-us",
},
"audio": {},
"general": {"first_run": False},
}
# Mock the imported modules
with patch.dict(
sys.modules,
{
"vocalinux.single_instance": mock_single_instance,
"vocalinux.common_types": MagicMock(),
"vocalinux.speech_recognition": MagicMock(
recognition_manager=MagicMock(
SpeechRecognitionManager=MagicMock(
side_effect=Exception("Test exception to stop execution")
)
)
),
"vocalinux.text_injection.text_injector": MagicMock(),
"vocalinux.ui.tray_indicator": MagicMock(),
"vocalinux.ui.action_handler": MagicMock(),
"vocalinux.ui.config_manager": mock_config_manager,
"vocalinux.ui.logging_manager": MagicMock(),
"vocalinux.text_injection": MagicMock(),
"vocalinux.ui.first_run_dialog": MagicMock(),
"vocalinux.ui.autostart_manager": MagicMock(),
"vocalinux.text_injection.start_ibus_daemon": MagicMock(),
},
):
# Mock the config manager and other components
with patch("vocalinux.main.logging.getLogger") as mock_get_logger:
mock_logger = MagicMock()
mock_get_logger.return_value = mock_logger
# This would normally start the GTK main loop, which we want to avoid
# The initialization should fail as we've set SpeechRecognitionManager to raise an exception
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 1
@patch("vocalinux.main.logging")
@patch("vocalinux.main.check_dependencies")
@patch("vocalinux.main.check_display_available")
@patch("vocalinux.main.parse_arguments")
@patch("vocalinux.main.atexit")
def test_main_initialization_error(
self,
mock_atexit,
mock_parse_args,
mock_check_display,
mock_check_deps,
mock_logging,
):
"""Test main() when initialization fails."""
from vocalinux.main import main
# Set up mocks
mock_check_deps.return_value = True
mock_check_display.return_value = True
mock_args = MagicMock()
mock_args.debug = False
mock_args.wayland = False
mock_args.start_minimized = False
mock_parse_args.return_value = mock_args
# Mock single_instance module since it's imported inside main()
mock_single_instance = MagicMock()
mock_single_instance.acquire_lock.return_value = True
# Mock components that will raise an exception
with patch("vocalinux.main.logging.getLogger") as mock_get_logger:
mock_logger = MagicMock()
mock_get_logger.return_value = mock_logger
with patch.dict(
sys.modules,
{
"vocalinux.single_instance": mock_single_instance,
"vocalinux.common_types": MagicMock(),
"vocalinux.speech_recognition": MagicMock(
recognition_manager=MagicMock(
SpeechRecognitionManager=MagicMock(side_effect=Exception("Init error"))
)
),
"vocalinux.text_injection.text_injector": MagicMock(),
"vocalinux.ui.tray_indicator": MagicMock(),
"vocalinux.ui.action_handler": MagicMock(),
"vocalinux.ui.config_manager": MagicMock(),
"vocalinux.ui.logging_manager": MagicMock(),
"vocalinux.text_injection": MagicMock(),
"vocalinux.ui.first_run_dialog": MagicMock(),
"vocalinux.ui.autostart_manager": MagicMock(),
"vocalinux.text_injection.start_ibus_daemon": MagicMock(),
},
):
# Should exit with status 1
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 1
class TestMainEntry(unittest.TestCase):
"""Tests for the main entry point and script execution."""
@patch("vocalinux.main.main")
def test_main_entry_point(self, mock_main):
"""Test that the script entry point calls main()."""
# Import the module and verify the entry point
import vocalinux.main as main_module
# Check that main function exists
assert hasattr(main_module, "main")
assert callable(main_module.main)
def test_module_can_be_imported(self):
"""Test that the main module can be imported successfully."""
try:
import vocalinux.main # noqa: F401
assert True
except Exception as e:
pytest.fail(f"Failed to import vocalinux.main: {e}")
if __name__ == "__main__":
unittest.main()