Debian Codegraph @

tests/unit_tests/test_debugging_tools_manager.py

raw
1 # Unit tests for debugging_tools_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
30 """Unit tests for debugging_tools_manager.py methods."""
31
32 from __future__ import annotations
33
34 from typing import TYPE_CHECKING
35 from unittest.mock import call
36
37 import gi
38 import pytest
39
40 gi.require_version("Atspi", "2.0")
41 from gi.repository import Atspi
42
43 if TYPE_CHECKING:
44 from unittest.mock import MagicMock
45
46 from .orca_test_context import OrcaTestContext
47
48
49 @pytest.mark.unit
50 class TestDebuggingToolsManager:
51 """Test DebuggingToolsManager class methods."""
52
53 def _setup_dependencies(self, test_context: OrcaTestContext) -> dict[str, MagicMock]:
54 """Set up mocks for debugging_tools_manager dependencies."""
55
56 additional_modules = [
57 "orca.orca_platform",
58 "orca.ax_utilities",
59 "orca.ax_utilities_debugging",
60 "faulthandler",
61 "subprocess",
62 "orca.braille_presenter",
63 "orca.presentation_manager",
64 ]
65 essential_modules = test_context.setup_shared_dependencies(additional_modules)
66
67 debug_mock = essential_modules["orca.debug"]
68 debug_mock.debugFile = None
69 debug_mock.debugLevel = 1000
70 debug_mock.LEVEL_ALL = 0
71 debug_mock.LEVEL_INFO = 800
72 debug_mock.LEVEL_WARNING = 900
73 debug_mock.LEVEL_SEVERE = 1000
74 debug_mock.LEVEL_OFF = 10000
75 debug_mock.print_message = test_context.Mock()
76
77 cmdnames_mock = essential_modules["orca.cmdnames"]
78 cmdnames_mock.DEBUG_CYCLE_LEVEL = "cycleDebugLevel"
79 cmdnames_mock.DEBUG_CLEAR_ATSPI_CACHE_FOR_APPLICATION = "clearAtSpiCache"
80
81 input_event_mock = essential_modules["orca.input_event"]
82 input_event_handler_mock = test_context.Mock()
83 input_event_mock.InputEventHandler = test_context.Mock(
84 return_value=input_event_handler_mock,
85 )
86 input_event_mock.InputEvent = test_context.Mock
87
88 keybindings_mock = essential_modules["orca.keybindings"]
89 key_bindings_instance = test_context.Mock()
90 key_bindings_instance.is_empty = test_context.Mock(return_value=True)
91 key_bindings_instance.remove_key_grabs = test_context.Mock(return_value=None)
92 key_bindings_instance.add = test_context.Mock(return_value=None)
93 keybindings_mock.KeyBindings = test_context.Mock(return_value=key_bindings_instance)
94 keybindings_mock.KeyBinding = test_context.Mock()
95 keybindings_mock.DEFAULT_MODIFIER_MASK = 1
96 keybindings_mock.NO_MODIFIER_MASK = 0
97
98 messages_mock = essential_modules["orca.messages"]
99 messages_mock.DEBUG_CLEAR_CACHE_FAILED = "Failed to clear cache"
100 messages_mock.DEBUG_CLEAR_CACHE = "Cache cleared"
101
102 orca_platform_mock = essential_modules["orca.orca_platform"]
103 orca_platform_mock.version = "3.50.0"
104 orca_platform_mock.revision = "abc123"
105
106 focus_manager_mock = essential_modules["orca.focus_manager"]
107 focus_manager_instance = test_context.Mock()
108 focus_manager_instance.get_active_mode_and_object_of_interest = test_context.Mock(
109 return_value=("focus", test_context.Mock(spec=Atspi.Accessible)),
110 )
111 focus_manager_mock.get_manager = test_context.Mock(return_value=focus_manager_instance)
112
113 ax_object_mock = essential_modules["orca.ax_object"]
114 ax_object_mock.get_name = test_context.Mock(return_value="TestApp")
115 ax_object_mock.clear_cache = test_context.Mock()
116
117 ax_utilities_mock = essential_modules["orca.ax_utilities"]
118 ax_utilities_mock.get_application = test_context.Mock(
119 return_value=test_context.Mock(spec=Atspi.Accessible),
120 )
121 test_apps = [
122 test_context.Mock(spec=Atspi.Accessible),
123 test_context.Mock(spec=Atspi.Accessible),
124 ]
125 ax_utilities_mock.get_all_applications = test_context.Mock(return_value=test_apps)
126 ax_utilities_mock.get_process_id = test_context.Mock(return_value=12345)
127 ax_utilities_mock.is_application_unresponsive = test_context.Mock(return_value=False)
128
129 ax_utilities_debugging_mock = essential_modules["orca.ax_utilities_debugging"]
130 ax_utilities_debugging_mock.as_string = test_context.Mock(return_value="debug_info")
131
132 faulthandler_mock = essential_modules["faulthandler"]
133 faulthandler_mock.enable = test_context.Mock()
134
135 subprocess_mock = essential_modules["subprocess"]
136 subprocess_mock.getoutput = test_context.Mock(return_value="test_command")
137 subprocess_mock.SubprocessError = Exception
138
139 essential_modules["input_event_handler"] = input_event_handler_mock
140 essential_modules["key_bindings_instance"] = key_bindings_instance
141 essential_modules["focus_manager_instance"] = focus_manager_instance
142
143 return essential_modules
144
145 @pytest.mark.parametrize(
146 "debug_file_config",
147 [
148 pytest.param(None, id="basic"),
149 pytest.param("mock_file", id="with_debug_file"),
150 pytest.param(None, id="without_debug_file"),
151 ],
152 )
153 def test_init_scenarios(
154 self,
155 test_context: OrcaTestContext,
156 debug_file_config: str | None,
157 ) -> None:
158 """Test DebuggingToolsManager.__init__ with various scenarios."""
159 essential_modules: dict[str, MagicMock] = self._setup_dependencies(test_context)
160
161 if debug_file_config == "mock_file":
162 debug_file_mock = test_context.Mock()
163 debug_file_mock.name = "/tmp/debug.log"
164 essential_modules["orca.debug"].debugFile = debug_file_mock
165 test_context.patch("os.path.exists", return_value=True)
166 elif debug_file_config is None:
167 essential_modules["orca.debug"].debugFile = None
168
169 from orca import command_manager
170 from orca.debugging_tools_manager import DebuggingToolsManager
171
172 manager = DebuggingToolsManager()
173
174 assert manager is not None
175 # Commands are registered with CommandManager
176 cmd_manager = command_manager.get_manager()
177 assert cmd_manager is not None
178
179 def test_setup_registers_commands(self, test_context: OrcaTestContext) -> None:
180 """Test DebuggingToolsManager.setup registers commands."""
181 self._setup_dependencies(test_context)
182 from orca import command_manager
183 from orca.debugging_tools_manager import DebuggingToolsManager
184
185 manager = DebuggingToolsManager()
186 manager.set_up_commands()
187
188 # Commands are registered with CommandManager
189 cmd_manager = command_manager.get_manager()
190 assert cmd_manager.get_keyboard_command("cycleDebugLevelHandler") is not None
191 assert cmd_manager.get_keyboard_command("clear_atspi_app_cache") is not None
192
193 @pytest.mark.parametrize(
194 "initial_level,expected_level,expected_message,expected_brief,has_event",
195 [
196 pytest.param(0, 800, "Debug level info.", "info", False, id="all_to_info"),
197 pytest.param(10000, 0, "Debug level all.", "all", False, id="off_to_all"),
198 pytest.param(
199 800,
200 900,
201 "Debug level warning.",
202 "warning",
203 True,
204 id="info_to_warning_with_event",
205 ),
206 pytest.param(900, 1000, "Debug level severe.", "severe", False, id="warning_to_severe"),
207 pytest.param(1000, 10000, "Debug level off.", "off", False, id="severe_to_off"),
208 ],
209 )
210 def test_cycle_debug_level_comprehensive(
211 self,
212 test_context: OrcaTestContext,
213 initial_level: int,
214 expected_level: int,
215 expected_message: str,
216 expected_brief: str,
217 has_event: bool,
218 ) -> None:
219 """Test DebuggingToolsManager._cycle_debug_level cycling through all levels."""
220
221 essential_modules: dict[str, MagicMock] = self._setup_dependencies(test_context)
222 essential_modules["orca.debug"].debugLevel = initial_level
223 from orca.debugging_tools_manager import DebuggingToolsManager
224
225 manager = DebuggingToolsManager()
226 script_mock = test_context.Mock()
227 event_mock = test_context.Mock() if has_event else None
228
229 result = manager._cycle_debug_level(script_mock, event_mock)
230 assert result
231 assert essential_modules["orca.debug"].debugLevel == expected_level
232 pres_manager = essential_modules["orca.presentation_manager"].get_manager()
233 pres_manager.present_message.assert_called_with(expected_message, expected_brief)
234
235 @pytest.mark.parametrize(
236 "test_scenario,focus_object,application_object,expected_message,"
237 "expects_clear_cache,expects_debug_call",
238 [
239 pytest.param(
240 "success",
241 "mock_obj",
242 "mock_app",
243 "Cache cleared",
244 True,
245 False,
246 id="successful_cache_clear",
247 ),
248 pytest.param(
249 "null_object",
250 None,
251 "mock_app",
252 "Failed to clear cache",
253 False,
254 True,
255 id="null_object_failure",
256 ),
257 pytest.param(
258 "null_application",
259 "mock_obj",
260 None,
261 "Failed to clear cache",
262 False,
263 True,
264 id="null_application_failure",
265 ),
266 ],
267 )
268 def test_clear_atspi_app_cache_comprehensive(
269 self,
270 test_context: OrcaTestContext,
271 test_scenario: str,
272 focus_object: str | None,
273 application_object: str | None,
274 expected_message: str,
275 expects_clear_cache: bool,
276 expects_debug_call: bool,
277 ) -> None:
278 """Test DebuggingToolsManager._clear_atspi_app_cache with various scenarios."""
279
280 essential_modules: dict[str, MagicMock] = self._setup_dependencies(test_context)
281 from orca.debugging_tools_manager import DebuggingToolsManager
282
283 manager = DebuggingToolsManager()
284 script_mock = test_context.Mock()
285
286 test_obj = test_context.Mock(spec=Atspi.Accessible) if focus_object else None
287 test_app = test_context.Mock(spec=Atspi.Accessible) if application_object else None
288
289 if test_scenario == "null_object":
290 focus_instance = essential_modules["focus_manager_instance"]
291 focus_instance.get_active_mode_and_object_of_interest.return_value = ("focus", None)
292 else:
293 mock_focus_instance = test_context.Mock()
294 mock_focus_instance.get_active_mode_and_object_of_interest.return_value = (
295 "focus",
296 test_obj,
297 )
298 test_context.patch(
299 "orca.debugging_tools_manager.focus_manager.get_manager",
300 return_value=mock_focus_instance,
301 )
302
303 test_context.patch(
304 "orca.debugging_tools_manager.AXUtilities.get_application",
305 return_value=test_app,
306 )
307
308 mock_clear_cache = test_context.patch("orca.debugging_tools_manager.AXObject.clear_cache")
309 mock_debug_print = test_context.patch("orca.debugging_tools_manager.debug.print_message")
310
311 result = manager._clear_atspi_app_cache(script_mock)
312 assert result
313 pres_manager = essential_modules["orca.presentation_manager"].get_manager()
314 pres_manager.present_message.assert_called_with(expected_message)
315
316 if expects_clear_cache:
317 mock_clear_cache.assert_called_once_with(
318 test_app,
319 recursive=True,
320 reason="User request.",
321 )
322 else:
323 mock_clear_cache.assert_not_called()
324
325 if expects_debug_call:
326 if test_scenario == "null_object":
327 debug_calls = [
328 call
329 for call in essential_modules["orca.debug"].print_message.call_args_list
330 if "Cannot clear cache on null object" in str(call)
331 ]
332 assert len(debug_calls) >= 1
333 else:
334 mock_debug_print.assert_called()
335
336 @pytest.mark.parametrize(
337 "test_method,scenario_data",
338 [
339 pytest.param(
340 "_get_running_applications_as_string_iter",
341 {
342 "is_command_line": True,
343 "app_count": 2,
344 "expected_length": 3,
345 "header_contains": "Desktop has 2 app(s):",
346 },
347 id="get_running_apps_cli",
348 ),
349 pytest.param(
350 "_get_running_applications_as_string_iter",
351 {
352 "is_command_line": False,
353 "app_count": 1,
354 "expected_length": 2,
355 "header_contains": "DEBUGGING TOOLS MANAGER:",
356 },
357 id="get_running_apps_not_cli",
358 ),
359 ],
360 )
361 def test_debug_utility_methods(
362 self,
363 test_context: OrcaTestContext,
364 test_method: str,
365 scenario_data: dict,
366 ) -> None:
367 """Test DebuggingToolsManager debug utility methods."""
368 self._setup_dependencies(test_context)
369 from orca.debugging_tools_manager import DebuggingToolsManager
370
371 manager = DebuggingToolsManager()
372
373 if test_method == "_get_running_applications_as_string_iter":
374 app_count = scenario_data["app_count"]
375 test_apps = [test_context.Mock(spec=Atspi.Accessible) for _ in range(app_count)]
376
377 test_context.patch(
378 "orca.debugging_tools_manager.AXUtilities.get_all_applications",
379 return_value=test_apps,
380 )
381 test_context.patch(
382 "orca.debugging_tools_manager.AXUtilities.get_process_id",
383 return_value=12345,
384 )
385 test_context.patch(
386 "orca.debugging_tools_manager.AXUtilities.is_application_unresponsive",
387 return_value=False,
388 )
389 test_context.patch(
390 "orca.debugging_tools_manager.AXObject.get_name",
391 return_value="TestApp",
392 )
393 test_context.patch(
394 "orca.debugging_tools_manager.subprocess.getoutput",
395 return_value="test_command",
396 )
397
398 result_list = list(
399 manager._get_running_applications_as_string_iter(
400 is_command_line=scenario_data["is_command_line"],
401 ),
402 )
403 assert len(result_list) == scenario_data["expected_length"]
404 assert scenario_data["header_contains"] in result_list[0]
405
406 @pytest.mark.parametrize(
407 "force,is_command_line,debug_level,expects_method_call,expects_debug,expects_stdout",
408 [
409 pytest.param(True, False, 1000, True, True, False, id="force_true_not_cli"),
410 pytest.param(False, True, 1000, True, False, True, id="no_force_cli"),
411 pytest.param(False, False, 900, False, False, False, id="debug_level_too_low"),
412 ],
413 )
414 def test_print_running_applications(
415 self,
416 test_context: OrcaTestContext,
417 force: bool,
418 is_command_line: bool,
419 debug_level: int,
420 expects_method_call: bool,
421 expects_debug: bool,
422 expects_stdout: bool,
423 capsys,
424 ) -> None:
425 """Test DebuggingToolsManager.print_running_applications."""
426 essential_modules: dict[str, MagicMock] = self._setup_dependencies(test_context)
427 essential_modules["orca.debug"].debugLevel = debug_level
428 from orca.debugging_tools_manager import DebuggingToolsManager
429
430 manager = DebuggingToolsManager()
431 expected_output = ["Header", "App 1", "App 2"]
432 mock_get_apps = test_context.patch_object(
433 manager,
434 "_get_running_applications_as_string_iter",
435 return_value=expected_output,
436 )
437
438 manager.print_running_applications(force=force, is_command_line=is_command_line)
439
440 if not expects_method_call:
441 mock_get_apps.assert_not_called()
442 else:
443 mock_get_apps.assert_called_once()
444 if expects_debug:
445 expected_calls = [call(1000, line, True) for line in expected_output]
446 essential_modules["orca.debug"].print_message.assert_has_calls(expected_calls)
447 if expects_stdout:
448 captured = capsys.readouterr()
449 for line in expected_output:
450 assert line in captured.out
451
452 @pytest.mark.parametrize(
453 "is_command_line,revision,session_type,session_desktop,"
454 "expects_stdout,expects_revision,expects_session",
455 [
456 pytest.param(
457 True,
458 "abc123",
459 "wayland",
460 "gnome",
461 True,
462 True,
463 True,
464 id="cli_with_revision_and_session",
465 ),
466 pytest.param(
467 False,
468 "abc123",
469 "x11",
470 "",
471 False,
472 True,
473 True,
474 id="not_cli_x11_no_desktop",
475 ),
476 pytest.param(
477 False,
478 None,
479 "wayland",
480 "gnome",
481 False,
482 False,
483 True,
484 id="not_cli_no_revision",
485 ),
486 pytest.param(
487 False,
488 "abc123",
489 None,
490 None,
491 False,
492 True,
493 False,
494 id="not_cli_no_session_env",
495 ),
496 ],
497 )
498 def test_print_session_details_comprehensive( # pylint: disable=too-many-branches
499 self,
500 test_context: OrcaTestContext,
501 is_command_line: bool,
502 revision: str | None,
503 session_type: str | None,
504 session_desktop: str | None,
505 expects_stdout: bool,
506 expects_revision: bool,
507 expects_session: bool,
508 capsys,
509 ) -> None:
510 """Test DebuggingToolsManager.print_session_details with various scenarios."""
511
512 essential_modules: dict[str, MagicMock] = self._setup_dependencies(test_context)
513 if revision is None:
514 essential_modules["orca.orca_platform"].revision = None
515
516 mock_atspi = test_context.Mock()
517 mock_atspi.get_version.return_value = (2, 48, 0)
518 test_context.patch("gi.repository.Atspi", new=mock_atspi)
519
520 env_patches = {}
521 remove_vars = []
522
523 if session_type:
524 env_patches["XDG_SESSION_TYPE"] = session_type
525 else:
526 remove_vars.append("XDG_SESSION_TYPE")
527
528 if session_desktop:
529 env_patches["XDG_SESSION_DESKTOP"] = session_desktop
530 else:
531 remove_vars.append("XDG_SESSION_DESKTOP")
532
533 test_context.patch_env(env_patches, remove_vars=remove_vars)
534
535 from orca.debugging_tools_manager import DebuggingToolsManager
536
537 manager = DebuggingToolsManager()
538 manager.print_session_details(is_command_line=is_command_line)
539
540 if expects_stdout:
541 captured = capsys.readouterr()
542 assert "Orca version 3.50.0" in captured.out
543 assert "AT-SPI2 version: 2.48.0" in captured.out
544
545 if expects_revision:
546 assert "rev abc123" in captured.out
547
548 if expects_session:
549 if session_desktop:
550 assert f"Session: {session_type} {session_desktop}" in captured.out
551 else:
552 assert f"Session: {session_type}" in captured.out
553 else:
554 session_calls = [
555 call
556 for call in essential_modules["orca.debug"].print_message.call_args_list
557 if "Orca version" in str(call)
558 ]
559 assert len(session_calls) >= 1
560 call_args = session_calls[0]
561
562 if not is_command_line:
563 assert "DEBUGGING TOOLS MANAGER:" in call_args[0][1]
564
565 assert "Orca version 3.50.0" in call_args[0][1]
566 assert "AT-SPI2 version: 2.48.0" in call_args[0][1]
567
568 if expects_revision:
569 assert "rev abc123" in call_args[0][1]
570 else:
571 assert "rev" not in call_args[0][1]
572
573 if expects_session:
574 if session_desktop:
575 assert f"Session: {session_type} {session_desktop}" in call_args[0][1]
576 else:
577 assert f"Session: {session_type}" in call_args[0][1]
578 else:
579 assert "Session:" not in call_args[0][1]
580
581 def test_get_manager_singleton(self, test_context: OrcaTestContext) -> None:
582 """Test debugging_tools_manager.get_manager singleton behavior."""
583 self._setup_dependencies(test_context)
584 from orca import command_manager, debugging_tools_manager
585
586 manager1 = debugging_tools_manager.get_manager()
587 manager2 = debugging_tools_manager.get_manager()
588
589 assert manager1 is manager2
590 # Commands are registered with CommandManager
591 cmd_manager = command_manager.get_manager()
592 assert cmd_manager is not None