dbusmock.mockobject

Mock D-Bus objects for test suites.

Attributes

__author__

__copyright__

objects

MOCK_IFACE

OBJECT_MANAGER_IFACE

PropsType

MethodType

CallLogType

orig_method_lookup

Classes

DBusMockObject

Mock D-Bus object

Functions

load_module_from_path(path, template_name)

Load a mock template from a file path

load_module(name)

Load a mock template Python module

loggedmethod(self, func)

Decorator for a method to end in the call log

get_objects(→ KeysView[str])

Return all existing object paths

get_object(→ DBusMockObject)

Return object for a given object path

Module Contents

dbusmock.mockobject.__author__ = 'Martin Pitt'[source]
Show Value
"""
(c) 2012 Canonical Ltd.
(c) 2017 - 2022 Martin Pitt <martin@piware.de>
"""
dbusmock.mockobject.objects: Dict[str, DBusMockObject][source]
dbusmock.mockobject.MOCK_IFACE = 'org.freedesktop.DBus.Mock'[source]
dbusmock.mockobject.OBJECT_MANAGER_IFACE = 'org.freedesktop.DBus.ObjectManager'[source]
dbusmock.mockobject.PropsType[source]
dbusmock.mockobject.MethodType[source]
dbusmock.mockobject.CallLogType[source]
dbusmock.mockobject.load_module_from_path(path: pathlib.Path, template_name: str)[source]

Load a mock template from a file path

dbusmock.mockobject.load_module(name: str)[source]

Load a mock template Python module

This can be a path to the template’s .py file, a bare module name in $XDG_DATA_DIRS/python-dbusmock/templates/, or a bare module name in dbusmock’s shipped templates.

dbusmock.mockobject.loggedmethod(self, func)[source]

Decorator for a method to end in the call log

class dbusmock.mockobject.DBusMockObject(bus_name: str, path: str, interface: str, props: PropsType, logfile: str | None = None, is_object_manager: bool = False, mock_data: Any = None)[source]

Bases: dbus.service.Object

Mock D-Bus object

This can be configured to have arbitrary methods (including code execution) and properties via methods on the org.freedesktop.DBus.Mock interface, so that you can control the mock from any programming language.

Beyond that “remote control” API, this is a standard dbus-python service object.

bus_name[source]
path[source]
interface[source]
is_object_manager[source]
object_manager: DBusMockObject | None = None[source]
logfile[source]
is_logfile_owner = True[source]
call_log: List[CallLogType] = [][source]
mock_data[source]
__del__() None[source]
Get(interface_name: str, property_name: str) Any[source]

Standard D-Bus API for getting a property value

GetAll(interface_name: str, *_, **__) PropsType[source]

Standard D-Bus API for getting all property values

Set(interface_name: str, property_name: str, value: Any, *_, **__) None[source]

Standard D-Bus API for setting a property value

AddObject(path: str, interface: str, properties: PropsType, methods: List[MethodType], **kwargs) None[source]

Dynamically add a new D-Bus object to the mock

Parameters:
  • path – D-Bus object path

  • interface – Primary D-Bus interface name of this object (where properties and methods will be put on)

  • properties – A property_name (string) → value map with initial properties on “interface”

  • methods – An array of 4-tuples (name, in_sig, out_sig, code) describing methods to add to “interface”; see AddMethod() for details of the tuple values

Keyword Arguments: :param mock_class: A DBusMockObject derived class name (this is only possible

when the method is not called via dbus)

Parameters:

mock_data – Additional data which will be passed to the DBusMockObject constructor

If this is a D-Bus ObjectManager instance, the InterfacesAdded signal will not be emitted for the object automatically; it must be emitted manually if desired. This is because AddInterface may be called after AddObject, but before the InterfacesAdded signal should be emitted.

Example:

dbus_proxy.AddObject('/com/example/Foo/Manager',
                     'com.example.Foo.Control',
                     {
                         'state': dbus.String('online'),
                     },
                     [
                         ('Start', '', '', ''),
                         ('EchoInt', 'i', 'i', 'ret = args[0]'),
                         ('GetClients', '', 'ao', 'ret = ["/com/example/Foo/Client1"]'),
                     ])

Example 2 (in a template):

class FooManager(dbusmock.mockobject.DBusMockObject):
    def __init__(self, *args, **kwargs):
        super(FooManager, self).__init__(*args, **kwargs)
        self.magic = kwargs.get('mock_data')

    @dbus.service.method('com.example.Foo.Control', in_signature='i', out_signature='i')
    def EchoMagic(self, input):
        return self.magic + input

dbus_proxy.AddObject('/com/example/Foo/Manager',
                     'com.example.Foo.Control',
                     {}, [],
                     mock_class=FooManager,
                     mock_data=42)
RemoveObject(path: str) None[source]

Remove a D-Bus object from the mock

As with AddObject, this will not emit the InterfacesRemoved signal if it’s an ObjectManager instance.

Reset() None[source]

Reset the mock object state.

Remove all mock objects from the bus and tidy up so the state is as if python-dbusmock had just been restarted. If the mock object was originally created with a template (from the command line, the Python API or by calling AddTemplate over D-Bus), it will be re-instantiated with that template.

AddMethod(interface, name: str, in_sig: str, out_sig: str, code: str) None[source]

Dynamically add a method to this object

