Files
voculinux/tests/test_keyboard_shortcuts.py
T
Jatin K MalikandGitHub 1dc1d44665 feat: Alpha Launch v0.2.0 - Complete UX Overhaul 🚀🎤 (#39)
* feat: prepare for v0.2.0-alpha release

* feat: prepare for v0.2.0-alpha release

* chore: remove CHANGELOG.md, use GitHub Releases instead

* refactor: use existing About dialog instead of Settings section

* style: enhance About dialog UI readability

* style: fix formatting with black and isort

* feat: show VAD and silence timeout settings for Whisper engine

- Renamed 'VOSK Settings' to 'Recognition Settings'
- VAD Sensitivity and Silence Timeout now apply to both engines
- Added tooltips explaining each setting
- VOSK-specific model info only shown when VOSK selected

* fix: resolve overlapping UI elements in settings dialog

* fix: save VAD and silence timeout settings for both engines

Previously these settings were only saved when VOSK was selected.
Now they persist correctly for Whisper as well.

* fix: show download progress when selecting undownloaded model

Previously when auto-applying settings, models would download silently
in the background without showing the progress dialog. Now:
- Download progress dialog appears for undownloaded models
- Model icons update correctly after download completes

* feat: add download progress, speed, ETA and cancel button

- Show real download progress percentage for VOSK models
- Display download speed (MB/s) and estimated time remaining
- Add Cancel button to abort downloads
- Update status during extraction phase
- Whisper downloads still pulse (uses internal downloader)

* fix: defer model download until needed, don't block startup

- App now starts instantly even if models aren't downloaded
- Models are downloaded on-demand when selected in Settings
- If user tries to dictate without a model, plays error sound
- Added model_ready property to check if engine is usable

* fix: improve first-run UX without downloaded models

- Settings dialog now defaults to smallest available model, not saved config
- Only show saved model if it's actually downloaded
- Add desktop notification when trying to dictate without a model
- Prevents auto-downloading large models on first launch

* feat: add download progress tracking for Whisper models

- Implement custom Whisper model download with progress/speed/ETA
- Uses OpenAI's CDN URLs directly instead of whisper.load_model()
- Progress callback works the same as VOSK downloads
- Supports cancellation during download

* fix: enable download progress callback for Whisper models

Progress callback was only being set for VOSK downloads, not Whisper.
Now both engines show real-time progress, speed, and ETA.

* fix: update tests for defer_download and config manager mocking

- test_main: Mock ConfigManager to prevent saved config from overriding test values
- test_settings_dialog: Mock ModelDownloadDialog to prevent GTK init errors
- test_speech_recognition: Use proper MockVoskModule class instead of MagicMock, pass defer_download=False for download test
- test_whisper_support: Pass defer_download=False to trigger model loading in test

* fix: resolve test failures for CI

- test_main: Fix ConfigManager patch path to use source module
- test_settings_dialog: Mock _is_vosk_model_downloaded and _is_whisper_model_downloaded to skip download flow, add missing dialog attributes
- test_speech_recognition: Replace recognizer with properly configured mock that returns valid JSON, fixing test isolation issues when running all tests together

* fix: mock _download_whisper_model in whisper test to avoid requests exception handling issue

* fix: add gir1.2-girepository-2.0 dep for PyGObject on Ubuntu 24.04

- Add missing girepository-2.0 package for newer Ubuntu runners
- Use --no-build-isolation for PyGObject to use system packages

* fix: skip PyGObject pip install, use system python3-gi package

- Use --no-deps for editable install to skip PyGObject
- Install other deps explicitly without PyGObject
- Add python3-gi-cairo for complete GTK support
- Removes problematic girepository-2.0 build requirement

* fix: install PyGObject via pip with proper build deps

- Remove python3-gi/python3-gi-cairo (doesn't work with setup-python)
- Install PyGObject from pip after installing build dependencies
- Simplify venv setup without --system-site-packages hack

* Fix GObject

* fix: set GI_TYPELIB_PATH for pip-installed PyGObject to find AppIndicator3
2025-12-28 15:29:51 -08:00

278 lines
9.9 KiB
Python

"""
Tests for keyboard shortcut functionality.
"""
import time
import unittest
from unittest.mock import MagicMock, patch
# Update import to use the new package structure
from vocalinux.ui.keyboard_shortcuts import KeyboardShortcutManager
class TestKeyboardShortcuts(unittest.TestCase):
"""Test cases for the keyboard shortcuts functionality."""
def setUp(self):
"""Set up for tests."""
# Set up more complete mocks for the keyboard library
self.kb_patch = patch("vocalinux.ui.keyboard_shortcuts.KEYBOARD_AVAILABLE", True)
self.kb_patch.start()
# Create proper Key enum and KeyCode class
self.keyboard_patch = patch("vocalinux.ui.keyboard_shortcuts.keyboard")
self.mock_keyboard = self.keyboard_patch.start()
# Set up Key attributes as simple strings for easier testing
self.mock_keyboard.Key.alt = "Key.alt"
self.mock_keyboard.Key.alt_l = "Key.alt_l"
self.mock_keyboard.Key.alt_r = "Key.alt_r"
self.mock_keyboard.Key.shift = "Key.shift"
self.mock_keyboard.Key.shift_l = "Key.shift_l"
self.mock_keyboard.Key.shift_r = "Key.shift_r"
self.mock_keyboard.Key.ctrl = "Key.ctrl"
self.mock_keyboard.Key.ctrl_l = "Key.ctrl_l"
self.mock_keyboard.Key.ctrl_r = "Key.ctrl_r"
self.mock_keyboard.Key.cmd = "Key.cmd"
self.mock_keyboard.Key.cmd_l = "Key.cmd_l"
self.mock_keyboard.Key.cmd_r = "Key.cmd_r"
# Create mock Listener
self.mock_listener = MagicMock()
self.mock_listener.is_alive.return_value = True
self.mock_keyboard.Listener.return_value = self.mock_listener
# Create a new KSM for each test
self.ksm = KeyboardShortcutManager()
def tearDown(self):
"""Clean up after tests."""
self.kb_patch.stop()
self.keyboard_patch.stop()
def test_init(self):
"""Test initialization of the keyboard shortcut manager."""
# Verify double-tap threshold is set
self.assertEqual(self.ksm.double_tap_threshold, 0.3)
# Verify double-tap callback is initially None
self.assertIsNone(self.ksm.double_tap_callback)
def test_start_listener(self):
"""Test starting the keyboard listener."""
# Start the listener
self.ksm.start()
# Verify listener was created with correct arguments
self.mock_keyboard.Listener.assert_called_once()
# Check that on_press and on_release are being passed
args, kwargs = self.mock_keyboard.Listener.call_args
self.assertIn("on_press", kwargs)
self.assertIn("on_release", kwargs)
# Check that listener was started
self.mock_listener.start.assert_called_once()
self.assertTrue(self.ksm.active)
def test_start_already_active(self):
"""Test starting when already active."""
# Make it active already
self.ksm.active = True
# Try to start again
self.ksm.start()
# Verify nothing was called
self.mock_keyboard.Listener.assert_not_called()
def test_start_listener_failed(self):
"""Test handling when listener fails to start."""
# Make is_alive return False
self.mock_listener.is_alive.return_value = False
# Start the listener
self.ksm.start()
# Should have tried to start but then set active to False
self.mock_listener.start.assert_called_once()
self.assertFalse(self.ksm.active)
def test_stop_listener(self):
"""Test stopping the keyboard listener."""
# Setup an active listener
self.ksm.start()
self.ksm.active = True
# Stop the listener
self.ksm.stop()
# Verify listener was stopped
self.mock_listener.stop.assert_called_once()
self.mock_listener.join.assert_called_once()
self.assertFalse(self.ksm.active)
self.assertIsNone(self.ksm.listener)
def test_stop_not_active(self):
"""Test stopping when not active."""
# Make it inactive
self.ksm.active = False
# Try to stop
self.ksm.stop()
# Nothing should happen
if hasattr(self.ksm, "listener") and self.ksm.listener:
self.mock_listener.stop.assert_not_called()
def test_register_toggle_callback(self):
"""Test registering toggle callback with double-tap shortcut."""
# Create mock callback
callback = MagicMock()
# Register as toggle callback
self.ksm.register_toggle_callback(callback)
# Verify it was registered as double-tap callback
self.assertEqual(self.ksm.double_tap_callback, callback)
def test_key_press_modifier(self):
"""Test handling a modifier key press."""
# Initialize and start to set up the listener
self.ksm.start()
# Get the on_press handler
on_press = self.mock_keyboard.Listener.call_args[1]["on_press"]
# Make sure current_keys is set and initially empty
self.ksm.current_keys = set()
# Simulate pressing Ctrl
on_press(self.mock_keyboard.Key.ctrl)
# Verify Ctrl was added to current keys
self.assertIn(self.mock_keyboard.Key.ctrl, self.ksm.current_keys)
def test_double_tap_ctrl(self):
"""Test double-tap Ctrl detection."""
# Initialize and start to set up the listener
self.ksm.start()
# Get the on_press handler
on_press = self.mock_keyboard.Listener.call_args[1]["on_press"]
# Register mock callback for double-tap Ctrl
callback = MagicMock()
self.ksm.register_toggle_callback(callback)
# Set up initial state
self.ksm.last_ctrl_press_time = time.time() - 0.2 # Recent press (within threshold)
self.ksm.last_trigger_time = 0 # No recent triggers
# Simulate second Ctrl press (should trigger callback)
on_press(self.mock_keyboard.Key.ctrl)
# Verify callback was triggered
callback.assert_called_once()
# Reset and test when press is outside threshold (not a double-tap)
callback.reset_mock()
self.ksm.last_ctrl_press_time = time.time() - 0.5 # Outside threshold
on_press(self.mock_keyboard.Key.ctrl)
callback.assert_not_called()
def test_normalize_modifier_keys(self):
"""Test normalizing left/right modifier keys."""
# Setup the key mapping dictionary correctly
self.ksm._normalize_modifier_key = MagicMock(
side_effect=lambda key: {
self.mock_keyboard.Key.alt_l: self.mock_keyboard.Key.alt,
self.mock_keyboard.Key.alt_r: self.mock_keyboard.Key.alt,
self.mock_keyboard.Key.shift_l: self.mock_keyboard.Key.shift,
self.mock_keyboard.Key.shift_r: self.mock_keyboard.Key.shift,
self.mock_keyboard.Key.ctrl_l: self.mock_keyboard.Key.ctrl,
self.mock_keyboard.Key.ctrl_r: self.mock_keyboard.Key.ctrl,
self.mock_keyboard.Key.cmd_l: self.mock_keyboard.Key.cmd,
self.mock_keyboard.Key.cmd_r: self.mock_keyboard.Key.cmd,
}.get(key, key)
)
# Test the normalization
self.assertEqual(
self.ksm._normalize_modifier_key(self.mock_keyboard.Key.alt_l),
self.mock_keyboard.Key.alt,
)
def test_double_tap_ctrl_debounce(self):
"""Test that double-tap Ctrl has debounce protection."""
# Initialize and start to set up the listener
self.ksm.start()
# Get the on_press handler
on_press = self.mock_keyboard.Listener.call_args[1]["on_press"]
# Register mock callback for double-tap Ctrl
callback = MagicMock()
self.ksm.register_toggle_callback(callback)
# Set up initial state (recent trigger)
self.ksm.last_ctrl_press_time = time.time() - 0.2 # Recent press (within threshold)
self.ksm.last_trigger_time = time.time() - 0.2 # Recent trigger, within debounce
# Simulate second Ctrl press (should NOT trigger due to debounce)
on_press(self.mock_keyboard.Key.ctrl)
# Verify callback was NOT triggered
callback.assert_not_called()
def test_key_release(self):
"""Test handling a key release."""
# Initialize and start to set up the listener
self.ksm.start()
# Get the on_release handler
on_release = self.mock_keyboard.Listener.call_args[1]["on_release"]
# Add some keys
self.ksm.current_keys = {self.mock_keyboard.Key.ctrl}
# Simulate releasing Ctrl
on_release(self.mock_keyboard.Key.ctrl)
# Verify Ctrl was removed
self.assertNotIn(self.mock_keyboard.Key.ctrl, self.ksm.current_keys)
def test_error_handling(self):
"""Test error handling in key event handlers."""
# Initialize and start to set up the listener
self.ksm.start()
# Get the handlers
on_press = self.mock_keyboard.Listener.call_args[1]["on_press"]
on_release = self.mock_keyboard.Listener.call_args[1]["on_release"]
# Make a key that raises an exception
bad_key = MagicMock()
bad_key.__eq__ = MagicMock(side_effect=Exception("Test exception"))
# Verify exceptions are caught
try:
on_press(bad_key)
on_release(bad_key)
# If we get here, exceptions were caught properly
self.assertTrue(True)
except:
self.fail("Exceptions were not caught in event handlers")
def test_no_keyboard_library(self):
"""Test behavior when keyboard library is not available."""
# Create a new mock to replace the keyboard system
with patch("vocalinux.ui.keyboard_shortcuts.KEYBOARD_AVAILABLE", False):
# Create a new KSM with no keyboard library
ksm = KeyboardShortcutManager()
# Start should do nothing
ksm.start()
# When keyboard is not available, active should remain False
self.assertFalse(ksm.active)