Skip to content

Commit f572c92

Browse files
committed
Add sdbus.utils.inspect.inspect_dbus_attached_bus function
Returns the D-Bus bus used by the object.
1 parent 54ffe5b commit f572c92

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

src/sdbus/utils/inspect.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,32 @@ def inspect_dbus_path(
110110
raise TypeError(f"Expected D-Bus object got {obj!r}")
111111

112112

113+
def inspect_dbus_bus(
114+
obj: Union[DbusInterfaceBase, DbusInterfaceBaseAsync]
115+
) -> Optional[SdBus]:
116+
"""Return D-Bus bus used by the object.
117+
118+
If called on D-Bus proxies or exported local D-Bus objects returns
119+
bus object.
120+
121+
If called on local D-Bus objects that had not been exported returns None.
122+
123+
If called on an object that is unrelated to D-Bus raises ``TypeError``.
124+
125+
:param obj:
126+
Object to inspect.
127+
:returns:
128+
D-Bus bus object.
129+
130+
*New in version 0.14.1.*
131+
"""
132+
if isinstance(obj, (DbusInterfaceBase, DbusInterfaceBaseAsync)):
133+
return obj._dbus.attached_bus
134+
else:
135+
raise TypeError(f"Expected D-Bus object got {obj!r}")
136+
137+
113138
__all__ = (
139+
'inspect_dbus_bus',
114140
"inspect_dbus_path",
115141
)

test/test_sdbus_utils.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
from unittest import TestCase
2323

2424
from sdbus.unittest import IsolatedDbusTestCase
25-
from sdbus.utils.inspect import inspect_dbus_path
25+
from sdbus.utils.inspect import inspect_dbus_bus, inspect_dbus_path
2626
from sdbus.utils.parse import parse_get_managed_objects
2727

2828
from sdbus import (
@@ -258,3 +258,24 @@ def test_inspect_dbus_path_async_local(self) -> None:
258258

259259
with self.assertRaisesRegex(LookupError, "is not attached to bus"):
260260
inspect_dbus_path(local_obj, new_bus)
261+
262+
def test_inspect_attached_bus(self) -> None:
263+
proxy = DbusInterfaceCommon("example.org", TEST_PATH)
264+
265+
self.assertIs(inspect_dbus_bus(proxy), self.bus)
266+
267+
with self.assertRaises(TypeError):
268+
inspect_dbus_bus(object()) # type: ignore[arg-type]
269+
270+
def test_inspect_attached_bus_async(self) -> None:
271+
proxy = DbusInterfaceCommonAsync.new_proxy("example.org", TEST_PATH)
272+
273+
self.assertIs(inspect_dbus_bus(proxy), self.bus)
274+
275+
local_obj = FooBarAsync()
276+
277+
self.assertIsNone(inspect_dbus_bus(local_obj))
278+
279+
local_obj.export_to_dbus("/")
280+
281+
self.assertIs(inspect_dbus_bus(local_obj), self.bus)

0 commit comments

Comments
 (0)