Debian Codegraph @

tests/integration_tests/test_dbus_with_orca.py

raw
1 # Orca
2 #
3 # Copyright 2025 Valve Corporation
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=too-many-locals
22 # pylint: disable=too-many-statements
23 # pylint: disable=too-many-return-statements
24 # pylint: disable=too-many-lines
25 # pylint: disable=too-many-branches
26
27 """Integration tests for Orca's D-Bus service."""
28
29 from __future__ import annotations
30
31 import os
32 from typing import TYPE_CHECKING, Any
33
34 import pytest
35 from dasbus.error import DBusError
36 from gi.repository import GLib
37
38 if TYPE_CHECKING:
39 from collections.abc import Callable
40
41 from dasbus.client.proxy import ObjectProxy as DBusProxy
42
43 # Get configurable timeout values from environment variables
44 DEFAULT_MODULE_TIMEOUT = 15
45 FLAT_REVIEW_TIMEOUT = int(os.environ.get("ORCA_FLAT_REVIEW_TIMEOUT", str(DEFAULT_MODULE_TIMEOUT)))
46 STRUCTURAL_NAVIGATOR_TIMEOUT = int(
47 os.environ.get("ORCA_STRUCTURAL_NAVIGATOR_TIMEOUT", str(DEFAULT_MODULE_TIMEOUT)),
48 )
49 SPEECH_MANAGER_TIMEOUT = int(os.environ.get("ORCA_SPEECH_MANAGER_TIMEOUT", "30"))
50 SPEECH_PRESENTER_TIMEOUT = int(os.environ.get("ORCA_SPEECH_PRESENTER_TIMEOUT", "30"))
51
52 MODULE_TIMEOUTS = {
53 "FlatReviewPresenter": FLAT_REVIEW_TIMEOUT,
54 "StructuralNavigator": STRUCTURAL_NAVIGATOR_TIMEOUT,
55 "SpeechManager": SPEECH_MANAGER_TIMEOUT,
56 "SpeechPresenter": SPEECH_PRESENTER_TIMEOUT,
57 }
58
59 # Modules that may not be present in all environments (e.g., X11 vs Wayland)
60 OPTIONAL_MODULES = {"MouseReviewer"}
61
62 MODULE_CONFIG = {
63 "ActionPresenter": {
64 "commands": ["ShowActionsList"],
65 "parameterized_commands": [],
66 "getters": [],
67 "setters": [],
68 "ui_commands": ["ShowActionsList"],
69 "toggle_commands": [],
70 "skip": [],
71 },
72 "ClipboardPresenter": {
73 "commands": ["PresentClipboardContents"],
74 "parameterized_commands": [],
75 "getters": [],
76 "setters": [],
77 "ui_commands": [],
78 "toggle_commands": [],
79 "skip": [],
80 },
81 "CommandManager": {
82 "commands": ["ToggleKeyboardLayout"],
83 "parameterized_commands": [],
84 "getters": ["DesktopModifierKeys", "KeyboardLayoutIsDesktop", "LaptopModifierKeys"],
85 "setters": ["DesktopModifierKeys", "KeyboardLayoutIsDesktop", "LaptopModifierKeys"],
86 "ui_commands": [],
87 "toggle_commands": ["ToggleKeyboardLayout"],
88 "skip": [],
89 },
90 "DocumentPresenter": {
91 "commands": [
92 "EnableStickyBrowseMode",
93 "EnableStickyFocusMode",
94 "TogglePresentationMode",
95 ],
96 "parameterized_commands": [],
97 "getters": [
98 "AutoStickyFocusModeForWebApps",
99 "BrowseModeIsSticky",
100 "FindResultsMinimumLength",
101 "FocusModeIsSticky",
102 "InFocusMode",
103 "NativeNavTriggersFocusMode",
104 "OnlySpeakChangedLines",
105 "PageSummaryOnLoad",
106 "SayAllOnLoad",
107 "SpeakFindResults",
108 ],
109 "setters": [
110 "AutoStickyFocusModeForWebApps",
111 "FindResultsMinimumLength",
112 "NativeNavTriggersFocusMode",
113 "OnlySpeakChangedLines",
114 "PageSummaryOnLoad",
115 "SayAllOnLoad",
116 "SpeakFindResults",
117 ],
118 "ui_commands": [],
119 "toggle_commands": ["TogglePresentationMode"],
120 "skip": [],
121 },
122 "MouseReviewer": {
123 "commands": ["Toggle"],
124 "parameterized_commands": [],
125 "getters": ["IsEnabled", "PresentTooltips"],
126 "setters": ["IsEnabled", "PresentTooltips"],
127 "ui_commands": [],
128 "toggle_commands": ["Toggle"],
129 "skip": [],
130 },
131 "FlatReviewPresenter": {
132 "commands": [
133 "AppendToClipboard",
134 "CopyToClipboard",
135 "GetCurrentObject",
136 "GoAbove",
137 "GoBelow",
138 "GoBottomLeft",
139 "GoEnd",
140 "GoEndOfLine",
141 "GoHome",
142 "GoNextCharacter",
143 "GoNextItem",
144 "GoNextLine",
145 "GoPreviousCharacter",
146 "GoPreviousItem",
147 "GoPreviousLine",
148 "GoStartOfLine",
149 "LeftClickOnObject",
150 "PhoneticItem",
151 "PhoneticLine",
152 "PresentCharacter",
153 "PresentItem",
154 "PresentLine",
155 "PresentObject",
156 "RightClickOnObject",
157 "RoutePointerToObject",
158 "SayAll",
159 "ShowContents",
160 "SpellCharacter",
161 "SpellItem",
162 "SpellLine",
163 "ToggleFlatReviewMode",
164 "ToggleRestrict",
165 "UnicodeCurrentCharacter",
166 ],
167 "parameterized_commands": [],
168 "getters": ["IsRestricted"],
169 "setters": ["IsRestricted"],
170 "ui_commands": [
171 "ShowContents",
172 "LeftClickOnObject",
173 "RightClickOnObject",
174 "RoutePointerToObject",
175 ],
176 "toggle_commands": ["ToggleFlatReviewMode", "ToggleRestrict"],
177 "skip": [],
178 },
179 "ObjectNavigator": {
180 "commands": [
181 "MoveToFirstChild",
182 "MoveToNextSibling",
183 "MoveToParent",
184 "MoveToPreviousSibling",
185 "PerformAction",
186 "ToggleSimplify",
187 ],
188 "parameterized_commands": [],
189 "getters": [],
190 "setters": [],
191 "ui_commands": ["PerformAction"],
192 "toggle_commands": ["ToggleSimplify"],
193 "skip": [],
194 },
195 "ProfileManager": {
196 "commands": [
197 "CycleSettingsProfile",
198 "PresentCurrentProfile",
199 ],
200 "parameterized_commands": [],
201 "getters": [
202 "ActiveProfile",
203 "AvailableProfiles",
204 "StartingProfile",
205 ],
206 "setters": [
207 "ActiveProfile",
208 "StartingProfile",
209 ],
210 "ui_commands": [],
211 "toggle_commands": [],
212 "skip": [],
213 },
214 "NotificationPresenter": {
215 "commands": [
216 "PresentLastNotification",
217 "PresentNextNotification",
218 "PresentPreviousNotification",
219 "ShowNotificationList",
220 ],
221 "parameterized_commands": [],
222 "getters": [],
223 "setters": [],
224 "ui_commands": ["ShowNotificationList"],
225 "toggle_commands": [],
226 "skip": [],
227 },
228 "SleepModeManager": {
229 "commands": ["ToggleSleepMode"],
230 "parameterized_commands": [],
231 "getters": [],
232 "setters": [],
233 "ui_commands": [],
234 "toggle_commands": ["ToggleSleepMode"],
235 "skip": [],
236 },
237 "SoundPresenter": {
238 "commands": [],
239 "parameterized_commands": [],
240 "getters": [
241 "BeepProgressBarUpdates",
242 "ProgressBarBeepInterval",
243 "ProgressBarBeepVerbosity",
244 "SoundIsEnabled",
245 "SoundVolume",
246 ],
247 "setters": [
248 "BeepProgressBarUpdates",
249 "ProgressBarBeepInterval",
250 "ProgressBarBeepVerbosity",
251 "SoundIsEnabled",
252 "SoundVolume",
253 ],
254 "ui_commands": [],
255 "toggle_commands": [],
256 "skip": [],
257 },
258 "SpeechManager": {
259 "commands": [
260 "CycleCapitalizationStyle",
261 "CyclePunctuationLevel",
262 "CycleSynthesizer",
263 "DecreasePitch",
264 "DecreaseRate",
265 "DecreaseVolume",
266 "IncreasePitch",
267 "IncreaseRate",
268 "IncreaseVolume",
269 "InterruptSpeech",
270 "RefreshSpeech",
271 "ShutdownSpeech",
272 "StartSpeech",
273 "ToggleSpeech",
274 ],
275 "parameterized_commands": ["GetVoicesForLanguage"],
276 "getters": [
277 "AutoLanguageSwitching",
278 "AvailableServers",
279 "AvailableSynthesizers",
280 "AvailableVoices",
281 "CapitalizationStyle",
282 "CurrentServer",
283 "CurrentSynthesizer",
284 "CurrentVoice",
285 "InsertPausesBetweenUtterances",
286 "Pitch",
287 "PunctuationLevel",
288 "Rate",
289 "SpeakNumbersAsDigits",
290 "SpeechIsEnabled",
291 "SpeechIsMuted",
292 "UseColorNames",
293 "UsePronunciationDictionary",
294 "Volume",
295 ],
296 "setters": [
297 "AutoLanguageSwitching",
298 "CapitalizationStyle",
299 "CurrentServer",
300 "CurrentSynthesizer",
301 "CurrentVoice",
302 "InsertPausesBetweenUtterances",
303 "Pitch",
304 "PunctuationLevel",
305 "Rate",
306 "SpeakNumbersAsDigits",
307 "SpeechIsEnabled",
308 "SpeechIsMuted",
309 "UseColorNames",
310 "UsePronunciationDictionary",
311 "Volume",
312 ],
313 "ui_commands": [],
314 "toggle_commands": ["ToggleSpeech"],
315 "skip": [],
316 },
317 "SpeechPresenter": {
318 "commands": [
319 "ChangeNumberStyle",
320 "ToggleIndentationAndJustification",
321 "ToggleMonitor",
322 "ToggleTableCellReadingMode",
323 "ToggleVerbosity",
324 ],
325 "parameterized_commands": [],
326 "getters": [
327 "AlwaysAnnounceSelectedRangeInSpreadsheet",
328 "AnnounceBlockquote",
329 "AnnounceCellCoordinates",
330 "AnnounceCellHeaders",
331 "AnnounceCellSpan",
332 "AnnounceForm",
333 "AnnounceGrouping",
334 "AnnounceLandmark",
335 "AnnounceList",
336 "AnnounceSpreadsheetCellCoordinates",
337 "AnnounceTable",
338 "MessagesAreDetailed",
339 "OnlySpeakDisplayedText",
340 "ProgressBarSpeechInterval",
341 "ProgressBarSpeechVerbosity",
342 "RepeatedCharacterLimit",
343 "SpeakBlankLines",
344 "SpeakDescription",
345 "SpeakIndentationAndJustification",
346 "SpeakIndentationOnlyIfChanged",
347 "SpeakMisspelledIndicator",
348 "SpeakPositionInSet",
349 "SpeakProgressBarUpdates",
350 "SpeakRowInDocumentTable",
351 "SpeakRowInGuiTable",
352 "SpeakRowInSpreadsheet",
353 "SpeakTutorialMessages",
354 "SpeakWidgetMnemonic",
355 "MonitorIsEnabled",
356 "MonitorFontSize",
357 "MonitorForeground",
358 "MonitorBackground",
359 "VerbosityLevel",
360 ],
361 "setters": [
362 "AlwaysAnnounceSelectedRangeInSpreadsheet",
363 "AnnounceBlockquote",
364 "AnnounceCellCoordinates",
365 "AnnounceCellHeaders",
366 "AnnounceCellSpan",
367 "AnnounceForm",
368 "AnnounceGrouping",
369 "AnnounceLandmark",
370 "AnnounceList",
371 "AnnounceSpreadsheetCellCoordinates",
372 "AnnounceTable",
373 "MessagesAreDetailed",
374 "OnlySpeakDisplayedText",
375 "ProgressBarSpeechInterval",
376 "ProgressBarSpeechVerbosity",
377 "RepeatedCharacterLimit",
378 "SpeakBlankLines",
379 "SpeakDescription",
380 "SpeakIndentationAndJustification",
381 "SpeakIndentationOnlyIfChanged",
382 "SpeakMisspelledIndicator",
383 "SpeakPositionInSet",
384 "SpeakProgressBarUpdates",
385 "SpeakRowInDocumentTable",
386 "SpeakRowInGuiTable",
387 "SpeakRowInSpreadsheet",
388 "SpeakTutorialMessages",
389 "SpeakWidgetMnemonic",
390 "MonitorIsEnabled",
391 "MonitorFontSize",
392 "MonitorForeground",
393 "MonitorBackground",
394 "VerbosityLevel",
395 ],
396 "ui_commands": [],
397 "toggle_commands": [
398 "ToggleIndentationAndJustification",
399 "ToggleTableCellReadingMode",
400 "ToggleVerbosity",
401 ],
402 "skip": [],
403 },
404 "SpellCheckPresenter": {
405 "commands": [],
406 "parameterized_commands": [],
407 "getters": ["PresentContext", "SpellError", "SpellSuggestion"],
408 "setters": ["PresentContext", "SpellError", "SpellSuggestion"],
409 "ui_commands": [],
410 "toggle_commands": [],
411 "skip": [],
412 },
413 "StructuralNavigator": {
414 "commands": [
415 "ContainerEnd",
416 "ContainerStart",
417 "CycleMode",
418 "ListBlockquotes",
419 "ListButtons",
420 "ListCheckboxes",
421 "ListClickables",
422 "ListComboboxes",
423 "ListEntries",
424 "ListFormFields",
425 "ListHeadings",
426 "ListHeadingsLevel1",
427 "ListHeadingsLevel2",
428 "ListHeadingsLevel3",
429 "ListHeadingsLevel4",
430 "ListHeadingsLevel5",
431 "ListHeadingsLevel6",
432 "ListIframes",
433 "ListImages",
434 "ListLandmarks",
435 "ListLargeObjects",
436 "ListLinks",
437 "ListListItems",
438 "ListLists",
439 "ListParagraphs",
440 "ListRadioButtons",
441 "ListTables",
442 "ListUnvisitedLinks",
443 "ListVisitedLinks",
444 "NextBlockquote",
445 "NextButton",
446 "NextCheckbox",
447 "NextClickable",
448 "NextCombobox",
449 "NextEntry",
450 "NextFormField",
451 "NextHeading",
452 "NextHeadingLevel1",
453 "NextHeadingLevel2",
454 "NextHeadingLevel3",
455 "NextHeadingLevel4",
456 "NextHeadingLevel5",
457 "NextHeadingLevel6",
458 "NextIframe",
459 "NextImage",
460 "NextLandmark",
461 "NextLargeObject",
462 "NextLink",
463 "NextList",
464 "NextListItem",
465 "NextLiveRegion",
466 "NextParagraph",
467 "NextRadioButton",
468 "NextSeparator",
469 "NextTable",
470 "NextUnvisitedLink",
471 "NextVisitedLink",
472 "PreviousBlockquote",
473 "PreviousButton",
474 "PreviousCheckbox",
475 "PreviousClickable",
476 "PreviousCombobox",
477 "PreviousEntry",
478 "PreviousFormField",
479 "PreviousHeading",
480 "PreviousHeadingLevel1",
481 "PreviousHeadingLevel2",
482 "PreviousHeadingLevel3",
483 "PreviousHeadingLevel4",
484 "PreviousHeadingLevel5",
485 "PreviousHeadingLevel6",
486 "PreviousIframe",
487 "PreviousImage",
488 "PreviousLandmark",
489 "PreviousLargeObject",
490 "PreviousLink",
491 "PreviousList",
492 "PreviousListItem",
493 "PreviousLiveRegion",
494 "PreviousParagraph",
495 "PreviousRadioButton",
496 "PreviousSeparator",
497 "PreviousTable",
498 "PreviousUnvisitedLink",
499 "PreviousVisitedLink",
500 ],
501 "parameterized_commands": [],
502 "getters": [
503 "IsEnabled",
504 "LargeObjectTextLength",
505 "NavigationWraps",
506 "TriggersFocusMode",
507 ],
508 "setters": [
509 "IsEnabled",
510 "LargeObjectTextLength",
511 "NavigationWraps",
512 "TriggersFocusMode",
513 ],
514 "ui_commands": [
515 "ListBlockquotes",
516 "ListButtons",
517 "ListCheckboxes",
518 "ListClickables",
519 "ListComboboxes",
520 "ListEntries",
521 "ListFormFields",
522 "ListHeadings",
523 "ListHeadingsLevel1",
524 "ListHeadingsLevel2",
525 "ListHeadingsLevel3",
526 "ListHeadingsLevel4",
527 "ListHeadingsLevel5",
528 "ListHeadingsLevel6",
529 "ListIframes",
530 "ListImages",
531 "ListLandmarks",
532 "ListLargeObjects",
533 "ListLinks",
534 "ListListItems",
535 "ListLists",
536 "ListParagraphs",
537 "ListRadioButtons",
538 "ListTables",
539 "ListUnvisitedLinks",
540 "ListVisitedLinks",
541 ],
542 "toggle_commands": [],
543 "skip": ["CycleMode"], # Test flakiness depending on app and focus.
544 },
545 "SystemInformationPresenter": {
546 "commands": [
547 "PresentBatteryStatus",
548 "PresentCpuAndMemoryUsage",
549 "PresentDate",
550 "PresentTime",
551 ],
552 "parameterized_commands": [],
553 "getters": [
554 "DateFormat",
555 "TimeFormat",
556 "AvailableDateFormats",
557 "AvailableTimeFormats",
558 ],
559 "setters": [
560 "DateFormat",
561 "TimeFormat",
562 ],
563 "ui_commands": [],
564 "toggle_commands": [],
565 "skip": ["PresentBatteryStatus"], # Can timeout on systems without battery
566 },
567 "TextAttributeManager": {
568 "commands": [],
569 "parameterized_commands": [],
570 "getters": ["AttributesToBraille", "AttributesToSpeak"],
571 "setters": ["AttributesToBraille", "AttributesToSpeak"],
572 "ui_commands": [],
573 "toggle_commands": [],
574 "skip": [],
575 },
576 "TableNavigator": {
577 "commands": [
578 "ClearDynamicColumnHeadersRow",
579 "ClearDynamicRowHeadersColumn",
580 "MoveDown",
581 "MoveLeft",
582 "MoveRight",
583 "MoveToBeginningOfRow",
584 "MoveToBottomOfColumn",
585 "MoveToEndOfRow",
586 "MoveToFirstCell",
587 "MoveToLastCell",
588 "MoveToTopOfColumn",
589 "MoveUp",
590 "SetDynamicColumnHeadersRow",
591 "SetDynamicRowHeadersColumn",
592 "ToggleEnabled",
593 ],
594 "parameterized_commands": [],
595 "getters": ["IsEnabled", "SkipBlankCells"],
596 "setters": ["IsEnabled", "SkipBlankCells"],
597 "ui_commands": [],
598 "toggle_commands": ["ToggleEnabled"],
599 "skip": [],
600 },
601 "TypingEchoPresenter": {
602 "commands": ["CycleKeyEcho"],
603 "parameterized_commands": [],
604 "getters": [
605 "KeyEchoEnabled",
606 "CharacterEchoEnabled",
607 "WordEchoEnabled",
608 "SentenceEchoEnabled",
609 "AlphabeticKeysEnabled",
610 "NumericKeysEnabled",
611 "PunctuationKeysEnabled",
612 "SpaceEnabled",
613 "ModifierKeysEnabled",
614 "FunctionKeysEnabled",
615 "ActionKeysEnabled",
616 "NavigationKeysEnabled",
617 "DiacriticalKeysEnabled",
618 "LockingKeysPresented",
619 ],
620 "setters": [
621 "KeyEchoEnabled",
622 "CharacterEchoEnabled",
623 "WordEchoEnabled",
624 "SentenceEchoEnabled",
625 "AlphabeticKeysEnabled",
626 "NumericKeysEnabled",
627 "PunctuationKeysEnabled",
628 "SpaceEnabled",
629 "ModifierKeysEnabled",
630 "FunctionKeysEnabled",
631 "ActionKeysEnabled",
632 "NavigationKeysEnabled",
633 "DiacriticalKeysEnabled",
634 "LockingKeysPresented",
635 ],
636 "ui_commands": [],
637 "toggle_commands": [],
638 "skip": [],
639 },
640 "CaretNavigator": {
641 "commands": [
642 "ToggleEnabled",
643 "ToggleLayoutMode",
644 "NextCharacter",
645 "PreviousCharacter",
646 "NextWord",
647 "PreviousWord",
648 "NextLine",
649 "PreviousLine",
650 "StartOfLine",
651 "EndOfLine",
652 "StartOfFile",
653 "EndOfFile",
654 ],
655 "parameterized_commands": [],
656 "getters": ["IsEnabled", "LayoutMode", "TriggersFocusMode"],
657 "setters": ["IsEnabled", "LayoutMode", "TriggersFocusMode"],
658 "ui_commands": [],
659 "toggle_commands": ["ToggleEnabled", "ToggleLayoutMode"],
660 "skip": [],
661 },
662 "ChatPresenter": {
663 "commands": [
664 "PresentNextMessage",
665 "PresentPreviousMessage",
666 "ToggleBuddyTyping",
667 "ToggleMessageHistories",
668 "TogglePrefix",
669 ],
670 "parameterized_commands": [],
671 "getters": [
672 "AnnounceBuddyTyping",
673 "MessageVerbosity",
674 "RoomHistories",
675 "SpeakRoomName",
676 "SpeakRoomNameLast",
677 ],
678 "setters": [
679 "AnnounceBuddyTyping",
680 "MessageVerbosity",
681 "RoomHistories",
682 "SpeakRoomName",
683 "SpeakRoomNameLast",
684 ],
685 "ui_commands": [],
686 "toggle_commands": [],
687 "skip": [],
688 },
689 "SayAllPresenter": {
690 "commands": ["SayAll", "Rewind", "FastForward"],
691 "parameterized_commands": [],
692 "getters": [
693 "AnnounceBlockquote",
694 "AnnounceForm",
695 "AnnounceGrouping",
696 "AnnounceLandmark",
697 "AnnounceList",
698 "AnnounceTable",
699 "OnlySpeakDisplayedText",
700 "Style",
701 "StructuralNavigationEnabled",
702 "RewindAndFastForwardEnabled",
703 ],
704 "setters": [
705 "AnnounceBlockquote",
706 "AnnounceForm",
707 "AnnounceGrouping",
708 "AnnounceLandmark",
709 "AnnounceList",
710 "AnnounceTable",
711 "OnlySpeakDisplayedText",
712 "Style",
713 "StructuralNavigationEnabled",
714 "RewindAndFastForwardEnabled",
715 ],
716 "ui_commands": [],
717 "toggle_commands": [],
718 "skip": [],
719 },
720 "WhereAmIPresenter": {
721 "commands": [
722 "PresentCellFormula",
723 "PresentCharacterAttributes",
724 "PresentDefaultButton",
725 "PresentLink",
726 "PresentSelectedText",
727 "PresentSelection",
728 "PresentSizeAndPosition",
729 "PresentStatusBar",
730 "PresentTitle",
731 "WhereAmIBasic",
732 "WhereAmIDetailed",
733 ],
734 "parameterized_commands": [],
735 "getters": [],
736 "setters": [],
737 "ui_commands": [],
738 "toggle_commands": [],
739 "skip": [],
740 },
741 "BraillePresenter": {
742 "commands": ["ToggleMonitor"],
743 "parameterized_commands": [],
744 "getters": [
745 "AvailableContractionTables",
746 "BrailleIsEnabled",
747 "MonitorIsEnabled",
748 "MonitorCellCount",
749 "MonitorShowDots",
750 "MonitorForeground",
751 "MonitorBackground",
752 "BrailleProgressBarUpdates",
753 "ComputerBrailleAtCursorIsEnabled",
754 "ContractedBrailleIsEnabled",
755 "ContractionTable",
756 "DisplayAncestors",
757 "EndOfLineIndicatorIsEnabled",
758 "FlashMessageDuration",
759 "FlashMessagesAreDetailed",
760 "FlashMessagesAreEnabled",
761 "FlashMessagesArePersistent",
762 "LinkIndicator",
763 "PresentMnemonics",
764 "ProgressBarBrailleInterval",
765 "ProgressBarBrailleVerbosity",
766 "RolenameStyle",
767 "SelectorIndicator",
768 "TextAttributesIndicator",
769 "VerbosityLevel",
770 "WordWrapIsEnabled",
771 ],
772 "setters": [
773 "BrailleIsEnabled",
774 "MonitorIsEnabled",
775 "MonitorCellCount",
776 "MonitorShowDots",
777 "MonitorForeground",
778 "MonitorBackground",
779 "BrailleProgressBarUpdates",
780 "ComputerBrailleAtCursorIsEnabled",
781 "ContractedBrailleIsEnabled",
782 "ContractionTable",
783 "DisplayAncestors",
784 "EndOfLineIndicatorIsEnabled",
785 "FlashMessageDuration",
786 "FlashMessagesAreDetailed",
787 "FlashMessagesAreEnabled",
788 "FlashMessagesArePersistent",
789 "LinkIndicator",
790 "PresentMnemonics",
791 "ProgressBarBrailleInterval",
792 "ProgressBarBrailleVerbosity",
793 "RolenameStyle",
794 "SelectorIndicator",
795 "TextAttributesIndicator",
796 "VerbosityLevel",
797 "WordWrapIsEnabled",
798 ],
799 "ui_commands": [],
800 "toggle_commands": [],
801 "skip": [],
802 },
803 }
804
805 PARAMETERIZED_TEST_PARAMS = {
806 "GetVoicesForLanguage": {"language": "en", "variant": "", "notify_user": False},
807 }
808
809
810 def safe_call(func: Callable[..., Any], *args: Any, **kwargs: Any) -> Any | None:
811 """Safely call a function, returning result or None on error."""
812
813 try:
814 return func(*args, **kwargs)
815 except (DBusError, AttributeError, TypeError, ValueError):
816 return None
817
818
819 def extract_names(items: list[Any] | None) -> list[str]:
820 """Extract first element from list of tuples/lists, return empty list if None."""
821
822 return [item[0] for item in items] if items else []
823
824
825 def is_context_error(error_str: str) -> bool:
826 """Check if error indicates missing context (script/runtime).
827
828 This function checks for common error patterns that indicate the Orca
829 service is running but lacks the proper context (e.g., no active script
830 or application context) to execute the requested operation.
831 """
832
833 context_error_patterns = [
834 # NoneType attribute errors indicate missing objects/context
835 ("NoneType" in error_str and "attribute" in error_str),
836 # Script-related None errors indicate missing script context
837 ("script" in error_str and "None" in error_str),
838 # AT-SPI context missing
839 ("context" in error_str.lower() and "none" in error_str.lower()),
840 # Missing application object
841 ("application" in error_str.lower() and "none" in error_str.lower()),
842 ]
843
844 return any(pattern for pattern in context_error_patterns)
845
846
847 def is_timeout_error(error_str: str) -> bool:
848 """Check if error indicates a timeout condition."""
849
850 timeout_patterns = [
851 "timed out" in error_str.lower(),
852 "timeout" in error_str.lower(),
853 "deadline exceeded" in error_str.lower(),
854 "connection timeout" in error_str.lower(),
855 ]
856
857 return any(pattern for pattern in timeout_patterns)
858
859
860 def unpack_variant(value: Any) -> Any:
861 """Unpack a GLib.Variant if needed."""
862
863 return value.unpack() if hasattr(value, "unpack") else value
864
865
866 def get_alternative_value(
867 proxy: DBusProxy,
868 prop_name: str,
869 current_value: str | float | bool,
870 ) -> str | float | bool:
871 """Get an alternative value for testing setters, avoiding defaults when possible."""
872
873 try:
874 if prop_name == "CurrentServer":
875 servers = proxy.ExecuteRuntimeGetter("AvailableServers")
876 servers = unpack_variant(servers)
877 assert isinstance(current_value, str)
878 non_default = [s for s in servers if s != current_value and "default" not in s.lower()]
879 if non_default:
880 return non_default[0]
881 return next((s for s in servers if s != current_value), current_value)
882 if prop_name == "CurrentSynthesizer":
883 synths = proxy.ExecuteRuntimeGetter("AvailableSynthesizers")
884 synths = unpack_variant(synths)
885 assert isinstance(current_value, str)
886 non_default = [s for s in synths if s != current_value and "default" not in s.lower()]
887 if non_default:
888 return non_default[0]
889 return next((s for s in synths if s != current_value), current_value)
890 if prop_name == "CurrentVoice":
891 voices = proxy.ExecuteRuntimeGetter("AvailableVoices")
892 voices = unpack_variant(voices)
893 if voices and len(voices) > 1:
894 assert isinstance(current_value, str)
895 current_voice_name = current_value.split()[0] if current_value else ""
896 non_default = [
897 v[0]
898 for v in voices
899 if v[0] != current_voice_name and "default" not in v[0].lower()
900 ]
901 if non_default:
902 return non_default[0]
903 return next((v[0] for v in voices if v[0] != current_voice_name), current_value)
904 return current_value
905 return current_value
906 except (DBusError, AttributeError, TypeError, ValueError):
907 return current_value
908
909
910 def get_test_value(
911 proxy: DBusProxy,
912 prop_name: str,
913 current_value: str | float | bool,
914 ) -> str | float | bool:
915 """Generate an appropriate test value for a property."""
916
917 if isinstance(current_value, bool):
918 return not current_value
919 if isinstance(current_value, (int, float)):
920 return current_value + 1 if current_value < 100 else current_value - 1
921 if isinstance(current_value, str):
922 return get_alternative_value(proxy, prop_name, current_value)
923 if isinstance(current_value, list):
924 return list(reversed(current_value)) if len(current_value) > 1 else current_value
925 return current_value
926
927
928 def to_variant(value: str | bool | float | list) -> Any:
929 """Convert a Python value to GLib.Variant."""
930
931 if isinstance(value, bool):
932 return GLib.Variant("b", value)
933 if isinstance(value, str):
934 return GLib.Variant("s", value)
935 if isinstance(value, int):
936 return GLib.Variant("i", value)
937 if isinstance(value, float):
938 return GLib.Variant("d", value)
939 if isinstance(value, list):
940 return GLib.Variant("as", value)
941 return GLib.Variant("s", str(value))
942
943
944 @pytest.mark.dbus
945 class TestOrcaDBusIntegration:
946 """Integration tests for Orca D-Bus service using pytest features."""
947
948 @pytest.mark.dbus
949 def test_orca_dbus_service_running(self, dbus_service_proxy):
950 """Test that Orca D-Bus service is running and accessible."""
951
952 version = dbus_service_proxy.GetVersion()
953 assert version is not None
954 assert len(str(version)) > 0
955
956 @pytest.mark.dbus
957 def test_list_modules(self, dbus_service_proxy):
958 """Test listing available modules."""
959
960 modules = list(dbus_service_proxy.ListModules())
961 assert isinstance(modules, list)
962
963 expected_modules = set(MODULE_CONFIG.keys()) - OPTIONAL_MODULES
964 actual_modules = set(modules)
965 missing_modules = expected_modules - actual_modules
966
967 assert not missing_modules, f"Missing expected modules: {missing_modules}"
968
969 @pytest.mark.dbus
970 def test_present_message(self, dbus_service_proxy):
971 """Test the PresentMessage service command."""
972
973 dbus_service_proxy.PresentMessage("Integration test message")
974
975 # TODO - JD: What we really want to do is verify that the message was presented.
976 # That will require we have a way to capture the speech and braille. Until then,
977 # verify service is still responsive after presentation.
978 version = dbus_service_proxy.GetVersion()
979 assert version is not None
980
981 @pytest.mark.dbus
982 def test_error_handling(self, dbus_service_proxy):
983 """Test error handling for invalid D-Bus calls."""
984
985 with pytest.raises((DBusError, AttributeError, TypeError)):
986 dbus_service_proxy.NonExistentMethod()
987
988 @pytest.mark.parametrize(
989 "module_name,config",
990 MODULE_CONFIG.items(),
991 ids=list(MODULE_CONFIG.keys()),
992 )
993 @pytest.mark.dbus
994 def test_module_capabilities(self, module_proxy_factory, run_with_timeout, module_name, config):
995 """Test that each module reports correct capabilities."""
996 # Skip optional modules that aren't available
997 if module_name in OPTIONAL_MODULES:
998 try:
999 proxy = module_proxy_factory(module_name)
1000 # Check if module has the required dbus interface
1001 if not hasattr(proxy, "ExecuteRuntimeGetter"):
1002 pytest.skip(f"{module_name} is optional and not available")
1003 except (DBusError, AttributeError):
1004 pytest.skip(f"{module_name} is optional and not available")
1005
1006 print(f"\n Testing {module_name} capabilities:")
1007 for cap_type in ["commands", "parameterized_commands", "getters", "setters"]:
1008 items = config.get(cap_type, [])
1009 if items:
1010 print(f" • {cap_type}: {len(items)} items")
1011 for item in sorted(items)[:5]: # Show first 5 items
1012 print(f" - {item}")
1013 if len(items) > 5:
1014 print(f" - ... and {len(items) - 5} more")
1015
1016 def get_capabilities():
1017 proxy = module_proxy_factory(module_name)
1018 return {
1019 "commands": extract_names(safe_call(proxy.ListCommands)),
1020 "parameterized_commands": extract_names(safe_call(proxy.ListParameterizedCommands)),
1021 "getters": extract_names(safe_call(proxy.ListRuntimeGetters)),
1022 "setters": extract_names(safe_call(proxy.ListRuntimeSetters)),
1023 }
1024
1025 timeout = MODULE_TIMEOUTS.get(module_name)
1026 result = run_with_timeout(get_capabilities, timeout)
1027 assert result["success"], f"Failed to get {module_name} capabilities: {result['error']}"
1028
1029 for cap_type in ["commands", "parameterized_commands", "getters", "setters"]:
1030 expected = set(config.get(cap_type, []))
1031 actual = set(result["result"].get(cap_type, []))
1032 missing = expected - actual
1033 unexpected = actual - expected
1034
1035 assert not missing, f"{module_name} missing {cap_type}: {sorted(missing)}"
1036 assert not unexpected, f"{module_name} unexpected {cap_type}: {sorted(unexpected)}"
1037
1038 @pytest.mark.parametrize(
1039 "module_name,config",
1040 [(name, config) for name, config in MODULE_CONFIG.items() if config.get("commands")],
1041 ids=[name for name, config in MODULE_CONFIG.items() if config.get("commands")],
1042 )
1043 @pytest.mark.dbus
1044 def test_module_commands(self, module_proxy_factory, run_with_timeout, module_name, config):
1045 """Test that module commands execute without errors."""
1046 # Skip optional modules that aren't available
1047 if module_name in OPTIONAL_MODULES:
1048 try:
1049 proxy = module_proxy_factory(module_name)
1050 # Check if module has the required dbus interface
1051 if not hasattr(proxy, "ExecuteRuntimeGetter"):
1052 pytest.skip(f"{module_name} is optional and not available")
1053 except (DBusError, AttributeError):
1054 pytest.skip(f"{module_name} is optional and not available")
1055
1056 commands = config["commands"]
1057 ui_commands = config.get("ui_commands", [])
1058 toggle_commands = config.get("toggle_commands", [])
1059 skip_commands = config.get("skip", [])
1060 print(f"\n Testing {module_name} commands ({len(commands)} total):")
1061 for cmd in sorted(commands):
1062 status_parts = []
1063 if cmd in ui_commands:
1064 status_parts.append("UI - skipped")
1065 if cmd in skip_commands:
1066 status_parts.append("skipped")
1067 if cmd in toggle_commands:
1068 status_parts.append("toggle - restore state")
1069 status = f"({', '.join(status_parts)})" if status_parts else ""
1070 print(f" • {cmd} {status}")
1071
1072 def test_single_command(proxy, cmd_name, ui_commands, toggle_commands, skip_commands):
1073 if cmd_name in ui_commands or cmd_name in skip_commands:
1074 return {"success": True, "skipped": True}
1075 try:
1076 proxy.ExecuteCommand(cmd_name, False)
1077 if cmd_name in toggle_commands:
1078 print(f" → Restoring {cmd_name} to original state")
1079 proxy.ExecuteCommand(cmd_name, False)
1080 return {"success": True}
1081 except (DBusError, AttributeError, TypeError, ValueError) as error:
1082 error_str = str(error)
1083 if is_context_error(error_str) or is_timeout_error(error_str):
1084 return {"success": True, "context_required": True}
1085 return {"success": False, "error": error_str}
1086
1087 def test_commands():
1088 proxy = module_proxy_factory(module_name)
1089 ui_commands = config.get("ui_commands", [])
1090 toggle_commands = config.get("toggle_commands", [])
1091 skip_commands = config.get("skip", [])
1092 return {
1093 cmd: test_single_command(proxy, cmd, ui_commands, toggle_commands, skip_commands)
1094 for cmd in config["commands"]
1095 }
1096
1097 timeout = MODULE_TIMEOUTS.get(module_name)
1098 result = run_with_timeout(test_commands, timeout)
1099 assert result["success"], f"Failed to test {module_name} commands: {result['error']}"
1100
1101 failed = [
1102 f"{cmd}: {res['error']}"
1103 for cmd, res in result["result"].items()
1104 if not res["success"] and not res.get("skipped")
1105 ]
1106 assert not failed, f"{module_name} command failures: {failed}"
1107
1108 @pytest.mark.parametrize(
1109 "module_name,config",
1110 [
1111 (name, config)
1112 for name, config in MODULE_CONFIG.items()
1113 if config.get("parameterized_commands")
1114 ],
1115 ids=[
1116 name for name, config in MODULE_CONFIG.items() if config.get("parameterized_commands")
1117 ],
1118 )
1119 @pytest.mark.dbus
1120 def test_module_parameterized_commands(
1121 self,
1122 module_proxy_factory,
1123 run_with_timeout,
1124 module_name,
1125 config,
1126 ):
1127 """Test that module parameterized commands execute with proper parameters."""
1128 param_commands = config["parameterized_commands"]
1129 print(f"\n Testing {module_name} parameterized commands ({len(param_commands)} total):")
1130 for cmd in sorted(param_commands):
1131 params = PARAMETERIZED_TEST_PARAMS.get(cmd, {})
1132 param_str = ", ".join(f"{k}={v}" for k, v in params.items())
1133 print(f" • {cmd}({param_str})")
1134
1135 def test_single_param_command(proxy, cmd_name):
1136 params = PARAMETERIZED_TEST_PARAMS.get(cmd_name, {})
1137 if not params:
1138 return {"success": False, "error": "No test parameters"}
1139
1140 try:
1141 variant_params = {k: to_variant(v) for k, v in params.items() if k != "notify_user"}
1142 notify_user = params.get("notify_user", False)
1143 result = proxy.ExecuteParameterizedCommand(cmd_name, variant_params, notify_user)
1144 return {"success": True, "result": result}
1145 except (DBusError, AttributeError, TypeError, ValueError) as error:
1146 if is_context_error(str(error)):
1147 return {"success": True, "context_required": True}
1148 return {"success": False, "error": str(error)}
1149
1150 def test_parameterized_commands():
1151 if GLib is None:
1152 pytest.skip("GLib not available")
1153 proxy = module_proxy_factory(module_name)
1154 return {
1155 cmd: test_single_param_command(proxy, cmd)
1156 for cmd in config["parameterized_commands"]
1157 }
1158
1159 timeout = MODULE_TIMEOUTS.get(module_name)
1160 result = run_with_timeout(test_parameterized_commands, timeout)
1161 error_msg = f"Failed to test {module_name} parameterized commands: {result['error']}"
1162 assert result["success"], error_msg
1163
1164 failed = [
1165 f"{cmd}: {res['error']}"
1166 for cmd, res in result["result"].items()
1167 if not res["success"] and not res.get("context_required")
1168 ]
1169 assert not failed, f"{module_name} parameterized command failures: {failed}"
1170
1171 @pytest.mark.parametrize(
1172 "module_name,config",
1173 [
1174 (name, config)
1175 for name, config in MODULE_CONFIG.items()
1176 if config.get("getters") or config.get("setters")
1177 ],
1178 ids=[
1179 name
1180 for name, config in MODULE_CONFIG.items()
1181 if config.get("getters") or config.get("setters")
1182 ],
1183 )
1184 @pytest.mark.dbus
1185 def test_module_getters_setters(
1186 self,
1187 module_proxy_factory,
1188 run_with_timeout,
1189 module_name,
1190 config,
1191 ):
1192 """Test that module getter/setter pairs work correctly."""
1193 # Skip optional modules that aren't available
1194 if module_name in OPTIONAL_MODULES:
1195 try:
1196 proxy = module_proxy_factory(module_name)
1197 # Check if module has the required dbus interface
1198 if not hasattr(proxy, "ExecuteRuntimeGetter"):
1199 pytest.skip(f"{module_name} is optional and not available")
1200 except (DBusError, AttributeError):
1201 pytest.skip(f"{module_name} is optional and not available")
1202
1203 all_props = sorted(set(config.get("getters", []) + config.get("setters", [])))
1204 print(f"\n Testing {module_name} properties ({len(all_props)} total):")
1205 for prop in all_props:
1206 has_getter = prop in config.get("getters", [])
1207 has_setter = prop in config.get("setters", [])
1208 status_parts = []
1209 if has_getter:
1210 status_parts.append("get")
1211 if has_setter:
1212 status_parts.append("set")
1213 status = f"({'/'.join(status_parts)})" if status_parts else ""
1214 print(f" • {prop} {status}")
1215
1216 def test_single_property(proxy, prop_name, is_setter=False):
1217 try:
1218 current_value = unpack_variant(proxy.ExecuteRuntimeGetter(prop_name))
1219 if is_setter:
1220 test_value = get_test_value(proxy, prop_name, current_value)
1221 proxy.ExecuteRuntimeSetter(prop_name, to_variant(test_value))
1222 new_value = unpack_variant(proxy.ExecuteRuntimeGetter(prop_name))
1223 proxy.ExecuteRuntimeSetter(prop_name, to_variant(current_value))
1224 return {
1225 "success": True,
1226 "original_value": current_value,
1227 "test_value": test_value,
1228 "actual_new_value": new_value,
1229 }
1230 return {"success": True, "value": current_value}
1231 except (DBusError, AttributeError, TypeError, ValueError) as error:
1232 return {"success": False, "error": str(error)}
1233
1234 def test_getters_setters():
1235 proxy = module_proxy_factory(module_name)
1236 results = {}
1237
1238 for prop in config.get("getters", []):
1239 results[f"get_{prop}"] = test_single_property(proxy, prop, is_setter=False)
1240
1241 for prop in config.get("setters", []):
1242 results[f"set_{prop}"] = test_single_property(proxy, prop, is_setter=True)
1243
1244 return results
1245
1246 timeout = MODULE_TIMEOUTS.get(module_name)
1247 result = run_with_timeout(test_getters_setters, timeout)
1248 assert result["success"], f"Failed to test {module_name} getters/setters: {result['error']}"
1249
1250 if result["result"]:
1251 getter_results = {k: v for k, v in result["result"].items() if k.startswith("get_")}
1252 setter_results = {k: v for k, v in result["result"].items() if k.startswith("set_")}
1253
1254 if getter_results:
1255 print(" Getter values:")
1256 for prop_key, res in getter_results.items():
1257 prop = prop_key[4:]
1258 if res["success"]:
1259 print(f" - {prop}: {res['value']}")
1260 else:
1261 print(f" - {prop}: ERROR - {res['error']}")
1262
1263 if setter_results:
1264 print(" Setter tests:")
1265 for prop_key, res in setter_results.items():
1266 prop = prop_key[4:]
1267 if res["success"]:
1268 original = res["original_value"]
1269 test_val = res["test_value"]
1270 actual = res["actual_new_value"]
1271 print(f" - {prop}: {original} → {test_val} (got: {actual})")
1272 else:
1273 print(f" - {prop}: ERROR - {res['error']}")
1274
1275 failed = [
1276 f"{prop}: {res['error']}"
1277 for prop, res in result["result"].items()
1278 if not res["success"]
1279 ]
1280 assert not failed, f"{module_name} getter/setter failures: {failed}"
1281
1282 @pytest.mark.dbus
1283 def test_parameterized_command_signatures(self, module_proxy_factory, run_with_timeout):
1284 """Test that parameterized commands have correct parameter signatures."""
1285
1286 def get_signatures():
1287 proxy = module_proxy_factory("SpeechManager")
1288 commands = proxy.ListParameterizedCommands()
1289 return {cmd[0]: [list(p[:2]) for p in cmd[2]] for cmd in commands}
1290
1291 result = run_with_timeout(get_signatures)
1292 error_msg = f"Could not get parameterized command signatures: {result['error']}"
1293 assert result["success"], error_msg
1294
1295 signatures = result["result"]
1296 if "GetVoicesForLanguage" in signatures:
1297 expected = [["language", "str"], ["variant", "str"], ["notify_user", "bool"]]
1298 actual = signatures["GetVoicesForLanguage"]
1299 error_msg = (
1300 f"GetVoicesForLanguage signature mismatch: expected {expected}, got {actual}"
1301 )
1302 assert actual == expected, error_msg
1303
1304 @pytest.mark.dbus
1305 def test_no_unexpected_modules(self, dbus_service_proxy):
1306 """Test that no unexpected modules exist - ensures test coverage for all modules."""
1307
1308 actual_modules = set(dbus_service_proxy.ListModules())
1309 expected_modules = set(MODULE_CONFIG.keys())
1310 unexpected_modules = actual_modules - expected_modules - OPTIONAL_MODULES
1311
1312 if unexpected_modules:
1313 module_list = sorted(unexpected_modules)
1314 error_msg = (
1315 f"Found {len(unexpected_modules)} unexpected modules that lack test coverage: "
1316 f"{module_list}\n"
1317 f"Please add configuration for these modules to MODULE_CONFIG in the test file."
1318 )
1319 raise AssertionError(error_msg)