Parameters:
  • interface – D-Bus interface to add this to. For convenience you can specify ‘’ here to add the method to the object’s main interface (as specified on construction).

  • name – Name of the method

  • in_sig – Signature of input arguments; for example “ias” for a method that takes an int32 and a string array as arguments; see the DBus spec.

  • out_sig – Signature of output arguments; for example “s” for a method that returns a string; use ‘’ for methods that do not return anything.

  • code

    Python 3 code to run in the method call; you have access to the arguments through the “args” list, and can set the return value by assigning a value to the “ret” variable. You can also read the global “objects” variable, which is a dictionary mapping object paths to DBusMockObject instances.

    For keeping state across method calls, you are free to use normal Python members of the “self” object, which will be persistent for the whole mock’s life time. E. g. you can have a method with “self.my_state = True”, and another method that returns it with “ret = self.my_state”.

    Methods can raise exceptions in the usual way, in particular dbus.exceptions.DBusException.

    When specifying ‘’, the method will not do anything (except logging) and return None.

This is meant for adding a method to a mock at runtime, from any programming language. You can also use it in templates in the load() function.

For implementing non-trivial and static methods in templates, it is recommended to implement them in the normal dbus-python way with using the @dbus.service.method decorator instead.

AddMethods(interface: str, methods: List[MethodType]) None[source]

Add several methods to this object

Parameters:
  • interface – D-Bus interface to add this to. For convenience you can specify ‘’ here to add the method to the object’s main interface (as specified on construction).

  • methods – list of 4-tuples (name, in_sig, out_sig, code) describing one method each. See AddMethod() for details of the tuple values.

UpdateProperties(interface: str, properties: PropsType) None[source]

Update properties on this object and send a PropertiesChanged signal

Parameters:
  • interface – D-Bus interface to update this to. For convenience you can specify ‘’ here to add the property to the object’s main interface (as specified on construction).

  • properties – A property_name (string) → value map

AddProperty(interface: str, name: str, value: Any) None[source]

Add property to this object

Parameters:
  • interface – D-Bus interface to add this to. For convenience you can specify ‘’ here to add the property to the object’s main interface (as specified on construction).

  • name – Property name.

  • value – Property value.

AddProperties(interface: str, properties: PropsType) None[source]

Add several properties to this object

Parameters:
  • interface – D-Bus interface to add this to. For convenience you can specify ‘’ here to add the property to the object’s main interface (as specified on construction).

  • properties – A property_name (string) → value map

AddTemplate(template: str, parameters: PropsType) None[source]

Load a template into the mock.

python-dbusmock ships a set of standard mocks for common system services such as UPower and NetworkManager. With these the actual tests become a lot simpler, as they only have to set up the particular properties for the tests, and not the skeleton of common properties, interfaces, and methods.

Parameters:
  • template – Name of the template to load or the full path to a *.py file for custom templates. See “pydoc dbusmock.templates” for a list of available templates from python-dbusmock package, and “pydoc dbusmock.templates.NAME” for documentation about template NAME.

  • parameters – A parameter (string) → value (variant) map, for parameterizing templates. Each template can define their own, see documentation of that particular template for details.

EmitSignal(interface: str, name: str, signature: str, sigargs: Tuple[Any, Ellipsis]) None[source]

Emit a signal from the object.

Parameters:
  • interface – D-Bus interface to send the signal from. For convenience you can specify ‘’ here to add the method to the object’s main interface (as specified on construction).

  • name – Name of the signal

  • signature – Signature of input arguments; for example “ias” for a signal that takes an int32 and a string array as arguments; see http://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-signatures

  • args – variant array with signal arguments; must match order and type in “signature”

EmitSignalDetailed(interface: str, name: str, signature: str, sigargs: Tuple[Any, Ellipsis], details: PropsType) None[source]

Emit a signal from the object with extra details.

Parameters:
  • interface – D-Bus interface to send the signal from. For convenience you can specify ‘’ here to add the method to the object’s main interface (as specified on construction).

  • name – Name of the signal

  • signature – Signature of input arguments; for example “ias” for a signal that takes an int32 and a string array as arguments; see http://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-signatures

  • args – variant array with signal arguments; must match order and type in “signature”

  • details – dictionary with a string key/value entries. Supported keys are: “destination”: for the signal destination “path”: for the object path to send the signal from

GetCalls() List[CallLogType][source]

List all the logged calls since the last call to ClearCalls().

Return a list of (timestamp, method_name, args_list) tuples.

GetMethodCalls(method: str) List[Tuple[int, Sequence[Any]]][source]

List all the logged calls of a particular method.

Return a list of (timestamp, args_list) tuples.

ClearCalls() None[source]

Empty the log of mock call signatures.

MethodCalled(name, args)[source]

Signal emitted for every called mock method.

This is emitted for all mock method calls. This can be used to confirm that a particular method was called with particular arguments, as an alternative to reading the mock’s log or GetCalls().

object_manager_emit_added(path: str) None[source]

Emit ObjectManager.InterfacesAdded signal

object_manager_emit_removed(path: str) None[source]

Emit ObjectManager.InterfacesRemoved signal

mock_method(interface: str, dbus_method: str, in_signature: str, *m_args, **_) Any[source]

Master mock method.

This gets “instantiated” in AddMethod(). Execute the code snippet of the method and return the “ret” variable if it was set.

log(msg: str) None[source]

Log a message, prefixed with a timestamp.

If a log file was specified in the constructor, it is written there, otherwise it goes to stdout.

Introspect(object_path: str, connection: dbus.connection.Connection) str[source]

Return XML description of this object’s interfaces, methods and signals.

This wraps dbus-python’s Introspect() method to include the dynamic methods and properties.

dbusmock.mockobject.orig_method_lookup[source]
dbusmock.mockobject.get_objects() KeysView[str][source]

Return all existing object paths

dbusmock.mockobject.get_object(path) DBusMockObject[source]

Return object for a given object path