Debian Codegraph @

tests/unit_tests/test_dbus_service.py

raw
1 # Unit tests for dbus_service.py methods.
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=wrong-import-position
22 # pylint: disable=import-outside-toplevel
23 # pylint: disable=too-many-public-methods
24 # pylint: disable=protected-access
25 # pylint: disable=too-many-arguments
26 # pylint: disable=too-many-positional-arguments
27 # pylint: disable=too-many-lines
28
29 """Unit tests for D-Bus functionality."""
30
31 from __future__ import annotations
32
33 import re
34 from typing import TYPE_CHECKING
35
36 import pytest
37
38 if TYPE_CHECKING:
39 from unittest.mock import MagicMock
40
41 from .orca_test_context import OrcaTestContext
42
43
44 class _MockDBusError(Exception):
45 def __init__(self, message="DBus error"):
46 super().__init__(message)
47 self.message = message
48
49
50 @pytest.mark.unit
51 class TestDBusService:
52 """Test D-Bus service functionality."""
53
54 def _setup_dependencies(self, test_context: OrcaTestContext) -> dict[str, MagicMock]:
55 """Set up mocks for dbus_service dependencies."""
56
57 external_modules = [
58 "gi",
59 "gi.repository",
60 "dasbus",
61 "dasbus.connection",
62 "dasbus.error",
63 "dasbus.loop",
64 "dasbus.server.interface",
65 "dasbus.server.publishable",
66 ]
67
68 internal_modules = [
69 "orca.debug",
70 "orca.input_event",
71 "orca.input_event_manager",
72 "orca.orca_platform",
73 "orca.script_manager",
74 "orca.braille_presenter",
75 "orca.presentation_manager",
76 ]
77
78 all_modules = external_modules + internal_modules
79 essential_modules = test_context._setup_essential_modules(all_modules)
80
81 class MockGLibVariant:
82 """Mock GLib.Variant for dasbus type handling."""
83
84 def __init__(self, type_string: str, value):
85 self._type_string = type_string
86 self._value = value
87
88 def get_type_string(self) -> str:
89 """Return the GLib type string."""
90 return self._type_string
91
92 def unpack(self):
93 """Unpack the variant value."""
94 return self._value
95
96 essential_modules["gi.repository"].GLib = test_context.Mock()
97 essential_modules["gi.repository"].GLib.Variant = MockGLibVariant
98
99 class MockPublishable:
100 """Mock Publishable base class for inheritance."""
101
102 def __init__(self, *args, **kwargs):
103 pass
104
105 essential_modules["dasbus.server.publishable"].Publishable = MockPublishable
106
107 essential_modules["dasbus.error"].DBusError = _MockDBusError
108
109 def mock_dbus_interface(_interface_name):
110 def decorator(cls):
111 return cls
112
113 return decorator
114
115 essential_modules["dasbus.server.interface"].dbus_interface = mock_dbus_interface
116
117 essential_modules["orca.debug"].LEVEL_INFO = 800
118 essential_modules["orca.debug"].println = test_context.Mock()
119
120 essential_modules["orca.orca_platform"].version = "test-version"
121
122 return essential_modules
123
124 def _get_mock_dbus_error(self) -> type[Exception]:
125 return _MockDBusError
126
127 def test_command_decorator(self, test_context: OrcaTestContext) -> None:
128 """Test command decorator."""
129
130 self._setup_dependencies(test_context)
131 from orca import dbus_service
132
133 @dbus_service.command
134 def test_function(script=None, event=None, notify_user=False) -> bool: # pylint: disable=unused-argument
135 """Test command function."""
136
137 return True
138
139 assert hasattr(test_function, "dbus_command_description")
140 assert test_function.dbus_command_description == "Test command function."
141
142 def test_command_decorator_without_docstring(self, test_context: OrcaTestContext) -> None:
143 """Test command decorator without docstring."""
144
145 self._setup_dependencies(test_context)
146 from orca import dbus_service
147
148 @dbus_service.command
149 def test_function_no_doc(script=None, event=None, notify_user=False) -> bool: # pylint: disable=unused-argument
150 return True
151
152 assert hasattr(test_function_no_doc, "dbus_command_description")
153 assert (
154 test_function_no_doc.dbus_command_description == "D-Bus command: test_function_no_doc"
155 )
156
157 def test_parameterized_command_decorator(self, test_context: OrcaTestContext) -> None:
158 """Test parameterized_command decorator."""
159
160 self._setup_dependencies(test_context)
161 from orca import dbus_service
162
163 @dbus_service.parameterized_command
164 def test_function(
165 script=None, # pylint: disable=unused-argument
166 event=None, # pylint: disable=unused-argument
167 language="", # pylint: disable=unused-argument
168 variant="", # pylint: disable=unused-argument
169 notify_user=False, # pylint: disable=unused-argument
170 ) -> list[tuple[str, str, str]]:
171 """Get voices for language."""
172
173 return [("voice1", language, variant)]
174
175 assert hasattr(test_function, "dbus_parameterized_command_description")
176 assert test_function.dbus_parameterized_command_description == "Get voices for language."
177
178 def test_getter_decorator(self, test_context: OrcaTestContext) -> None:
179 """Test getter decorator."""
180
181 self._setup_dependencies(test_context)
182 from orca import dbus_service
183
184 @dbus_service.getter
185 def get_rate() -> int:
186 """Returns the current speech rate."""
187
188 return 50
189
190 assert hasattr(get_rate, "dbus_getter_description")
191 assert get_rate.dbus_getter_description == "Returns the current speech rate."
192
193 def test_setter_decorator(self, test_context: OrcaTestContext) -> None:
194 """Test setter decorator."""
195
196 self._setup_dependencies(test_context)
197 from orca import dbus_service
198
199 @dbus_service.setter
200 def set_rate(_value) -> bool:
201 """Sets the current speech rate."""
202
203 return True
204
205 assert hasattr(set_rate, "dbus_setter_description")
206 assert set_rate.dbus_setter_description == "Sets the current speech rate."
207
208 def test_multiple_decorators_on_module(self, test_context: OrcaTestContext) -> None:
209 """Test multiple decorators on module."""
210
211 self._setup_dependencies(test_context)
212 from orca import dbus_service
213
214 class MockModule:
215 """Mock module for testing multiple decorators."""
216
217 @dbus_service.command
218 def toggle_speech(self, notify_user=False) -> bool: # pylint: disable=unused-argument
219 """Toggle speech on/off."""
220
221 return True
222
223 @dbus_service.parameterized_command
224 def get_voices_for_language(
225 self,
226 language="", # pylint: disable=unused-argument
227 variant="", # pylint: disable=unused-argument
228 notify_user=False, # pylint: disable=unused-argument
229 ) -> list:
230 """Get voices for language."""
231
232 return []
233
234 @dbus_service.getter
235 def get_rate(self) -> int:
236 """Get speech rate."""
237
238 return 50
239
240 @dbus_service.setter
241 def set_rate(self, _value) -> bool:
242 """Set speech rate."""
243
244 return True
245
246 mock_module = MockModule()
247 assert hasattr(mock_module.toggle_speech, "dbus_command_description")
248 assert hasattr(
249 mock_module.get_voices_for_language,
250 "dbus_parameterized_command_description",
251 )
252 assert hasattr(mock_module.get_rate, "dbus_getter_description")
253 assert hasattr(mock_module.set_rate, "dbus_setter_description")
254
255 def test_decorated_functions_remain_callable(self, test_context: OrcaTestContext) -> None:
256 """Test decorated functions remain callable."""
257
258 self._setup_dependencies(test_context)
259 from orca import dbus_service
260
261 @dbus_service.parameterized_command
262 def test_command(param1="default", notify_user=False) -> str:
263 """Test parameterized command."""
264
265 return f"param1={param1}, notify_user={notify_user}"
266
267 assert hasattr(test_command, "dbus_parameterized_command_description")
268 result = test_command(param1="test_value", notify_user=True)
269 assert "param1=test_value" in result
270 assert "notify_user=True" in result
271
272 def test_handler_info_creation(self, test_context: OrcaTestContext) -> None:
273 """Test _HandlerInfo creation."""
274
275 self._setup_dependencies(test_context)
276 from orca import dbus_service
277
278 def test_action() -> bool:
279 return True
280
281 info = dbus_service._HandlerInfo(
282 python_function_name="test_function",
283 description="Test function",
284 action=test_action,
285 handler_type=dbus_service.HandlerType.COMMAND,
286 )
287 assert info.python_function_name == "test_function"
288 assert info.description == "Test function"
289 assert info.action is test_action
290 assert info.handler_type == dbus_service.HandlerType.COMMAND
291
292 def test_handler_info_default_type(self, test_context: OrcaTestContext) -> None:
293 """Test _HandlerInfo default type."""
294
295 self._setup_dependencies(test_context)
296 from orca import dbus_service
297
298 def test_action() -> bool:
299 return True
300
301 info = dbus_service._HandlerInfo(
302 python_function_name="test_function",
303 description="Test function",
304 action=test_action,
305 )
306 assert info.handler_type == dbus_service.HandlerType.COMMAND
307
308 def test_extract_function_parameters_basic(self, test_context: OrcaTestContext) -> None:
309 """Test _extract_function_parameters basic types."""
310
311 self._setup_dependencies(test_context)
312 from orca import dbus_service
313
314 def test_func(self, param1: str, param2: int, param3: bool) -> None: # pylint: disable=unused-argument
315 pass
316
317 params = dbus_service._extract_function_parameters(test_func)
318 expected = [("param1", "str"), ("param2", "int"), ("param3", "bool")]
319 assert params == expected
320
321 def test_extract_function_parameters_skips_standard_params(
322 self,
323 test_context: OrcaTestContext,
324 ) -> None:
325 """Test _extract_function_parameters skips standard params."""
326
327 self._setup_dependencies(test_context)
328 from orca import dbus_service
329
330 def test_func(self, script=None, event=None, param1: str = "test") -> None: # pylint: disable=unused-argument
331 pass
332
333 params = dbus_service._extract_function_parameters(test_func)
334 expected = [("param1", "str")]
335 assert params == expected
336
337 def test_extract_function_parameters_no_annotations(
338 self,
339 test_context: OrcaTestContext,
340 ) -> None:
341 """Test _extract_function_parameters no annotations."""
342
343 self._setup_dependencies(test_context)
344 from orca import dbus_service
345
346 def test_func(self, param1, param2) -> None: # pylint: disable=unused-argument
347 pass
348
349 params = dbus_service._extract_function_parameters(test_func)
350 expected = [("param1", "Any"), ("param2", "Any")]
351 assert params == expected
352
353 def test_extract_function_parameters_mixed_annotations(
354 self,
355 test_context: OrcaTestContext,
356 ) -> None:
357 """Test _extract_function_parameters mixed annotations."""
358
359 self._setup_dependencies(test_context)
360 from orca import dbus_service
361
362 def test_func(self, param1: str, param2, param3: bool) -> None: # pylint: disable=unused-argument
363 pass
364
365 params = dbus_service._extract_function_parameters(test_func)
366 expected = [("param1", "str"), ("param2", "Any"), ("param3", "bool")]
367 assert params == expected
368
369 def test_extract_function_parameters_complex_types(self, test_context: OrcaTestContext) -> None:
370 """Test _extract_function_parameters complex types."""
371
372 self._setup_dependencies(test_context)
373 from orca import dbus_service
374
375 def test_func(self, param1: list[str], param2: dict[str, int]) -> None: # pylint: disable=unused-argument
376 pass
377
378 params = dbus_service._extract_function_parameters(test_func)
379 assert len(params) == 2
380 assert params[0][0] == "param1"
381 assert params[1][0] == "param2"
382 assert params[0][1] != "Any"
383 assert params[1][1] != "Any"
384
385 @pytest.mark.parametrize(
386 "case",
387 [
388 {
389 "id": "command",
390 "input_name": "toggle_speech",
391 "handler_type": "COMMAND",
392 "expected_result": "ToggleSpeech",
393 },
394 {
395 "id": "getter_with_prefix",
396 "input_name": "get_speech_rate",
397 "handler_type": "GETTER",
398 "expected_result": "SpeechRate",
399 },
400 {
401 "id": "setter_with_prefix",
402 "input_name": "set_speech_rate",
403 "handler_type": "SETTER",
404 "expected_result": "SpeechRate",
405 },
406 {
407 "id": "getter_without_prefix",
408 "input_name": "speech_rate",
409 "handler_type": "GETTER",
410 "expected_result": "SpeechRate",
411 },
412 {
413 "id": "setter_without_prefix",
414 "input_name": "speech_rate",
415 "handler_type": "SETTER",
416 "expected_result": "SpeechRate",
417 },
418 ],
419 ids=lambda case: case["id"],
420 )
421 def test_normalize_handler_name(self, test_context, case: dict) -> None:
422 """Test OrcaModuleDBusInterface._normalize_handler_name."""
423
424 self._setup_dependencies(test_context)
425 from orca import dbus_service
426
427 handler_type_obj = getattr(dbus_service.HandlerType, case["handler_type"])
428 result = dbus_service.OrcaModuleDBusInterface._normalize_handler_name(
429 case["input_name"],
430 handler_type_obj,
431 )
432 assert result == case["expected_result"]
433
434 @pytest.mark.parametrize(
435 "case",
436 [
437 {"id": "bool_true", "input_value": True, "expected_type": "b", "expected_output": True},
438 {
439 "id": "bool_false",
440 "input_value": False,
441 "expected_type": "b",
442 "expected_output": False,
443 },
444 {"id": "integer", "input_value": 42, "expected_type": "i", "expected_output": 42},
445 {"id": "float", "input_value": 3.14, "expected_type": "d", "expected_output": 3.14},
446 {
447 "id": "string",
448 "input_value": "test",
449 "expected_type": "s",
450 "expected_output": "test",
451 },
452 ],
453 ids=lambda case: case["id"],
454 )
455 def test_to_variant_basic_types(self, test_context, case: dict) -> None:
456 """Test OrcaModuleDBusInterface._to_variant with basic types."""
457
458 self._setup_dependencies(test_context)
459 from orca import dbus_service
460
461 variant = dbus_service.OrcaModuleDBusInterface._to_variant(case["input_value"])
462 assert variant.get_type_string() == case["expected_type"]
463 assert variant.unpack() == case["expected_output"]
464
465 @pytest.mark.parametrize(
466 "case",
467 [
468 {"id": "list_strings", "input_list": ["hello", "world"], "expected_type": "as"},
469 {"id": "list_ints", "input_list": [1, 2, 3], "expected_type": "ax"},
470 {"id": "list_bools", "input_list": [True, False, True], "expected_type": "ab"},
471 {"id": "list_ints_not_bools", "input_list": [2, 3, 4], "expected_type": "ax"},
472 {"id": "empty_list", "input_list": [], "expected_type": "as"},
473 ],
474 ids=lambda case: case["id"],
475 )
476 def test_to_variant_lists(self, test_context, case: dict) -> None:
477 """Test OrcaModuleDBusInterface._to_variant with various list types."""
478
479 self._setup_dependencies(test_context)
480 from orca import dbus_service
481
482 variant = dbus_service.OrcaModuleDBusInterface._to_variant(case["input_list"])
483 assert variant.get_type_string() == case["expected_type"]
484 assert variant.unpack() == case["input_list"]
485
486 def test_to_variant_list_tuples(self, test_context: OrcaTestContext) -> None:
487 """Test OrcaModuleDBusInterface._to_variant list tuples."""
488
489 self._setup_dependencies(test_context)
490 from orca import dbus_service
491
492 test_list = [("voice1", "en", "US"), ("voice2", "es", "ES")]
493 variant = dbus_service.OrcaModuleDBusInterface._to_variant(test_list)
494 assert variant.get_type_string() == "a(sss)"
495 expected = [("voice1", "en", "US"), ("voice2", "es", "ES")]
496 assert variant.unpack() == expected
497
498 def test_to_variant_dict(self, test_context: OrcaTestContext) -> None:
499 """Test OrcaModuleDBusInterface._to_variant dict."""
500
501 self._setup_dependencies(test_context)
502 from orca import dbus_service
503
504 test_dict = {"key1": "value1", "key2": "value2"}
505 variant = dbus_service.OrcaModuleDBusInterface._to_variant(test_dict)
506 assert variant.get_type_string() == "a{sv}"
507 unpacked = variant.unpack()
508 assert "key1" in unpacked
509 assert "key2" in unpacked
510
511 def test_to_variant_none(self, test_context: OrcaTestContext) -> None:
512 """Test OrcaModuleDBusInterface._to_variant None."""
513
514 self._setup_dependencies(test_context)
515 from orca import dbus_service
516
517 variant = dbus_service.OrcaModuleDBusInterface._to_variant(None)
518 assert variant.get_type_string() == "v"
519 inner = variant.unpack()
520 assert inner.unpack() == ""
521
522 def test_to_variant_unknown_type(self, test_context: OrcaTestContext) -> None:
523 """Test OrcaModuleDBusInterface._to_variant unknown type."""
524
525 self._setup_dependencies(test_context)
526 from orca import dbus_service
527
528 class CustomObject:
529 """Test class for unknown type conversion."""
530
531 def __str__(self):
532 return "custom_object"
533
534 obj = CustomObject()
535 variant = dbus_service.OrcaModuleDBusInterface._to_variant(obj)
536 assert variant.get_type_string() == "s"
537 assert variant.unpack() == "custom_object"
538
539 @pytest.mark.parametrize(
540 "case",
541 [
542 {
543 "id": "success",
544 "handlers_config": {"has_handler": True, "action": lambda: 42},
545 "getter_name": "Integer",
546 "expected_type": "i",
547 "expected_value": 42,
548 },
549 {
550 "id": "unknown",
551 "handlers_config": {"has_handler": False},
552 "getter_name": "UnknownGetter",
553 "expected_type": "v",
554 "expected_value": "",
555 },
556 {
557 "id": "string_type",
558 "handlers_config": {"has_handler": True, "action": lambda: "hello"},
559 "getter_name": "String",
560 "expected_type": "s",
561 "expected_value": "hello",
562 },
563 {
564 "id": "bool_type",
565 "handlers_config": {"has_handler": True, "action": lambda: True},
566 "getter_name": "Bool",
567 "expected_type": "b",
568 "expected_value": True,
569 },
570 {
571 "id": "list_type",
572 "handlers_config": {"has_handler": True, "action": lambda: ["a", "b"]},
573 "getter_name": "List",
574 "expected_type": "as",
575 "expected_value": ["a", "b"],
576 },
577 {
578 "id": "none_type",
579 "handlers_config": {"has_handler": True, "action": lambda: None},
580 "getter_name": "None",
581 "expected_type": "v",
582 "expected_value": "",
583 },
584 ],
585 ids=lambda case: case["id"],
586 )
587 def test_execute_runtime_getter_scenarios(
588 self,
589 test_context: OrcaTestContext,
590 case: dict,
591 ) -> None:
592 """Test OrcaModuleDBusInterface.ExecuteRuntimeGetter with various scenarios."""
593 self._setup_dependencies(test_context)
594 from orca import dbus_service
595
596 handlers_config = case["handlers_config"]
597 getter_name = case["getter_name"]
598 expected_type = case["expected_type"]
599 expected_value = case["expected_value"]
600
601 if handlers_config.get("has_handler", False):
602 if "action" in handlers_config:
603 action = handlers_config["action"]
604 elif "return_value" in handlers_config:
605 mock_action = test_context.Mock()
606 mock_action.return_value = handlers_config["return_value"]
607 action = mock_action
608 else:
609 action = test_context.Mock(return_value=True)
610
611 mock_info = dbus_service._HandlerInfo(
612 python_function_name=f"get_{getter_name.lower()}",
613 description=f"Get {getter_name.lower()}",
614 action=action,
615 handler_type=dbus_service.HandlerType.GETTER,
616 )
617 handlers = [mock_info]
618 else:
619 handlers = []
620
621 interface = dbus_service.OrcaModuleDBusInterface("TestModule", handlers)
622 result = interface.ExecuteRuntimeGetter(getter_name)
623 assert result.get_type_string() == expected_type
624
625 if expected_type == "v":
626 inner = result.unpack()
627 assert inner.get_type_string() == "s"
628 assert inner.unpack() == expected_value
629 else:
630 assert result.unpack() == expected_value
631
632 @pytest.mark.parametrize(
633 "case",
634 [
635 {
636 "id": "success",
637 "has_handler": True,
638 "action_returns": True,
639 "variant_type": "i",
640 "variant_value": 99,
641 "setter_name": "TestValue",
642 "expected_result": True,
643 "expects_setter_called": True,
644 },
645 {
646 "id": "unknown",
647 "has_handler": False,
648 "action_returns": None,
649 "variant_type": "i",
650 "variant_value": 99,
651 "setter_name": "UnknownSetter",
652 "expected_result": False,
653 "expects_setter_called": False,
654 },
655 {
656 "id": "failure",
657 "has_handler": True,
658 "action_returns": False,
659 "variant_type": "s",
660 "variant_value": "test",
661 "setter_name": "TestValue",
662 "expected_result": False,
663 "expects_setter_called": True,
664 },
665 ],
666 ids=lambda case: case["id"],
667 )
668 def test_execute_runtime_setter_scenarios(
669 self,
670 test_context: OrcaTestContext,
671 case: dict,
672 ) -> None:
673 """Test OrcaModuleDBusInterface.ExecuteRuntimeSetter with various scenarios."""
674 self._setup_dependencies(test_context)
675 from orca import dbus_service
676
677 test_state = {"setter_called": False, "setter_value": None}
678
679 if case["has_handler"]:
680
681 def mock_setter_action(value) -> bool:
682 test_state["setter_called"] = True
683 test_state["setter_value"] = value
684 return case["action_returns"] if case["action_returns"] is not None else False
685
686 mock_info = dbus_service._HandlerInfo(
687 python_function_name="set_test_value",
688 description="Set test value",
689 action=mock_setter_action,
690 handler_type=dbus_service.HandlerType.SETTER,
691 )
692 handlers = [mock_info]
693 else:
694 handlers = []
695
696 interface = dbus_service.OrcaModuleDBusInterface("TestModule", handlers)
697 mock_variant = dbus_service.GLib.Variant(case["variant_type"], case["variant_value"])
698 result = interface.ExecuteRuntimeSetter(case["setter_name"], mock_variant)
699 assert result is case["expected_result"]
700
701 if case["expects_setter_called"]:
702 assert test_state["setter_called"]
703 assert test_state["setter_value"] == case["variant_value"]
704 else:
705 assert not test_state["setter_called"]
706
707 @pytest.mark.parametrize(
708 "case",
709 [
710 {
711 "id": "success",
712 "command_name": "TestCommand",
713 "notify_user": True,
714 "mock_action_return": True,
715 "handler_infos": "create_handler",
716 "expected_result": True,
717 "should_verify_call": True,
718 },
719 {
720 "id": "unknown",
721 "command_name": "UnknownCommand",
722 "notify_user": False,
723 "mock_action_return": None,
724 "handler_infos": [],
725 "expected_result": False,
726 "should_verify_call": False,
727 },
728 {
729 "id": "failure",
730 "command_name": "FailingCommand",
731 "notify_user": False,
732 "mock_action_return": False,
733 "handler_infos": "create_handler",
734 "expected_result": False,
735 "should_verify_call": False,
736 },
737 ],
738 ids=lambda case: case["id"],
739 )
740 def test_execute_command_scenarios(
741 self,
742 test_context: OrcaTestContext,
743 case: dict,
744 ) -> None:
745 """Test OrcaModuleDBusInterface.ExecuteCommand with various scenarios."""
746 self._setup_dependencies(test_context)
747 from orca import dbus_service
748
749 command_name = case["command_name"]
750 notify_user = case["notify_user"]
751 mock_action_return = case["mock_action_return"]
752 handler_infos = case["handler_infos"]
753 expected_result = case["expected_result"]
754 should_verify_call = case["should_verify_call"]
755
756 test_state = {"command_called": False, "notify_value": None}
757
758 if handler_infos == "create_handler":
759
760 def mock_command_action(notify_user_param) -> bool:
761 test_state["command_called"] = True
762 test_state["notify_value"] = notify_user_param
763 return mock_action_return
764
765 mock_info = dbus_service._HandlerInfo(
766 python_function_name="_".join(
767 word.lower() for word in re.findall(r"[A-Z][a-z]*", command_name)
768 ),
769 description="test command",
770 action=mock_command_action,
771 handler_type=dbus_service.HandlerType.COMMAND,
772 )
773 handler_infos = [mock_info]
774
775 interface = dbus_service.OrcaModuleDBusInterface("TestModule", handler_infos)
776 result = interface.ExecuteCommand(command_name, notify_user)
777
778 assert result is expected_result
779 if should_verify_call:
780 assert test_state["command_called"]
781 assert test_state["notify_value"] is notify_user
782
783 @pytest.mark.parametrize(
784 "case",
785 [
786 {
787 "id": "success",
788 "has_handler": True,
789 "command_name": "ParamCommand",
790 "function_name": "param_command",
791 "notify_user": True,
792 "params": {"param1": ("s", "hello"), "param2": ("i", 42)},
793 "expected_type": "as",
794 "expected_value": ["result1", "result2"],
795 "action_config": {
796 "returns": ["result1", "result2"],
797 "track_state": True,
798 "parameters": [("param1", "str"), ("param2", "int")],
799 },
800 },
801 {
802 "id": "unknown",
803 "has_handler": False,
804 "command_name": "UnknownCommand",
805 "function_name": None,
806 "notify_user": False,
807 "params": {"param1": ("s", "test")},
808 "expected_type": "b",
809 "expected_value": False,
810 "action_config": None,
811 },
812 {
813 "id": "complex_result",
814 "has_handler": True,
815 "command_name": "GetVoices",
816 "function_name": "get_voices",
817 "notify_user": False,
818 "params": {"language": ("s", "en")},
819 "expected_type": "a(sss)",
820 "expected_value": [("voice1", "en", "US"), ("voice2", "es", "ES")],
821 "action_config": {
822 "returns": [("voice1", "en", "US"), ("voice2", "es", "ES")],
823 "track_state": False,
824 },
825 },
826 ],
827 ids=lambda case: case["id"],
828 )
829 def test_execute_parameterized_command_scenarios( # pylint: disable=too-many-locals
830 self,
831 test_context: OrcaTestContext,
832 case: dict,
833 ) -> None:
834 """Test OrcaModuleDBusInterface.ExecuteParameterizedCommand with various scenarios."""
835 self._setup_dependencies(test_context)
836 from orca import dbus_service
837
838 has_handler = case["has_handler"]
839 command_name = case["command_name"]
840 function_name = case["function_name"]
841 notify_user = case["notify_user"]
842 params = case["params"]
843 expected_type = case["expected_type"]
844 expected_value = case["expected_value"]
845 action_config = case["action_config"]
846
847 test_state: dict[str, str | int | float | bool | dict | None] = {
848 "param_command_called": False,
849 "received_params": None,
850 }
851
852 if has_handler:
853
854 def mock_param_command(**kwargs) -> bool:
855 if action_config and action_config.get("track_state", False):
856 test_state["param_command_called"] = True
857 test_state["received_params"] = kwargs
858 return True
859
860 parameters = action_config.get("parameters", []) if action_config else []
861 mock_info = dbus_service._HandlerInfo(
862 python_function_name=function_name or "default_function",
863 description="test command",
864 action=mock_param_command,
865 handler_type=dbus_service.HandlerType.PARAMETERIZED_COMMAND,
866 parameters=parameters,
867 )
868 handlers = [mock_info]
869 else:
870 handlers = []
871
872 interface = dbus_service.OrcaModuleDBusInterface("TestModule", handlers)
873
874 if has_handler and action_config:
875
876 def wrapped_action(**kwargs):
877 if action_config.get("track_state", False):
878 mock_param_command(**kwargs)
879 return action_config["returns"]
880
881 interface._parameterized_commands[command_name].action = wrapped_action
882
883 # Convert params to GLib.Variant format
884 variant_params = {}
885 for key, (variant_type, value) in params.items():
886 variant_params[key] = dbus_service.GLib.Variant(variant_type, value)
887
888 result = interface.ExecuteParameterizedCommand(command_name, variant_params, notify_user)
889 assert result.get_type_string() == expected_type
890 assert result.unpack() == expected_value
891
892 if action_config and action_config.get("track_state", False):
893 assert test_state["param_command_called"]
894 expected_params = {key: value for key, (_, value) in params.items()}
895 expected_params["notify_user"] = notify_user
896 assert test_state["received_params"] == expected_params
897
898 @pytest.mark.parametrize(
899 "case",
900 [
901 {
902 "id": "commands",
903 "list_type": "commands",
904 "handler_configs": [
905 {
906 "name": "command_one",
907 "desc": "First command",
908 "type": "COMMAND",
909 "action": lambda x: True,
910 },
911 {
912 "name": "command_two",
913 "desc": "Second command",
914 "type": "COMMAND",
915 "action": lambda x: True,
916 },
917 {
918 "name": "get_value",
919 "desc": "A getter",
920 "type": "GETTER",
921 "action": lambda: True,
922 },
923 ],
924 "method_name": "ListCommands",
925 "expected_count": 2,
926 "expected_items": [
927 ("CommandOne", "First command"),
928 ("CommandTwo", "Second command"),
929 ],
930 },
931 {
932 "id": "runtime_getters",
933 "list_type": "runtime_getters",
934 "handler_configs": [
935 {
936 "name": "get_rate",
937 "desc": "Get speech rate",
938 "type": "GETTER",
939 "action": lambda: True,
940 },
941 {
942 "name": "get_pitch",
943 "desc": "Get speech pitch",
944 "type": "GETTER",
945 "action": lambda: True,
946 },
947 ],
948 "method_name": "ListRuntimeGetters",
949 "expected_count": 2,
950 "expected_items": [("Rate", "Get speech rate"), ("Pitch", "Get speech pitch")],
951 },
952 {
953 "id": "runtime_setters",
954 "list_type": "runtime_setters",
955 "handler_configs": [
956 {
957 "name": "set_rate",
958 "desc": "Set speech rate",
959 "type": "SETTER",
960 "action": lambda x: True,
961 },
962 {
963 "name": "set_pitch",
964 "desc": "Set speech pitch",
965 "type": "SETTER",
966 "action": lambda x: True,
967 },
968 ],
969 "method_name": "ListRuntimeSetters",
970 "expected_count": 2,
971 "expected_items": [("Rate", "Set speech rate"), ("Pitch", "Set speech pitch")],
972 },
973 {
974 "id": "parameterized_commands",
975 "list_type": "parameterized_commands",
976 "handler_configs": [
977 {
978 "name": "get_voices_for_language",
979 "desc": "Get voices for language",
980 "type": "PARAMETERIZED_COMMAND",
981 "action": lambda **kwargs: True,
982 "parameters": [("language", "str"), ("variant", "str")],
983 },
984 ],
985 "method_name": "ListParameterizedCommands",
986 "expected_count": 1,
987 "expected_items": [
988 (
989 "GetVoicesForLanguage",
990 "Get voices for language",
991 [("language", "str"), ("variant", "str")],
992 ),
993 ],
994 },
995 ],
996 ids=lambda case: case["id"],
997 )
998 def test_list_methods_scenarios( # pylint: disable=too-many-locals
999 self,
1000 test_context: OrcaTestContext,
1001 case: dict,
1002 ) -> None:
1003 """Test OrcaModuleDBusInterface list methods with various handler types."""
1004 self._setup_dependencies(test_context)
1005 from orca import dbus_service
1006
1007 list_type = case["list_type"]
1008 handler_configs = case["handler_configs"]
1009 method_name = case["method_name"]
1010 expected_count = case["expected_count"]
1011 expected_items = case["expected_items"]
1012
1013 handlers = []
1014 for config in handler_configs:
1015 handler_type = getattr(dbus_service.HandlerType, config["type"])
1016 handler_info = dbus_service._HandlerInfo(
1017 python_function_name=config["name"],
1018 description=config["desc"],
1019 action=config["action"],
1020 handler_type=handler_type,
1021 parameters=config.get("parameters", []),
1022 )
1023 handlers.append(handler_info)
1024
1025 interface = dbus_service.OrcaModuleDBusInterface("TestModule", handlers)
1026 list_method = getattr(interface, method_name)
1027 result = list_method()
1028
1029 assert len(result) == expected_count
1030
1031 if list_type == "parameterized_commands":
1032 # Parameterized commands return tuples with 3 elements
1033 for expected_item in expected_items:
1034 assert result[0][0] == expected_item[0] # Name
1035 assert result[0][1] == expected_item[1] # Description
1036 assert result[0][2] == expected_item[2] # Parameters
1037 else:
1038 # Other types return simple tuples
1039 for expected_item in expected_items:
1040 assert expected_item in result
1041
1042 def test_constructor_empty_handlers(self, test_context: OrcaTestContext) -> None:
1043 """Test OrcaModuleDBusInterface constructor empty handlers."""
1044
1045 self._setup_dependencies(test_context)
1046 from orca import dbus_service
1047
1048 interface = dbus_service.OrcaModuleDBusInterface("TestModule", [])
1049 assert interface._module_name == "TestModule"
1050 assert len(interface._commands) == 0
1051 assert len(interface._parameterized_commands) == 0
1052 assert len(interface._getters) == 0
1053 assert len(interface._setters) == 0
1054
1055 def test_constructor_mixed_handlers(self, test_context: OrcaTestContext) -> None:
1056 """Test OrcaModuleDBusInterface constructor mixed handlers."""
1057
1058 self._setup_dependencies(test_context)
1059 from orca import dbus_service
1060
1061 handlers = [
1062 dbus_service._HandlerInfo(
1063 python_function_name="toggle_something",
1064 description="Toggle something",
1065 action=lambda x: True,
1066 handler_type=dbus_service.HandlerType.COMMAND,
1067 ),
1068 dbus_service._HandlerInfo(
1069 python_function_name="get_value",
1070 description="Get value",
1071 action=lambda: True,
1072 handler_type=dbus_service.HandlerType.GETTER,
1073 ),
1074 dbus_service._HandlerInfo(
1075 python_function_name="set_value",
1076 description="Set value",
1077 action=lambda x: True,
1078 handler_type=dbus_service.HandlerType.SETTER,
1079 ),
1080 dbus_service._HandlerInfo(
1081 python_function_name="do_something_complex",
1082 description="Do something complex",
1083 action=lambda **kwargs: True,
1084 handler_type=dbus_service.HandlerType.PARAMETERIZED_COMMAND,
1085 parameters=[("param", "str")],
1086 ),
1087 ]
1088 interface = dbus_service.OrcaModuleDBusInterface("TestModule", handlers)
1089 assert interface._module_name == "TestModule"
1090 assert "ToggleSomething" in interface._commands
1091 assert "Value" in interface._getters
1092 assert "Value" in interface._setters
1093 assert "DoSomethingComplex" in interface._parameterized_commands
1094
1095 def test_constructor_handler_without_type(self, test_context: OrcaTestContext) -> None:
1096 """Test OrcaModuleDBusInterface constructor handler without type."""
1097
1098 self._setup_dependencies(test_context)
1099 from orca import dbus_service
1100
1101 class MockHandlerInfo:
1102 """Mock handler info for testing."""
1103
1104 def __init__(self):
1105 self.python_function_name = "test_command"
1106 self.description = "Test command"
1107 self.action = lambda x: True
1108
1109 MockHandlerInfo()
1110 # Convert to proper _HandlerInfo for type compatibility
1111 real_handler = dbus_service._HandlerInfo(
1112 python_function_name="test_command",
1113 description="Test command",
1114 action=lambda x: True,
1115 handler_type=dbus_service.HandlerType.COMMAND,
1116 )
1117 interface = dbus_service.OrcaModuleDBusInterface("TestModule", [real_handler])
1118 assert "TestCommand" in interface._commands
1119
1120 def test_constructor_duplicate_names(self, test_context: OrcaTestContext) -> None:
1121 """Test OrcaModuleDBusInterface constructor duplicate names."""
1122
1123 self._setup_dependencies(test_context)
1124 from orca import dbus_service
1125
1126 handlers = [
1127 dbus_service._HandlerInfo(
1128 python_function_name="test_command",
1129 description="First command",
1130 action=lambda x: True,
1131 handler_type=dbus_service.HandlerType.COMMAND,
1132 ),
1133 dbus_service._HandlerInfo(
1134 python_function_name="test_command",
1135 description="Second command",
1136 action=lambda x: True,
1137 handler_type=dbus_service.HandlerType.COMMAND,
1138 ),
1139 ]
1140 interface = dbus_service.OrcaModuleDBusInterface("TestModule", handlers)
1141 assert len(interface._commands) == 1
1142 assert interface._commands["TestCommand"].action(False) is True
1143
1144 def test_for_publication(self, test_context: OrcaTestContext) -> None:
1145 """Test OrcaModuleDBusInterface.for_publication."""
1146
1147 self._setup_dependencies(test_context)
1148 from orca import dbus_service
1149
1150 interface = dbus_service.OrcaModuleDBusInterface("TestModule", [])
1151 interface.__dbus_xml__ = "<xml>test</xml>"
1152 result = interface.for_publication()
1153 assert result == "<xml>test</xml>"
1154
1155 def test_orca_dbus_service_constructor(self, test_context: OrcaTestContext) -> None:
1156 """Test OrcaDBusServiceInterface constructor."""
1157
1158 self._setup_dependencies(test_context)
1159 from orca import dbus_service
1160
1161 service = dbus_service.OrcaDBusServiceInterface()
1162 assert service._registered_modules == set()
1163
1164 def test_orca_dbus_service_for_publication(self, test_context: OrcaTestContext) -> None:
1165 """Test OrcaDBusServiceInterface.for_publication."""
1166
1167 self._setup_dependencies(test_context)
1168 from orca import dbus_service
1169
1170 service = dbus_service.OrcaDBusServiceInterface()
1171 service.__dbus_xml__ = "<xml>service</xml>"
1172 result = service.for_publication()
1173 assert result == "<xml>service</xml>"
1174
1175 def test_add_module_interface_new(self, test_context: OrcaTestContext) -> None:
1176 """Test OrcaDBusServiceInterface.add_module_interface new module."""
1177
1178 self._setup_dependencies(test_context)
1179 from orca import dbus_service
1180
1181 mock_bus = test_context.Mock()
1182 service = dbus_service.OrcaDBusServiceInterface()
1183 handlers: list[dbus_service._HandlerInfo] = []
1184 mock_module_iface = test_context.Mock()
1185 test_context.patch_object(
1186 dbus_service,
1187 "OrcaModuleDBusInterface",
1188 side_effect=lambda module_name, handlers_info: mock_module_iface,
1189 )
1190 service.add_module_interface("TestModule", handlers, mock_bus, "/test/path")
1191 assert "TestModule" in service._registered_modules
1192 mock_bus.publish_object.assert_called_once_with("/test/path/TestModule", mock_module_iface)
1193
1194 def test_add_module_interface_replace_existing(self, test_context: OrcaTestContext) -> None:
1195 """Test OrcaDBusServiceInterface.add_module_interface replace existing."""
1196
1197 self._setup_dependencies(test_context)
1198 from orca import dbus_service
1199
1200 mock_bus = test_context.Mock()
1201 service = dbus_service.OrcaDBusServiceInterface()
1202 service._registered_modules.add("TestModule")
1203 handlers: list[dbus_service._HandlerInfo] = []
1204 mock_module_iface = test_context.Mock()
1205 test_context.patch_object(
1206 dbus_service,
1207 "OrcaModuleDBusInterface",
1208 side_effect=lambda module_name, handlers_info: mock_module_iface,
1209 )
1210 service.add_module_interface("TestModule", handlers, mock_bus, "/test/path")
1211 assert "TestModule" in service._registered_modules
1212 mock_bus.unpublish_object.assert_called_once_with("/test/path/TestModule")
1213 mock_bus.publish_object.assert_called_once_with("/test/path/TestModule", mock_module_iface)
1214
1215 def test_add_module_interface_unpublish_error(self, test_context: OrcaTestContext) -> None:
1216 """Test OrcaDBusServiceInterface.add_module_interface unpublish error."""
1217
1218 self._setup_dependencies(test_context)
1219 from orca import dbus_service
1220
1221 mock_dbus_error = self._get_mock_dbus_error()
1222 mock_bus = test_context.Mock()
1223 mock_bus.unpublish_object.side_effect = mock_dbus_error("Unpublish failed")
1224 service = dbus_service.OrcaDBusServiceInterface()
1225 service._registered_modules.add("TestModule")
1226 handlers: list[dbus_service._HandlerInfo] = []
1227 mock_module_iface = test_context.Mock()
1228 test_context.patch_object(
1229 dbus_service,
1230 "OrcaModuleDBusInterface",
1231 side_effect=lambda module_name, handlers_info: mock_module_iface,
1232 )
1233
1234 # The unpublish_object call should fail but be caught gracefully by the production code
1235 # The module should still be successfully registered despite the unpublish error
1236 service.add_module_interface("TestModule", handlers, mock_bus, "/test/path")
1237 assert "TestModule" in service._registered_modules
1238 mock_bus.unpublish_object.assert_called_once_with("/test/path/TestModule")
1239 mock_bus.publish_object.assert_called_once_with("/test/path/TestModule", mock_module_iface)
1240
1241 def test_add_module_interface_publish_error(self, test_context: OrcaTestContext) -> None:
1242 """Test OrcaDBusServiceInterface.add_module_interface publish error."""
1243
1244 self._setup_dependencies(test_context)
1245 from orca import dbus_service
1246
1247 mock_dbus_error = self._get_mock_dbus_error()
1248 mock_bus = test_context.Mock()
1249 mock_bus.publish_object.side_effect = mock_dbus_error("Publish failed")
1250 service = dbus_service.OrcaDBusServiceInterface()
1251 handlers: list[dbus_service._HandlerInfo] = []
1252 mock_module_iface = test_context.Mock()
1253 test_context.patch_object(
1254 dbus_service,
1255 "OrcaModuleDBusInterface",
1256 side_effect=lambda module_name, handlers_info: mock_module_iface,
1257 )
1258
1259 service.add_module_interface("TestModule", handlers, mock_bus, "/test/path")
1260 assert "TestModule" not in service._registered_modules
1261
1262 def test_remove_module_interface_success(self, test_context: OrcaTestContext) -> None:
1263 """Test OrcaDBusServiceInterface.remove_module_interface success."""
1264
1265 self._setup_dependencies(test_context)
1266 from orca import dbus_service
1267
1268 mock_bus = test_context.Mock()
1269 service = dbus_service.OrcaDBusServiceInterface()
1270 service._registered_modules.add("TestModule")
1271 result = service.remove_module_interface("TestModule", mock_bus, "/test/path")
1272 assert result is True
1273 assert "TestModule" not in service._registered_modules
1274 mock_bus.unpublish_object.assert_called_once_with("/test/path/TestModule")
1275
1276 def test_remove_module_interface_not_registered(self, test_context: OrcaTestContext) -> None:
1277 """Test OrcaDBusServiceInterface.remove_module_interface not registered."""
1278
1279 self._setup_dependencies(test_context)
1280 from orca import dbus_service
1281
1282 mock_bus = test_context.Mock()
1283 service = dbus_service.OrcaDBusServiceInterface()
1284 result = service.remove_module_interface("TestModule", mock_bus, "/test/path")
1285 assert result is False
1286 mock_bus.unpublish_object.assert_not_called()
1287
1288 def test_remove_module_interface_unpublish_error(self, test_context: OrcaTestContext) -> None:
1289 """Test OrcaDBusServiceInterface.remove_module_interface unpublish error."""
1290
1291 self._setup_dependencies(test_context)
1292 from orca import dbus_service
1293
1294 mock_dbus_error = self._get_mock_dbus_error()
1295 mock_bus = test_context.Mock()
1296 mock_bus.unpublish_object.side_effect = mock_dbus_error("Unpublish failed")
1297 service = dbus_service.OrcaDBusServiceInterface()
1298 service._registered_modules.add("TestModule")
1299
1300 result = service.remove_module_interface("TestModule", mock_bus, "/test/path")
1301 assert result is False
1302 assert "TestModule" in service._registered_modules
1303
1304 def test_list_modules(self, test_context: OrcaTestContext) -> None:
1305 """Test OrcaDBusServiceInterface.ListModules."""
1306
1307 self._setup_dependencies(test_context)
1308 from orca import dbus_service
1309
1310 service = dbus_service.OrcaDBusServiceInterface()
1311 service._registered_modules.update(["Module1", "Module2", "Module3"])
1312 modules = service.ListModules()
1313 assert set(modules) == {"Module1", "Module2", "Module3"}
1314
1315 def test_orca_dbus_service_list_commands(self, test_context: OrcaTestContext) -> None:
1316 """Test OrcaDBusServiceInterface.ListCommands."""
1317
1318 self._setup_dependencies(test_context)
1319 from orca import dbus_service
1320
1321 service = dbus_service.OrcaDBusServiceInterface()
1322 commands = service.ListCommands()
1323 command_names = [cmd[0] for cmd in commands]
1324 assert "ShowPreferences" in command_names
1325 assert "PresentMessage" in command_names
1326 assert "GetVersion" in command_names
1327
1328 def test_show_preferences_success(self, test_context: OrcaTestContext) -> None:
1329 """Test OrcaDBusServiceInterface.ShowPreferences success."""
1330
1331 self._setup_dependencies(test_context)
1332 from orca import dbus_service
1333
1334 mock_script = test_context.Mock()
1335 mock_script.show_preferences_gui.return_value = None
1336 mock_manager = test_context.Mock()
1337 mock_manager.get_active_script.return_value = mock_script
1338 test_context.patch("orca.script_manager.get_manager", return_value=mock_manager)
1339 service = dbus_service.OrcaDBusServiceInterface()
1340 result = service.ShowPreferences()
1341 assert result is True
1342 mock_script.show_preferences_gui.assert_called_once()
1343
1344 def test_show_preferences_no_active_script(self, test_context: OrcaTestContext) -> None:
1345 """Test OrcaDBusServiceInterface.ShowPreferences no active script."""
1346
1347 self._setup_dependencies(test_context)
1348 from orca import dbus_service
1349
1350 mock_script = test_context.Mock()
1351 mock_script.show_preferences_gui.return_value = None
1352 mock_manager = test_context.Mock()
1353 mock_manager.get_active_script.return_value = None
1354 mock_manager.get_default_script.return_value = mock_script
1355 test_context.patch("orca.script_manager.get_manager", return_value=mock_manager)
1356 service = dbus_service.OrcaDBusServiceInterface()
1357 result = service.ShowPreferences()
1358 assert result is True
1359 mock_script.show_preferences_gui.assert_called_once()
1360
1361 def test_show_preferences_no_script(self, test_context: OrcaTestContext) -> None:
1362 """Test OrcaDBusServiceInterface.ShowPreferences no script."""
1363
1364 self._setup_dependencies(test_context)
1365 from orca import dbus_service
1366
1367 mock_manager = test_context.Mock()
1368 mock_manager.get_active_script.return_value = None
1369 mock_manager.get_default_script.return_value = None
1370 test_context.patch("orca.script_manager.get_manager", return_value=mock_manager)
1371 service = dbus_service.OrcaDBusServiceInterface()
1372 result = service.ShowPreferences()
1373 assert result is False
1374
1375 def test_present_message_success(self, test_context: OrcaTestContext) -> None:
1376 """Test OrcaDBusServiceInterface.PresentMessage success."""
1377
1378 essential_modules = self._setup_dependencies(test_context)
1379 from orca import dbus_service
1380
1381 mock_script = test_context.Mock()
1382 mock_manager = test_context.Mock()
1383 mock_manager.get_active_script.return_value = mock_script
1384 test_context.patch("orca.script_manager.get_manager", return_value=mock_manager)
1385 service = dbus_service.OrcaDBusServiceInterface()
1386 pres_manager = essential_modules["orca.presentation_manager"].get_manager()
1387 pres_manager.present_message.reset_mock()
1388 result = service.PresentMessage("Test message")
1389 assert result is True
1390 pres_manager.present_message.assert_called_once_with("Test message")
1391
1392 def test_present_message_no_script(self, test_context: OrcaTestContext) -> None:
1393 """Test OrcaDBusServiceInterface.PresentMessage works without active script."""
1394
1395 essential_modules = self._setup_dependencies(test_context)
1396 from orca import dbus_service
1397
1398 mock_manager = test_context.Mock()
1399 mock_manager.get_active_script.return_value = None
1400 mock_manager.get_default_script.return_value = None
1401 test_context.patch("orca.script_manager.get_manager", return_value=mock_manager)
1402 pres_manager = essential_modules["orca.presentation_manager"].get_manager()
1403 pres_manager.present_message.reset_mock()
1404 service = dbus_service.OrcaDBusServiceInterface()
1405 result = service.PresentMessage("Test message")
1406 # presentation_manager works without a script now
1407 assert result is True
1408 pres_manager.present_message.assert_called_once_with("Test message")
1409
1410 @pytest.mark.parametrize(
1411 "case",
1412 [
1413 {
1414 "id": "with_revision",
1415 "version": "2.0.0",
1416 "revision": "abcd1234",
1417 "expected_result": "2.0.0 (rev abcd1234)",
1418 },
1419 {"id": "no_revision", "version": "2.0.0", "revision": "", "expected_result": "2.0.0"},
1420 ],
1421 ids=lambda case: case["id"],
1422 )
1423 def test_get_version_scenarios(self, test_context: OrcaTestContext, case: dict) -> None:
1424 """Test OrcaDBusServiceInterface.GetVersion with and without revision."""
1425 self._setup_dependencies(test_context)
1426 from orca import dbus_service
1427
1428 version = case["version"]
1429 revision = case["revision"]
1430 expected_result = case["expected_result"]
1431
1432 test_context.patch_object(dbus_service.orca_platform, "version", new=version)
1433 test_context.patch_object(dbus_service.orca_platform, "revision", new=revision)
1434 service = dbus_service.OrcaDBusServiceInterface()
1435 result = service.GetVersion()
1436 assert result == expected_result
1437
1438 def test_shutdown_service(self, test_context: OrcaTestContext) -> None:
1439 """Test OrcaDBusServiceInterface.shutdown_service."""
1440
1441 self._setup_dependencies(test_context)
1442 from orca import dbus_service
1443
1444 mock_bus = test_context.Mock()
1445 service = dbus_service.OrcaDBusServiceInterface()
1446 service._registered_modules.update(["Module1", "Module2"])
1447 service.shutdown_service(mock_bus, "/test/path")
1448 assert len(service._registered_modules) == 0
1449 assert mock_bus.unpublish_object.call_count == 2
1450 mock_bus.unpublish_object.assert_any_call("/test/path/Module1")
1451 mock_bus.unpublish_object.assert_any_call("/test/path/Module2")
1452
1453 def test_shutdown_service_unpublish_error(self, test_context: OrcaTestContext) -> None:
1454 """Test OrcaDBusServiceInterface.shutdown_service unpublish error."""
1455
1456 self._setup_dependencies(test_context)
1457 from orca import dbus_service
1458
1459 mock_dbus_error = self._get_mock_dbus_error()
1460 mock_bus = test_context.Mock()
1461 mock_bus.unpublish_object.side_effect = mock_dbus_error("Unpublish failed")
1462 service = dbus_service.OrcaDBusServiceInterface()
1463 service._registered_modules.update(["Module1"])
1464
1465 service.shutdown_service(mock_bus, "/test/path")
1466 assert len(service._registered_modules) == 0
1467
1468 def test_orca_remote_controller_constructor(self, test_context: OrcaTestContext) -> None:
1469 """Test OrcaRemoteController constructor."""
1470
1471 self._setup_dependencies(test_context)
1472 from orca import dbus_service
1473
1474 controller = dbus_service.OrcaRemoteController()
1475 assert controller._dbus_service_interface is None
1476 assert controller._is_running is False
1477 assert controller._bus is None
1478 assert controller._event_loop is None
1479 assert not controller._pending_registrations
1480 assert controller._total_commands == 0
1481 assert controller._total_getters == 0
1482 assert controller._total_setters == 0
1483 assert controller._total_modules == 0
1484
1485 def test_is_running_false(self, test_context: OrcaTestContext) -> None:
1486 """Test OrcaRemoteController.is_running false."""
1487
1488 self._setup_dependencies(test_context)
1489 from orca import dbus_service
1490
1491 controller = dbus_service.OrcaRemoteController()
1492 assert controller.is_running() is False
1493
1494 def test_is_running_true(self, test_context: OrcaTestContext) -> None:
1495 """Test OrcaRemoteController.is_running true."""
1496
1497 self._setup_dependencies(test_context)
1498 from orca import dbus_service
1499
1500 controller = dbus_service.OrcaRemoteController()
1501 controller._is_running = True
1502 assert controller.is_running() is True
1503
1504 def test_start_already_running(self, test_context: OrcaTestContext) -> None:
1505 """Test OrcaRemoteController.start already running."""
1506
1507 self._setup_dependencies(test_context)
1508 from orca import dbus_service
1509
1510 controller = dbus_service.OrcaRemoteController()
1511 controller._is_running = True
1512 result = controller.start()
1513 assert result is True
1514
1515 def test_start_bus_error(self, test_context: OrcaTestContext) -> None:
1516 """Test OrcaRemoteController.start bus error."""
1517
1518 self._setup_dependencies(test_context)
1519 from orca import dbus_service
1520
1521 mock_dbus_error = self._get_mock_dbus_error()
1522
1523 def mock_session_bus() -> None:
1524 raise mock_dbus_error("Bus connection failed")
1525
1526 test_context.patch_object(dbus_service, "SessionMessageBus", new=mock_session_bus)
1527
1528 controller = dbus_service.OrcaRemoteController()
1529 result = controller.start()
1530 assert result is False
1531 assert controller._bus is None
1532 assert controller._is_running is False
1533
1534 def test_start_publish_error(self, test_context: OrcaTestContext) -> None:
1535 """Test OrcaRemoteController.start publish error."""
1536
1537 self._setup_dependencies(test_context)
1538 from orca import dbus_service
1539
1540 mock_dbus_error = self._get_mock_dbus_error()
1541 mock_bus = test_context.Mock()
1542 mock_bus.connection.get_unique_name.return_value = "test_name"
1543 mock_bus.publish_object.side_effect = mock_dbus_error("Publish failed")
1544 test_context.patch_object(dbus_service, "SessionMessageBus", return_value=mock_bus)
1545
1546 controller = dbus_service.OrcaRemoteController()
1547 result = controller.start()
1548 assert result is False
1549 assert controller._bus is None
1550 assert controller._dbus_service_interface is None
1551 assert controller._is_running is False
1552
1553 def test_start_publish_error_with_cleanup(self, test_context: OrcaTestContext) -> None:
1554 """Test OrcaRemoteController.start publish error with cleanup."""
1555
1556 self._setup_dependencies(test_context)
1557 from orca import dbus_service
1558
1559 mock_dbus_error = self._get_mock_dbus_error()
1560 mock_bus = test_context.Mock()
1561 mock_bus.connection.get_unique_name.return_value = "test_name"
1562 mock_bus.register_service.side_effect = mock_dbus_error("Register failed")
1563 test_context.patch_object(dbus_service, "SessionMessageBus", return_value=mock_bus)
1564
1565 controller = dbus_service.OrcaRemoteController()
1566 result = controller.start()
1567 assert result is False
1568 mock_bus.unpublish_object.assert_called_once()
1569
1570 def test_start_success(self, test_context: OrcaTestContext) -> None:
1571 """Test OrcaRemoteController.start success."""
1572
1573 self._setup_dependencies(test_context)
1574 from orca import dbus_service
1575
1576 mock_bus = test_context.Mock()
1577 mock_bus.connection.get_unique_name.return_value = "test_name"
1578 test_context.patch_object(dbus_service, "SessionMessageBus", return_value=mock_bus)
1579 controller = dbus_service.OrcaRemoteController()
1580 mock_process = test_context.Mock()
1581 mock_print = test_context.Mock()
1582 test_context.patch_object(controller, "_process_pending_registrations", new=mock_process)
1583 test_context.patch_object(controller, "_print_registration_summary", new=mock_print)
1584 result = controller.start()
1585 assert result is True
1586 assert controller._is_running is True
1587 assert controller._bus is mock_bus
1588 assert controller._dbus_service_interface is not None
1589 mock_bus.publish_object.assert_called_once()
1590 mock_bus.register_service.assert_called_once()
1591 mock_process.assert_called_once()
1592 mock_print.assert_called_once()
1593
1594 def test_shutdown_not_running(self, test_context: OrcaTestContext) -> None:
1595 """Test OrcaRemoteController.shutdown not running."""
1596
1597 self._setup_dependencies(test_context)
1598 from orca import dbus_service
1599
1600 controller = dbus_service.OrcaRemoteController()
1601 controller.shutdown()
1602
1603 def test_shutdown_success(self, test_context: OrcaTestContext) -> None:
1604 """Test OrcaRemoteController.shutdown success."""
1605
1606 self._setup_dependencies(test_context)
1607 from orca import dbus_service
1608
1609 mock_bus = test_context.Mock()
1610 mock_service = test_context.Mock()
1611 controller = dbus_service.OrcaRemoteController()
1612 controller._is_running = True
1613 controller._bus = mock_bus
1614 controller._dbus_service_interface = mock_service
1615 controller._total_commands = 5
1616 controller._total_getters = 3
1617 controller._total_setters = 2
1618 controller._total_modules = 1
1619 controller._pending_registrations = {"test": "module"}
1620 controller.shutdown()
1621 assert controller._is_running is False
1622 assert controller._bus is None
1623 assert controller._dbus_service_interface is None
1624 assert controller._total_commands == 0
1625 assert controller._total_getters == 0
1626 assert controller._total_setters == 0
1627 assert controller._total_modules == 0
1628 assert not controller._pending_registrations
1629 mock_service.shutdown_service.assert_called_once()
1630 mock_bus.unpublish_object.assert_called_once()
1631 mock_bus.unregister_service.assert_called_once()
1632 mock_bus.disconnect.assert_called_once()
1633
1634 def test_shutdown_unpublish_error(self, test_context: OrcaTestContext) -> None:
1635 """Test OrcaRemoteController.shutdown unpublish error."""
1636
1637 self._setup_dependencies(test_context)
1638 from orca import dbus_service
1639
1640 mock_dbus_error = self._get_mock_dbus_error()
1641 mock_bus = test_context.Mock()
1642 mock_bus.unpublish_object.side_effect = mock_dbus_error("Unpublish failed")
1643 mock_service = test_context.Mock()
1644 controller = dbus_service.OrcaRemoteController()
1645 controller._is_running = True
1646 controller._bus = mock_bus
1647 controller._dbus_service_interface = mock_service
1648
1649 controller.shutdown()
1650 assert controller._is_running is False
1651 mock_bus.unregister_service.assert_called_once()
1652 mock_bus.disconnect.assert_called_once()
1653
1654 def test_shutdown_unregister_error(self, test_context: OrcaTestContext) -> None:
1655 """Test OrcaRemoteController.shutdown unregister error."""
1656
1657 self._setup_dependencies(test_context)
1658 from orca import dbus_service
1659
1660 mock_dbus_error = self._get_mock_dbus_error()
1661 mock_bus = test_context.Mock()
1662 mock_bus.unregister_service.side_effect = mock_dbus_error("Unregister failed")
1663 mock_service = test_context.Mock()
1664 controller = dbus_service.OrcaRemoteController()
1665 controller._is_running = True
1666 controller._bus = mock_bus
1667 controller._dbus_service_interface = mock_service
1668
1669 controller.shutdown()
1670 assert controller._is_running is False
1671 mock_bus.disconnect.assert_called_once()
1672
1673 def test_register_decorated_module_not_running(self, test_context: OrcaTestContext) -> None:
1674 """Test OrcaRemoteController.register_decorated_module not running."""
1675
1676 self._setup_dependencies(test_context)
1677 from orca import dbus_service
1678
1679 controller = dbus_service.OrcaRemoteController()
1680 mock_module = test_context.Mock()
1681 controller.register_decorated_module("TestModule", mock_module)
1682 assert "TestModule" in controller._pending_registrations
1683 assert controller._pending_registrations["TestModule"] is mock_module
1684
1685 def test_register_decorated_module_running(self, test_context: OrcaTestContext) -> None:
1686 """Test OrcaRemoteController.register_decorated_module running."""
1687
1688 self._setup_dependencies(test_context)
1689 from orca import dbus_service
1690
1691 controller = dbus_service.OrcaRemoteController()
1692 controller._is_running = True
1693 controller._dbus_service_interface = test_context.Mock()
1694 controller._bus = test_context.Mock()
1695 mock_register = test_context.Mock()
1696 test_context.patch_object(
1697 controller,
1698 "_register_decorated_commands_internal",
1699 new=mock_register,
1700 )
1701 mock_module = test_context.Mock()
1702 controller.register_decorated_module("TestModule", mock_module)
1703 mock_register.assert_called_once_with("TestModule", mock_module)
1704
1705 @pytest.mark.parametrize(
1706 "case",
1707 [
1708 {
1709 "id": "pending",
1710 "is_running": False,
1711 "has_pending": True,
1712 "mock_service_returns": None,
1713 "expected_result": True,
1714 "expects_service_call": False,
1715 },
1716 {
1717 "id": "not_running",
1718 "is_running": False,
1719 "has_pending": False,
1720 "mock_service_returns": None,
1721 "expected_result": False,
1722 "expects_service_call": False,
1723 },
1724 {
1725 "id": "running",
1726 "is_running": True,
1727 "has_pending": False,
1728 "mock_service_returns": True,
1729 "expected_result": True,
1730 "expects_service_call": True,
1731 },
1732 ],
1733 ids=lambda case: case["id"],
1734 )
1735 def test_deregister_module_commands_scenarios(
1736 self,
1737 test_context: OrcaTestContext,
1738 case: dict,
1739 ) -> None:
1740 """Test OrcaRemoteController.deregister_module_commands with various scenarios."""
1741 self._setup_dependencies(test_context)
1742 from orca import dbus_service
1743
1744 is_running = case["is_running"]
1745 has_pending = case["has_pending"]
1746 mock_service_returns = case["mock_service_returns"]
1747 expected_result = case["expected_result"]
1748 expects_service_call = case["expects_service_call"]
1749
1750 controller = dbus_service.OrcaRemoteController()
1751
1752 if has_pending:
1753 controller._pending_registrations["TestModule"] = test_context.Mock()
1754
1755 if is_running:
1756 mock_service = test_context.Mock()
1757 mock_service.remove_module_interface.return_value = mock_service_returns
1758 controller._is_running = True
1759 controller._dbus_service_interface = mock_service
1760 controller._bus = test_context.Mock()
1761
1762 result = controller.deregister_module_commands("TestModule")
1763 assert result is expected_result
1764
1765 if has_pending:
1766 assert "TestModule" not in controller._pending_registrations
1767
1768 if expects_service_call:
1769 mock_service.remove_module_interface.assert_called_once()
1770
1771 def test_process_pending_registrations_empty(self, test_context: OrcaTestContext) -> None:
1772 """Test OrcaRemoteController._process_pending_registrations empty."""
1773
1774 self._setup_dependencies(test_context)
1775 from orca import dbus_service
1776
1777 controller = dbus_service.OrcaRemoteController()
1778 controller._process_pending_registrations()
1779
1780 def test_process_pending_registrations_with_modules(
1781 self,
1782 test_context: OrcaTestContext,
1783 ) -> None:
1784 """Test OrcaRemoteController._process_pending_registrations with modules."""
1785
1786 self._setup_dependencies(test_context)
1787 from orca import dbus_service
1788
1789 controller = dbus_service.OrcaRemoteController()
1790 mock_register = test_context.Mock()
1791 test_context.patch_object(
1792 controller,
1793 "_register_decorated_commands_internal",
1794 new=mock_register,
1795 )
1796 mock_module1 = test_context.Mock()
1797 mock_module2 = test_context.Mock()
1798 controller._pending_registrations = {"Module1": mock_module1, "Module2": mock_module2}
1799 controller._process_pending_registrations()
1800 assert not controller._pending_registrations
1801 assert mock_register.call_count == 2
1802 mock_register.assert_any_call("Module1", mock_module1)
1803 mock_register.assert_any_call("Module2", mock_module2)
1804
1805 @pytest.mark.parametrize(
1806 "case",
1807 [
1808 {
1809 "id": "no_interface",
1810 "has_interface": False,
1811 "expected_count_check": lambda count: count == 0,
1812 },
1813 {
1814 "id": "with_interface",
1815 "has_interface": True,
1816 "expected_count_check": lambda count: count >= 3,
1817 },
1818 ],
1819 ids=lambda case: case["id"],
1820 )
1821 def test_count_system_commands_scenarios(
1822 self,
1823 test_context: OrcaTestContext,
1824 case: dict,
1825 ) -> None:
1826 """Test OrcaRemoteController._count_system_commands with and without interface."""
1827 self._setup_dependencies(test_context)
1828 from orca import dbus_service
1829
1830 has_interface = case["has_interface"]
1831 expected_count_check = case["expected_count_check"]
1832
1833 controller = dbus_service.OrcaRemoteController()
1834 if has_interface:
1835 controller._dbus_service_interface = dbus_service.OrcaDBusServiceInterface()
1836
1837 count = controller._count_system_commands()
1838 assert expected_count_check(count)
1839
1840 def test_print_registration_summary(self, test_context: OrcaTestContext) -> None:
1841 """Test OrcaRemoteController._print_registration_summary."""
1842
1843 self._setup_dependencies(test_context)
1844 from orca import dbus_service
1845
1846 controller = dbus_service.OrcaRemoteController()
1847 controller._total_commands = 5
1848 controller._total_getters = 3
1849 controller._total_setters = 2
1850 controller._total_modules = 2
1851 mock_count = test_context.Mock(return_value=4)
1852 test_context.patch_object(controller, "_count_system_commands", new=mock_count)
1853 controller._print_registration_summary()
1854 mock_count.assert_called_once()
1855
1856 def test_get_remote_controller(self, test_context: OrcaTestContext) -> None:
1857 """Test get_remote_controller function."""
1858
1859 self._setup_dependencies(test_context)
1860 from orca import dbus_service
1861
1862 controller = dbus_service.get_remote_controller()
1863 assert isinstance(controller, dbus_service.OrcaRemoteController)
1864
1865 def test_extract_function_parameters_complex_annotation(
1866 self,
1867 test_context: OrcaTestContext,
1868 ) -> None:
1869 """Test _extract_function_parameters complex annotation without __name__."""
1870
1871 self._setup_dependencies(test_context)
1872 from orca import dbus_service
1873
1874 def test_func(self, param1: list[str]) -> None: # pylint: disable=unused-argument
1875 pass
1876
1877 params = dbus_service._extract_function_parameters(test_func)
1878 assert len(params) == 1
1879 assert params[0][0] == "param1"
1880 # Complex types without __name__ get string representation
1881 assert "list" in params[0][1] or "List" in params[0][1]
1882
1883 def test_to_variant_empty_list_tuples(self, test_context: OrcaTestContext) -> None:
1884 """Test OrcaModuleDBusInterface._to_variant empty list tuples."""
1885
1886 self._setup_dependencies(test_context)
1887 from orca import dbus_service
1888
1889 empty_tuples: list[tuple[str, str]] = []
1890 variant = dbus_service.OrcaModuleDBusInterface._to_variant(empty_tuples)
1891 assert variant.get_type_string() == "as" # Empty list defaults to string array
1892 assert variant.unpack() == []
1893
1894 def test_to_variant_mixed_types_list(self, test_context: OrcaTestContext) -> None:
1895 """Test OrcaModuleDBusInterface._to_variant mixed types list."""
1896
1897 self._setup_dependencies(test_context)
1898 from orca import dbus_service
1899
1900 mixed_list = ["string", 42, True]
1901 variant = dbus_service.OrcaModuleDBusInterface._to_variant(mixed_list)
1902 assert variant.get_type_string() == "av"
1903 unpacked = variant.unpack()
1904 assert len(unpacked) == 3
1905
1906 def test_register_decorated_commands_internal_not_ready(
1907 self,
1908 test_context: OrcaTestContext,
1909 ) -> None:
1910 """Test OrcaRemoteController._register_decorated_commands_internal not ready."""
1911
1912 self._setup_dependencies(test_context)
1913 from orca import dbus_service
1914
1915 controller = dbus_service.OrcaRemoteController()
1916 mock_module = test_context.Mock()
1917
1918 # This should return early and not process anything
1919 controller._register_decorated_commands_internal("TestModule", mock_module)
1920
1921 # Nothing should be changed since service is not ready
1922 assert controller._total_commands == 0
1923 assert controller._total_getters == 0
1924 assert controller._total_setters == 0
1925 assert controller._total_modules == 0
1926
1927 def test_register_decorated_commands_internal_with_decorators(
1928 self,
1929 test_context: OrcaTestContext,
1930 ) -> None:
1931 """Test OrcaRemoteController._register_decorated_commands_internal with decorators."""
1932
1933 self._setup_dependencies(test_context)
1934 from orca import dbus_service
1935
1936 class MockModule:
1937 """Mock module with decorated methods."""
1938
1939 def regular_method(self) -> str:
1940 """Regular method without decoration."""
1941
1942 return "regular"
1943
1944 def command_method(self) -> str:
1945 """Test command method."""
1946
1947 return "command"
1948
1949 def param_command_method(self) -> str:
1950 """Test parameterized command."""
1951
1952 return "param_command"
1953
1954 def getter_method(self) -> str:
1955 """Test getter method."""
1956
1957 return "getter"
1958
1959 def setter_method(self) -> str:
1960 """Test setter method."""
1961
1962 return "setter"
1963
1964 # Add decorations to methods
1965 MockModule.command_method.dbus_command_description = "Test command method."
1966 MockModule.param_command_method.dbus_parameterized_command_description = (
1967 "Test parameterized command."
1968 )
1969 MockModule.getter_method.dbus_getter_description = "Test getter method."
1970 MockModule.setter_method.dbus_setter_description = "Test setter method."
1971 mock_module = MockModule()
1972 controller = dbus_service.OrcaRemoteController()
1973 controller._is_running = True
1974 controller._dbus_service_interface = test_context.Mock()
1975 controller._bus = test_context.Mock()
1976
1977 def mock_get_manager():
1978 return test_context.Mock()
1979
1980 def mock_remote_controller_event():
1981 return test_context.Mock()
1982
1983 # Patch modules directly since they're imported locally in the method
1984 test_context.patch("orca.script_manager.get_manager", new=mock_get_manager)
1985 test_context.patch(
1986 "orca.input_event.RemoteControllerEvent",
1987 new=mock_remote_controller_event,
1988 )
1989 controller._register_decorated_commands_internal("TestModule", mock_module)
1990 assert controller._total_commands == 2 # command + parameterized command
1991 assert controller._total_getters == 1
1992 assert controller._total_setters == 1
1993 assert controller._total_modules == 1
1994
1995 def test_register_decorated_commands_internal_no_handlers(
1996 self,
1997 test_context: OrcaTestContext,
1998 ) -> None:
1999 """Test OrcaRemoteController._register_decorated_commands_internal no handlers."""
2000
2001 self._setup_dependencies(test_context)
2002 from orca import dbus_service
2003
2004 class MockModule:
2005 """Mock module without decorated methods."""
2006
2007 def regular_method(self) -> str:
2008 """Regular method without decoration."""
2009
2010 return "regular"
2011
2012 mock_module = MockModule()
2013 controller = dbus_service.OrcaRemoteController()
2014 controller._is_running = True
2015 controller._dbus_service_interface = test_context.Mock()
2016 controller._bus = test_context.Mock()
2017
2018 # Properly patch the method we want to assert on
2019 mock_add_interface = test_context.Mock()
2020 test_context.patch_object(
2021 controller._dbus_service_interface,
2022 "add_module_interface",
2023 new=mock_add_interface,
2024 )
2025 controller._register_decorated_commands_internal("TestModule", mock_module)
2026 assert controller._total_commands == 0
2027 assert controller._total_getters == 0
2028 assert controller._total_setters == 0
2029 assert controller._total_modules == 0
2030 mock_add_interface.assert_not_called()
2031
2032 def test_start_unpublish_object_error_during_cleanup(
2033 self,
2034 test_context: OrcaTestContext,
2035 ) -> None:
2036 """Test OrcaRemoteController.start unpublish object error during cleanup."""
2037
2038 self._setup_dependencies(test_context)
2039 from orca import dbus_service
2040
2041 mock_dbus_error = self._get_mock_dbus_error()
2042 mock_bus = test_context.Mock()
2043 mock_bus.connection.get_unique_name.return_value = "test_name"
2044 mock_bus.register_service.side_effect = mock_dbus_error("Register failed")
2045 mock_bus.unpublish_object.side_effect = mock_dbus_error("Unpublish failed")
2046 test_context.patch_object(dbus_service, "SessionMessageBus", return_value=mock_bus)
2047
2048 controller = dbus_service.OrcaRemoteController()
2049 result = controller.start()
2050 assert result is False
2051 assert controller._bus is None
2052 assert controller._dbus_service_interface is None