Debian Codegraph @

tests/unit_tests/test_script_manager.py

raw
1 # Unit tests for script_manager.py methods.
2 #
3 # Copyright 2025 Igalia, S.L.
4 # Author: Joanmarie Diggs <[email protected]>
5 #
6 # This library is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU Lesser General Public
8 # License as published by the Free Software Foundation; either
9 # version 2.1 of the License, or (at your option) any later version.
10 #
11 # This library is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # Lesser General Public License for more details.
15 #
16 # You should have received a copy of the GNU Lesser General Public
17 # License along with this library; if not, write to the
18 # Free Software Foundation, Inc., Franklin Street, Fifth Floor,
19 # Boston MA 02110-1301 USA.
20
21 # pylint: disable=wrong-import-position
22 # pylint: disable=import-outside-toplevel
23 # pylint: disable=too-many-public-methods
24 # pylint: disable=too-many-statements
25 # pylint: disable=protected-access
26 # pylint: disable=too-many-arguments
27 # pylint: disable=too-many-positional-arguments
28 # pylint: disable=too-many-locals
29 # pylint: disable=too-many-instance-attributes
30 # pylint: disable=too-many-lines
31
32 """Unit tests for script_manager.py methods."""
33
34 from __future__ import annotations
35
36 import sys
37 from typing import TYPE_CHECKING
38 from unittest.mock import Mock
39
40 import pytest
41
42 if TYPE_CHECKING:
43 from unittest.mock import MagicMock
44
45 from .orca_test_context import OrcaTestContext
46
47
48 @pytest.mark.unit
49 class TestScriptManager:
50 """Test ScriptManager class methods."""
51
52 def _setup_dependencies(self, test_context: OrcaTestContext) -> dict[str, MagicMock]:
53 """Returns dependencies for script_manager module testing."""
54
55 modules_to_clean = ["orca.script_manager"]
56 for module_name in modules_to_clean:
57 if module_name in sys.modules:
58 del sys.modules[module_name]
59
60 additional_modules = [
61 "gi",
62 "gi.repository",
63 "gi.repository.Atspi",
64 "orca.ax_utilities",
65 "orca.command_manager",
66 "orca.scripts",
67 "orca.scripts.apps",
68 "orca.scripts.default",
69 "orca.scripts.sleepmode",
70 "orca.scripts.toolkits",
71 "orca.sleep_mode_manager",
72 "orca.speech_manager",
73 ]
74 essential_modules = test_context.setup_shared_dependencies(additional_modules)
75
76 if "orca.script_manager" in essential_modules:
77 del essential_modules["orca.script_manager"]
78 if "orca.script_manager" in sys.modules:
79 del sys.modules["orca.script_manager"]
80
81 gi_repository_mock = essential_modules["gi.repository"]
82 atspi_mock = essential_modules["gi.repository.Atspi"]
83
84 class UnionSupportingMock(Mock):
85 """Mock that supports union operations for Atspi.Accessible."""
86
87 def __or__(self, other):
88 return UnionSupportingMock()
89
90 atspi_mock.Accessible = UnionSupportingMock()
91 gi_repository_mock.Atspi = atspi_mock
92
93 ax_object_mock = essential_modules["orca.ax_object"]
94 ax_object_class_mock = test_context.Mock()
95 ax_object_class_mock.get_name = test_context.Mock(return_value="test-app")
96 ax_object_class_mock.get_attribute = test_context.Mock(return_value="GTK")
97 ax_object_mock.AXObject = ax_object_class_mock
98
99 ax_utilities_mock = essential_modules["orca.ax_utilities"]
100 ax_utilities_class_mock = test_context.Mock()
101 ax_utilities_class_mock.is_terminal = test_context.Mock(return_value=False)
102 ax_utilities_class_mock.get_application_toolkit_name = test_context.Mock(return_value="gtk")
103 ax_utilities_class_mock.is_application_in_desktop = test_context.Mock(return_value=True)
104 ax_utilities_class_mock.is_frame = test_context.Mock(return_value=False)
105 ax_utilities_class_mock.is_status_bar = test_context.Mock(return_value=False)
106 ax_utilities_mock.AXUtilities = ax_utilities_class_mock
107
108 braille_mock = essential_modules["orca.braille"]
109 braille_mock.check_braille_setting = test_context.Mock()
110 braille_mock.setup_key_ranges = test_context.Mock()
111
112 debug_mock = essential_modules["orca.debug"]
113 debug_mock.print_message = test_context.Mock()
114 debug_mock.LEVEL_INFO = 800
115
116 speech_verbosity_mock = essential_modules["orca.speech_manager"]
117 speech_manager_instance = test_context.Mock()
118 speech_manager_instance.check_speech_setting = test_context.Mock()
119 speech_verbosity_mock.get_manager = test_context.Mock(return_value=speech_manager_instance)
120
121 command_manager_mock = essential_modules["orca.command_manager"]
122 command_manager_instance = test_context.Mock()
123 command_manager_instance.check_keyboard_settings = test_context.Mock()
124 command_manager_mock.get_manager = test_context.Mock(return_value=command_manager_instance)
125
126 scripts_mock = essential_modules["orca.scripts"]
127 apps_mock = essential_modules["orca.scripts.apps"]
128 toolkits_mock = essential_modules["orca.scripts.toolkits"]
129 default_mock = essential_modules["orca.scripts.default"]
130 sleepmode_mock = essential_modules["orca.scripts.sleepmode"]
131
132 apps_mock.__all__ = ["evolution", "gnome-shell"]
133 toolkits_mock.__all__ = ["gtk", "Gecko", "Qt"]
134
135 class MockScript:
136 """Mock script class for testing."""
137
138 def __init__(self, app=None):
139 self.app = app
140 self.register_event_listeners = test_context.Mock()
141 self.deregister_event_listeners = test_context.Mock()
142 self.activate = test_context.Mock()
143 self.deactivate = test_context.Mock()
144
145 def __or__(self, other):
146 return MockScript
147
148 default_script_constructor = test_context.Mock(return_value=MockScript())
149 default_script_constructor.__or__ = lambda self, other: MockScript()
150 sleepmode_script_constructor = test_context.Mock(return_value=MockScript())
151 sleepmode_script_constructor.__or__ = lambda self, other: MockScript()
152
153 default_mock.Script = default_script_constructor
154 sleepmode_mock.Script = sleepmode_script_constructor
155
156 scripts_mock.apps = apps_mock
157 scripts_mock.default = default_mock
158 scripts_mock.sleepmode = sleepmode_mock
159 scripts_mock.toolkits = toolkits_mock
160
161 essential_modules["speech_manager_instance"] = speech_manager_instance
162
163 default_script = test_context.Mock()
164 default_script.app = test_context.Mock()
165 default_script.register_event_listeners = test_context.Mock()
166 default_script.deregister_event_listeners = test_context.Mock()
167 default_script.activate = test_context.Mock()
168 default_script.deactivate = test_context.Mock()
169
170 sleepmode_script = test_context.Mock()
171 sleepmode_script.app = test_context.Mock()
172 sleepmode_script.register_event_listeners = test_context.Mock()
173 sleepmode_script.deregister_event_listeners = test_context.Mock()
174 sleepmode_script.activate = test_context.Mock()
175 sleepmode_script.deactivate = test_context.Mock()
176
177 sleep_mode_manager_instance = test_context.Mock()
178 sleep_mode_manager_instance.is_active_for_app = test_context.Mock(return_value=False)
179
180 # Set up the module-level get_manager mock
181 sleep_mode_manager_mock = essential_modules["orca.sleep_mode_manager"]
182 sleep_mode_manager_mock.get_manager = test_context.Mock(
183 return_value=sleep_mode_manager_instance,
184 )
185
186 essential_modules["default_script"] = default_script
187 essential_modules["sleepmode_script"] = sleepmode_script
188 essential_modules["sleep_mode_manager"] = sleep_mode_manager_instance
189
190 default_module = test_context.Mock()
191 default_module.Script = test_context.Mock(return_value=test_context.Mock())
192
193 sleepmode_module = test_context.Mock()
194 sleepmode_module.Script = test_context.Mock(return_value=test_context.Mock())
195
196 deps_speech_manager = test_context.Mock()
197 deps_speech_manager_instance = test_context.Mock()
198 deps_speech_manager_instance.check_speech_setting = test_context.Mock()
199 deps_speech_manager.get_manager = test_context.Mock(
200 return_value=deps_speech_manager_instance,
201 )
202
203 braille_module = test_context.Mock()
204 braille_module.check_braille_setting = test_context.Mock()
205 braille_module.setup_key_ranges = test_context.Mock()
206
207 essential_modules["default_module"] = default_module
208 essential_modules["sleepmode_module"] = sleepmode_module
209 essential_modules["deps_speech_manager"] = deps_speech_manager
210 essential_modules["braille_module"] = braille_module
211
212 return essential_modules
213
214 def test_init(self, test_context: OrcaTestContext) -> None:
215 """Test ScriptManager.__init__."""
216
217 self._setup_dependencies(test_context)
218 from orca.script_manager import ScriptManager
219
220 manager = ScriptManager()
221 assert not manager.app_scripts
222 assert not manager.toolkit_scripts
223 assert not manager.custom_scripts
224 assert not manager._sleep_mode_scripts
225 assert manager._default_script is None
226 assert manager._active_script is None
227 assert manager._active is False
228
229 @pytest.mark.parametrize(
230 "case",
231 [
232 {
233 "id": "inactive_to_active",
234 "initially_active": False,
235 "expects_script_creation": True,
236 },
237 {"id": "already_active", "initially_active": True, "expects_script_creation": False},
238 ],
239 ids=lambda case: case["id"],
240 )
241 def test_activate(self, test_context: OrcaTestContext, case: dict) -> None:
242 """Test ScriptManager.activate with different initial states."""
243
244 essential_modules = self._setup_dependencies(test_context)
245 default_script = essential_modules["default_script"]
246
247 if case["expects_script_creation"]:
248 mock_default_script = test_context.Mock()
249 test_context.patch("orca.script_manager.default.Script", new=mock_default_script)
250 mock_default_script.return_value = default_script
251
252 from orca.script_manager import ScriptManager
253
254 manager = ScriptManager()
255 manager._active = case["initially_active"]
256 manager.activate()
257
258 assert manager._active is True
259
260 if case["expects_script_creation"]:
261 assert manager._default_script is not None
262 assert manager._active_script is not None
263 default_script.register_event_listeners.assert_called_once()
264
265 @pytest.mark.parametrize(
266 "case",
267 [
268 {"id": "active_to_inactive", "initially_active": True, "expects_cleanup": True},
269 {"id": "already_inactive", "initially_active": False, "expects_cleanup": False},
270 ],
271 ids=lambda case: case["id"],
272 )
273 def test_deactivate(self, test_context: OrcaTestContext, case: dict) -> None:
274 """Test ScriptManager.deactivate with different initial states."""
275
276 self._setup_dependencies(test_context)
277 from orca.script_manager import ScriptManager
278
279 manager = ScriptManager()
280 manager._active = case["initially_active"]
281
282 if case["expects_cleanup"]:
283 mock_script = test_context.Mock()
284 mock_script.deregister_event_listeners = test_context.Mock()
285 manager._default_script = mock_script
286 manager.app_scripts = {"test": "script"}
287 manager.toolkit_scripts = {"test": "script"}
288 manager.custom_scripts = {"test": "script"}
289
290 manager.deactivate()
291 assert manager._active is False
292
293 if case["expects_cleanup"]:
294 assert manager._default_script is None
295 assert manager._active_script is None
296 assert not manager.app_scripts
297 assert not manager.toolkit_scripts
298 assert not manager.custom_scripts
299 mock_script.deregister_event_listeners.assert_called_once()
300
301 @pytest.mark.parametrize(
302 "case",
303 [
304 {
305 "id": "app_in_apps_list",
306 "app_name": "evolution",
307 "expected_result": "evolution",
308 "use_null_app": False,
309 },
310 {
311 "id": "toolkit_in_toolkits_list",
312 "app_name": "gtk",
313 "expected_result": "gtk",
314 "use_null_app": False,
315 },
316 {
317 "id": "mapped_app_name",
318 "app_name": "mate-notification-daemon",
319 "expected_result": "notification-daemon",
320 "use_null_app": False,
321 },
322 {
323 "id": "python_extension",
324 "app_name": "test-app.py",
325 "expected_result": "test-app",
326 "use_null_app": False,
327 },
328 {
329 "id": "bin_extension",
330 "app_name": "test-app.bin",
331 "expected_result": "test-app",
332 "use_null_app": False,
333 },
334 {
335 "id": "reverse_domain",
336 "app_name": "org.gnome.TestApp",
337 "expected_result": "TestApp",
338 "use_null_app": False,
339 },
340 {
341 "id": "reverse_domain_com",
342 "app_name": "com.example.TestApp",
343 "expected_result": "TestApp",
344 "use_null_app": False,
345 },
346 {
347 "id": "unknown_app",
348 "app_name": "unknown-app",
349 "expected_result": "unknown-app",
350 "use_null_app": False,
351 },
352 {"id": "null_app", "app_name": None, "expected_result": None, "use_null_app": True},
353 {"id": "nameless_app", "app_name": "", "expected_result": None, "use_null_app": False},
354 ],
355 ids=lambda case: case["id"],
356 )
357 def test_get_module_name_scenarios(self, test_context, case: dict) -> None:
358 """Test ScriptManager.get_module_name with various scenarios."""
359 self._setup_dependencies(test_context)
360 from orca.script_manager import ScriptManager
361
362 manager = ScriptManager()
363
364 if case["use_null_app"]:
365 result = manager.get_module_name(None)
366 else:
367 mock_app = test_context.Mock()
368 mock_ax_object = test_context.Mock()
369 test_context.patch("orca.script_manager.AXObject", new=mock_ax_object)
370 mock_ax_object.get_name.return_value = case["app_name"]
371 result = manager.get_module_name(mock_app)
372
373 assert result == case["expected_result"]
374
375 @pytest.mark.parametrize(
376 "case",
377 [
378 {"id": "gtk_toolkit", "toolkit_attribute": "GTK", "expected_result": "gtk"},
379 {"id": "gail_mapped_to_gtk", "toolkit_attribute": "GAIL", "expected_result": "gtk"},
380 {"id": "qt_toolkit", "toolkit_attribute": "Qt", "expected_result": "Qt"},
381 {"id": "empty_toolkit", "toolkit_attribute": "", "expected_result": ""},
382 {"id": "none_toolkit", "toolkit_attribute": None, "expected_result": None},
383 ],
384 ids=lambda case: case["id"],
385 )
386 def test_toolkit_for_object(self, test_context, case: dict) -> None:
387 """Test ScriptManager._toolkit_for_object."""
388
389 self._setup_dependencies(test_context)
390 from orca.script_manager import ScriptManager
391
392 manager = ScriptManager()
393 mock_obj = test_context.Mock()
394
395 mock_ax_object = test_context.Mock()
396 test_context.patch("orca.script_manager.AXObject", new=mock_ax_object)
397 mock_ax_object.get_attribute.return_value = case["toolkit_attribute"]
398 result = manager._toolkit_for_object(mock_obj)
399 assert result == case["expected_result"]
400 mock_ax_object.get_attribute.assert_called_once_with(mock_obj, "toolkit")
401
402 @pytest.mark.parametrize(
403 "case",
404 [
405 {"id": "terminal_role", "is_terminal": True, "expected_result": "terminal"},
406 {"id": "non_terminal_role", "is_terminal": False, "expected_result": ""},
407 ],
408 ids=lambda case: case["id"],
409 )
410 def test_script_for_role(self, test_context, case: dict) -> None:
411 """Test ScriptManager._script_for_role."""
412
413 self._setup_dependencies(test_context)
414 from orca.script_manager import ScriptManager
415
416 manager = ScriptManager()
417 mock_obj = test_context.Mock()
418
419 mock_ax_utilities = test_context.Mock()
420 test_context.patch("orca.script_manager.AXUtilities", new=mock_ax_utilities)
421 mock_ax_utilities.is_terminal.return_value = case["is_terminal"]
422 result = manager._script_for_role(mock_obj)
423 assert result == case["expected_result"]
424 mock_ax_utilities.is_terminal.assert_called_once_with(mock_obj)
425
426 @pytest.mark.parametrize(
427 "case",
428 [
429 {
430 "id": "null_app_empty_name",
431 "app": None,
432 "name": "",
433 "has_module": False,
434 "has_get_script": False,
435 "has_script_class": False,
436 "should_succeed": False,
437 },
438 {
439 "id": "empty_name",
440 "app": "app",
441 "name": "",
442 "has_module": False,
443 "has_get_script": False,
444 "has_script_class": False,
445 "should_succeed": False,
446 },
447 {
448 "id": "no_module",
449 "app": "app",
450 "name": "test",
451 "has_module": False,
452 "has_get_script": False,
453 "has_script_class": False,
454 "should_succeed": False,
455 },
456 {
457 "id": "has_get_script",
458 "app": "app",
459 "name": "test",
460 "has_module": True,
461 "has_get_script": True,
462 "has_script_class": False,
463 "should_succeed": True,
464 },
465 {
466 "id": "has_script_class",
467 "app": "app",
468 "name": "test",
469 "has_module": True,
470 "has_get_script": False,
471 "has_script_class": True,
472 "should_succeed": True,
473 },
474 {
475 "id": "no_script_creation",
476 "app": "app",
477 "name": "test",
478 "has_module": True,
479 "has_get_script": False,
480 "has_script_class": False,
481 "should_succeed": False,
482 },
483 ],
484 ids=lambda case: case["id"],
485 )
486 def test_new_named_script(self, test_context, case: dict) -> None:
487 """Test ScriptManager._new_named_script."""
488
489 self._setup_dependencies(test_context)
490 from orca.script_manager import ScriptManager
491
492 manager = ScriptManager()
493 mock_app = test_context.Mock() if case["app"] else None
494 mock_script = test_context.Mock()
495 mock_import = test_context.Mock()
496 test_context.patch("importlib.import_module", side_effect=mock_import)
497 if case["has_module"]:
498 mock_module = type("MockModule", (), {})()
499 if case["has_get_script"]:
500 mock_module.get_script = test_context.Mock(return_value=mock_script)
501 elif case["has_script_class"]:
502 mock_module.Script = test_context.Mock(return_value=mock_script)
503 mock_import.return_value = mock_module
504 else:
505 mock_import.side_effect = ImportError("Module not found")
506 result = manager._new_named_script(mock_app, case["name"])
507 if case["should_succeed"]:
508 assert result == mock_script
509 else:
510 assert result is None
511
512 @pytest.mark.parametrize(
513 "case",
514 [
515 {
516 "id": "os_error_returns_none",
517 "exception_type": "OSError",
518 },
519 {
520 "id": "script_creation_error",
521 "exception_type": "AttributeError",
522 },
523 ],
524 ids=lambda case: case["id"],
525 )
526 def test_new_named_script_error_handling(
527 self,
528 test_context: OrcaTestContext,
529 case: dict,
530 ) -> None:
531 """Test ScriptManager._new_named_script handles various errors."""
532
533 self._setup_dependencies(test_context)
534 from orca.script_manager import ScriptManager
535
536 manager = ScriptManager()
537 mock_app = test_context.Mock()
538 mock_import = test_context.Mock()
539 test_context.patch("importlib.import_module", side_effect=mock_import)
540
541 if case["exception_type"] == "OSError":
542 mock_import.side_effect = OSError("Permission denied")
543 result = manager._new_named_script(mock_app, "test")
544 assert result is None
545 else:
546 mock_module = type("MockModule", (), {})()
547 mock_module.Script = test_context.Mock(
548 side_effect=AttributeError("Script class not found"),
549 )
550 mock_import.return_value = mock_module
551 result = manager._new_named_script(mock_app, "test")
552 assert result is None
553
554 @pytest.mark.parametrize(
555 "case",
556 [
557 {"id": "no_module_name", "module_name": None, "expected_result_type": "default_script"},
558 {
559 "id": "with_module_name",
560 "module_name": "test_script",
561 "expected_result_type": "named_script",
562 },
563 ],
564 ids=lambda case: case["id"],
565 )
566 def test_create_script(self, test_context: OrcaTestContext, case: dict) -> None:
567 """Test ScriptManager._create_script with different module name scenarios."""
568
569 essential_modules = self._setup_dependencies(test_context)
570 default_script = essential_modules["default_script"]
571 from orca.script_manager import ScriptManager
572
573 manager = ScriptManager()
574 mock_app = test_context.Mock()
575 mock_obj = test_context.Mock()
576 mock_script = test_context.Mock()
577
578 test_context.patch_object(manager, "get_module_name", return_value=case["module_name"])
579 test_context.patch_object(manager, "_toolkit_for_object", return_value=None)
580 test_context.patch_object(manager, "get_default_script", return_value=default_script)
581
582 test_context.patch(
583 "orca.script_manager.AXUtilities.get_application_toolkit_name",
584 return_value=None,
585 )
586
587 if case["expected_result_type"] == "default_script":
588 mock_new_named_script = test_context.Mock(return_value=None)
589 else:
590 mock_new_named_script = test_context.Mock(return_value=mock_script)
591 test_context.patch_object(manager, "_new_named_script", side_effect=mock_new_named_script)
592
593 result = manager._create_script(mock_app, mock_obj)
594
595 if case["expected_result_type"] == "default_script":
596 assert result == default_script
597 else:
598 assert result == mock_script
599 mock_new_named_script.assert_called_once_with(mock_app, case["module_name"])
600
601 def test_get_default_script(self, test_context: OrcaTestContext) -> None:
602 """Test ScriptManager.get_default_script."""
603
604 essential_modules = self._setup_dependencies(test_context)
605 default_script = essential_modules["default_script"]
606 from orca.script_manager import ScriptManager
607
608 mock_default_script = test_context.Mock()
609 test_context.patch("orca.script_manager.default.Script", new=mock_default_script)
610 mock_default_script.return_value = default_script
611 manager = ScriptManager()
612 mock_app = test_context.Mock()
613
614 result = manager.get_default_script(mock_app)
615 assert result is not None
616 mock_default_script.assert_called_with(mock_app)
617
618 manager._default_script = default_script
619 result = manager.get_default_script(None)
620 assert result == default_script
621
622 manager._default_script = None
623 result = manager.get_default_script(None)
624 assert result is not None
625 assert manager._default_script is not None
626
627 def test_get_or_create_sleep_mode_script(self, test_context: OrcaTestContext) -> None:
628 """Test ScriptManager.get_or_create_sleep_mode_script."""
629
630 essential_modules = self._setup_dependencies(test_context)
631 sleepmode_script = essential_modules["sleepmode_script"]
632 from orca.script_manager import ScriptManager
633
634 mock_sleepmode_script = test_context.Mock()
635 test_context.patch("orca.script_manager.sleepmode.Script", new=mock_sleepmode_script)
636 mock_sleepmode_script.return_value = sleepmode_script
637 manager = ScriptManager()
638 mock_app = test_context.Mock()
639
640 result = manager.get_or_create_sleep_mode_script(mock_app)
641 assert result is not None
642 assert result == sleepmode_script
643 assert manager._sleep_mode_scripts[mock_app] == result
644
645 result2 = manager.get_or_create_sleep_mode_script(mock_app)
646 assert result2 == result
647 assert len(manager._sleep_mode_scripts) == 1
648
649 @pytest.mark.parametrize(
650 "case",
651 [
652 {
653 "id": "null_app_and_obj",
654 "app": None,
655 "obj": None,
656 "sleep_mode_active": False,
657 "has_custom_script": False,
658 "has_toolkit_script": False,
659 "expected_script_type": "default",
660 },
661 {
662 "id": "sleep_mode_active",
663 "app": "app",
664 "obj": "obj",
665 "sleep_mode_active": True,
666 "has_custom_script": False,
667 "has_toolkit_script": False,
668 "expected_script_type": "sleep",
669 },
670 {
671 "id": "custom_script",
672 "app": "app",
673 "obj": "obj",
674 "sleep_mode_active": False,
675 "has_custom_script": True,
676 "has_toolkit_script": False,
677 "expected_script_type": "custom",
678 },
679 {
680 "id": "toolkit_script",
681 "app": "app",
682 "obj": "obj",
683 "sleep_mode_active": False,
684 "has_custom_script": False,
685 "has_toolkit_script": True,
686 "expected_script_type": "toolkit",
687 },
688 {
689 "id": "app_script",
690 "app": "app",
691 "obj": "obj",
692 "sleep_mode_active": False,
693 "has_custom_script": False,
694 "has_toolkit_script": False,
695 "expected_script_type": "app",
696 },
697 ],
698 ids=lambda case: case["id"],
699 )
700 def test_get_script(self, test_context, case: dict) -> None:
701 """Test ScriptManager.get_script."""
702
703 essential_modules = self._setup_dependencies(test_context)
704 sleepmode_script = essential_modules["sleepmode_script"]
705 sleep_mode_manager = essential_modules["sleep_mode_manager"]
706 from orca.script_manager import ScriptManager
707
708 manager = ScriptManager()
709 mock_app = test_context.Mock() if case["app"] else None
710 mock_obj = test_context.Mock() if case["obj"] else None
711 mock_sleep_script = sleepmode_script
712 mock_custom_script = test_context.Mock()
713
714 class ToolkitScript:
715 """Mock toolkit script class."""
716
717 class AppScript:
718 """Mock app script class."""
719
720 mock_toolkit_script = test_context.Mock(spec=ToolkitScript)
721 mock_app_script = test_context.Mock(spec=AppScript)
722 sleep_mode_manager.is_active_for_app = test_context.Mock(
723 return_value=case["sleep_mode_active"],
724 )
725 test_context.patch_object(
726 manager,
727 "get_or_create_sleep_mode_script",
728 return_value=mock_sleep_script,
729 )
730 test_context.patch_object(
731 manager,
732 "_script_for_role",
733 return_value="terminal" if case["has_custom_script"] else "",
734 )
735 test_context.patch_object(
736 manager,
737 "_toolkit_for_object",
738 return_value="gtk" if case["has_toolkit_script"] else None,
739 )
740
741 def create_script_side_effect(_app, obj):
742 if obj and case["has_toolkit_script"]:
743 return mock_toolkit_script
744 return mock_app_script
745
746 test_context.patch_object(manager, "_create_script", side_effect=create_script_side_effect)
747 if case["has_custom_script"]:
748 test_context.patch_object(manager, "_new_named_script", return_value=mock_custom_script)
749 result = manager.get_script(mock_app, mock_obj)
750 if case["expected_script_type"] == "default":
751 assert result is not None
752 assert hasattr(result, "register_event_listeners")
753 elif case["expected_script_type"] == "sleep":
754 assert result == mock_sleep_script
755 elif case["expected_script_type"] == "custom":
756 assert result == mock_custom_script
757 elif case["expected_script_type"] == "toolkit":
758 assert result == mock_toolkit_script
759 elif case["expected_script_type"] == "app":
760 assert result == mock_app_script
761
762 def test_get_script_exception_handling(self, test_context: OrcaTestContext) -> None:
763 """Test ScriptManager.get_script handles exceptions."""
764
765 self._setup_dependencies(test_context)
766 from orca.script_manager import ScriptManager
767
768 manager = ScriptManager()
769 mock_app = test_context.Mock()
770 mock_obj = test_context.Mock()
771 test_context.patch_object(manager, "_script_for_role", return_value="")
772 test_context.patch_object(manager, "_toolkit_for_object", return_value=None)
773
774 def create_script_side_effect(app, obj):
775 raise KeyError("Script creation failed")
776
777 test_context.patch_object(manager, "_create_script", side_effect=create_script_side_effect)
778 result = manager.get_script(mock_app, mock_obj)
779 assert result is not None
780 assert hasattr(result, "register_event_listeners")
781
782 @pytest.mark.parametrize(
783 "case",
784 [
785 {"id": "no_active_script", "has_active_script": False, "test_type": "script"},
786 {"id": "has_active_script", "has_active_script": True, "test_type": "script"},
787 {"id": "no_active_script_app", "has_active_script": False, "test_type": "app"},
788 {"id": "has_active_script_app", "has_active_script": True, "test_type": "app"},
789 ],
790 ids=lambda case: case["id"],
791 )
792 def test_get_active_script_and_app(self, test_context: OrcaTestContext, case: dict) -> None:
793 """Test ScriptManager.get_active_script and get_active_script_app."""
794 essential_modules = self._setup_dependencies(test_context)
795 default_script = essential_modules["default_script"]
796 from orca.script_manager import ScriptManager
797
798 manager = ScriptManager()
799 mock_app = test_context.Mock()
800
801 if case["has_active_script"]:
802 default_script.app = mock_app
803 manager._active_script = default_script
804
805 if case["test_type"] == "script":
806 result = manager.get_active_script()
807 expected = default_script if case["has_active_script"] else None
808 else:
809 result = manager.get_active_script_app()
810 expected = mock_app if case["has_active_script"] else None
811
812 assert result == expected
813
814 def test_set_active_script(self, test_context: OrcaTestContext) -> None:
815 """Test ScriptManager.set_active_script."""
816
817 essential_modules = self._setup_dependencies(test_context)
818 default_script = essential_modules["default_script"]
819 from orca.script_manager import ScriptManager
820
821 mock_get_speech_manager = test_context.Mock()
822 test_context.patch(
823 "orca.script_manager.speech_manager.get_manager",
824 new=mock_get_speech_manager,
825 )
826 mock_speech_manager_instance = test_context.Mock()
827 mock_get_speech_manager.return_value = mock_speech_manager_instance
828
829 manager = ScriptManager()
830 old_script = test_context.Mock()
831 old_script.app = test_context.Mock()
832 old_script.deactivate = test_context.Mock()
833 new_script = default_script
834 new_script.app = test_context.Mock()
835 new_script.activate = test_context.Mock()
836
837 manager._active_script = old_script
838 manager.set_active_script(new_script, "test reason")
839 old_script.deactivate.assert_called_once()
840 new_script.activate.assert_called_once()
841 assert manager._active_script == new_script
842
843 mock_speech_manager_instance.check_speech_setting.assert_called_once()
844
845 @pytest.mark.parametrize(
846 "case",
847 [
848 {
849 "id": "same_script_no_change",
850 "new_script_type": "same",
851 "expects_deactivate": False,
852 "expects_activate": False,
853 },
854 {
855 "id": "set_to_none",
856 "new_script_type": "none",
857 "expects_deactivate": True,
858 "expects_activate": False,
859 },
860 ],
861 ids=lambda case: case["id"],
862 )
863 def test_set_active_script_special_cases(
864 self,
865 test_context: OrcaTestContext,
866 case: dict,
867 ) -> None:
868 """Test ScriptManager.set_active_script special cases."""
869 essential_modules = self._setup_dependencies(test_context)
870 default_script = essential_modules["default_script"]
871 from orca.script_manager import ScriptManager
872
873 manager = ScriptManager()
874 old_script = test_context.Mock()
875 old_script.deactivate = test_context.Mock()
876 manager._active_script = old_script
877
878 if case["new_script_type"] == "same":
879 manager._active_script = default_script
880 manager.set_active_script(default_script, "same script")
881 if case["expects_deactivate"]:
882 default_script.deactivate.assert_called_once()
883 else:
884 default_script.deactivate.assert_not_called()
885 default_script.activate.assert_not_called()
886 else:
887 manager.set_active_script(None)
888 if case["expects_deactivate"]:
889 old_script.deactivate.assert_called_once()
890 assert manager._active_script is None
891
892 @pytest.mark.parametrize(
893 "case",
894 [
895 {"id": "mixed_apps_normal", "has_app_in_desktop": True, "has_key_error": False},
896 {
897 "id": "no_desktop_apps_with_key_error",
898 "has_app_in_desktop": False,
899 "has_key_error": True,
900 },
901 ],
902 ids=lambda case: case["id"],
903 )
904 def test_reclaim_scripts(self, test_context: OrcaTestContext, case: dict) -> None:
905 """Test ScriptManager.reclaim_scripts with various scenarios."""
906 self._setup_dependencies(test_context)
907 from orca.script_manager import ScriptManager
908
909 desktop_patch = "orca.script_manager.AXUtilities.is_application_in_desktop"
910 mock_is_in_desktop = test_context.Mock()
911 test_context.patch(desktop_patch, new=mock_is_in_desktop)
912 manager = ScriptManager()
913 app_not_in_desktop = test_context.Mock()
914
915 if case["has_app_in_desktop"]:
916 app_in_desktop = test_context.Mock()
917 manager.app_scripts = {
918 app_in_desktop: test_context.Mock(),
919 app_not_in_desktop: test_context.Mock(),
920 }
921 manager.toolkit_scripts = {app_not_in_desktop: test_context.Mock()}
922 manager.custom_scripts = {app_not_in_desktop: test_context.Mock()}
923 manager._sleep_mode_scripts = {app_not_in_desktop: test_context.Mock()}
924
925 def mock_is_in_desktop_func(app):
926 return app == app_in_desktop
927
928 mock_is_in_desktop.side_effect = mock_is_in_desktop_func
929 manager.reclaim_scripts()
930 assert app_in_desktop in manager.app_scripts
931 assert app_not_in_desktop not in manager.app_scripts
932 assert app_not_in_desktop not in manager.toolkit_scripts
933 assert app_not_in_desktop not in manager.custom_scripts
934 assert app_not_in_desktop not in manager._sleep_mode_scripts
935 else:
936 manager.app_scripts = {app_not_in_desktop: test_context.Mock()}
937 if case["has_key_error"]:
938 manager.toolkit_scripts = {}
939 manager.custom_scripts = {}
940 manager._sleep_mode_scripts = {}
941 else:
942 manager.toolkit_scripts = {app_not_in_desktop: test_context.Mock()}
943 manager.custom_scripts = {app_not_in_desktop: test_context.Mock()}
944 manager._sleep_mode_scripts = {app_not_in_desktop: test_context.Mock()}
945
946 mock_is_in_desktop.return_value = False
947 manager.reclaim_scripts()
948 assert app_not_in_desktop not in manager.app_scripts
949 if not case["has_key_error"]:
950 assert app_not_in_desktop not in manager.toolkit_scripts
951 assert app_not_in_desktop not in manager.custom_scripts
952 assert app_not_in_desktop not in manager._sleep_mode_scripts
953
954 def test_get_manager(self, test_context: OrcaTestContext) -> None:
955 """Test script_manager.get_manager."""
956
957 self._setup_dependencies(test_context)
958 from orca import script_manager
959
960 manager1 = script_manager.get_manager()
961 manager2 = script_manager.get_manager()
962 assert manager1 is manager2
963 assert isinstance(manager1, script_manager.ScriptManager)