dbusmock

Mock D-Bus objects for test suites.

Submodules

Attributes

MOCK_IFACE

OBJECT_MANAGER_IFACE

Classes

DBusMockObject

Mock D-Bus object

BusType

Represents a system or session bus

DBusTestCase

Base class for D-Bus mock tests.

PrivateDBus

A D-Bus daemon instance that represents a private session or system bus.

SpawnedMock

An instance of a D-Bus mock template instance in a separate process.

Functions

get_object(→ DBusMockObject)

Return object for a given object path

get_objects(→ KeysView[str])

Return all existing object paths

Package Contents

dbusmock.MOCK_IFACE = 'org.freedesktop.DBus.Mock'[source]
dbusmock.OBJECT_MANAGER_IFACE = 'org.freedesktop.DBus.ObjectManager'[source]
class dbusmock.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
path
interface
is_object_manager
object_manager: DBusMockObject | None = None
logfile
is_logfile_owner = True
call_log: List[CallLogType] = []
mock_data
__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.get_object(path) DBusMockObject[source]

Return object for a given object path

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

Return all existing object paths

class dbusmock.BusType[source]

Bases: enum.Enum

Represents a system or session bus

SESSION = 'session'
SYSTEM = 'system'
property environ: Tuple[str, str | None]

Returns the name and value of this bus’ address environment variable

get_connection() dbus.bus.Connection[source]

Get a dbus.bus.BusConnection() object to this bus.

This uses the current environment variables for this bus (if any) and falls back to dbus.SystemBus() or dbus.SessionBus() otherwise.

This is preferrable to dbus.SystemBus() and dbus.SessionBus() as those do not get along with multiple changing local test buses.

reload_configuration()[source]

Notify this bus that it needs to reload the configuration

wait_for_bus_object(dest: str, path: str, timeout: float = 60.0)[source]

Wait for an object to appear on D-Bus

Raise an exception if object does not appear within one minute. You can change the timeout in seconds with the “timeout” keyword argument.

class dbusmock.DBusTestCase(methodName='runTest')[source]

Bases: unittest.TestCase

Base class for D-Bus mock tests.

This provides some convenience API to start/stop local D-Buses, so that you can run a private local session and/or system bus to run mocks on.

This also provides a spawn_server() static method to run the D-Bus mock server in a separate process.

session_bus_pid = None
system_bus_pid = None
static get_services_dir(system_bus: bool = False) str[source]

Returns the private services directory for the bus type in question. This allows dropping in a .service file so that the dbus server inside dbusmock can launch it.

classmethod tearDownClass()[source]

Hook method for deconstructing the class fixture after running all tests in the class.

classmethod start_session_bus() None[source]

Set up a private local session bus

This gets stopped automatically at class teardown.

classmethod start_system_bus() None[source]

Set up a private local system bus

This gets stopped automatically at class teardown.

static start_dbus(conf: str | None = None) Tuple[int, str][source]

Start a D-Bus daemon

Return (pid, address) pair.

Normally you do not need to call this directly. Use start_system_bus() and start_session_bus() instead.

static stop_dbus(pid: int) None[source]

Stop a D-Bus daemon

Normally you do not need to call this directly. When you use start_system_bus() and start_session_bus(), these buses are automatically stopped in tearDownClass().

static get_dbus(system_bus: bool = False) dbus.Bus[source]

Get a dbus.bus.BusConnection() object to this bus

This is preferrable to dbus.SystemBus() and dbus.SessionBus() as those do not get along with multiple changing local test buses.

This is a legacy method kept for backwards compatibility, use BusType.get_connection() instead.

static wait_for_bus_object(dest: str, path: str, system_bus: bool = False, timeout: int = 600)[source]

Wait for an object to appear on D-Bus

Raise an exception if object does not appear within one minute. You can change the timeout with the “timeout” keyword argument which specifies deciseconds.

This is a legacy method kept for backwards compatibility, use BusType.wait_for_bus_object() instead.

static spawn_server(name: str, path: str, interface: str, system_bus: bool = False, stdout=None) subprocess.Popen[source]

Run a DBusMockObject instance in a separate process

The daemon will terminate automatically when the D-Bus that it connects to goes down. If that does not happen (e. g. you test on the actual system/session bus), you need to kill it manually.

This function blocks until the spawned DBusMockObject is ready and listening on the bus.

Returns the Popen object of the spawned daemon.

This is a legacy method kept for backwards compatibility, use SpawnedMock.spawn_for_name() instead.

static spawn_server_template(template: str, parameters: Dict[str, Any] | None = None, stdout=None, system_bus: bool | None = None) Tuple[subprocess.Popen, dbus.proxies.ProxyObject][source]

Run a D-Bus mock template instance in a separate process

This starts a D-Bus mock process and loads the given template with (optional) parameters into it. For details about templates see dbusmock.DBusMockObject.AddTemplate().

Usually a template should specify SYSTEM_BUS = False/True to select whether it gets loaded on the session or system bus. This can be overridden with the system_bus parameter. For templates which don’t set SYSTEM_BUS, this parameter has to be set.

The daemon will terminate automatically when the D-Bus that it connects to goes down. If that does not happen (e. g. you test on the actual system/session bus), you need to kill it manually.

This function blocks until the spawned DBusMockObject is ready and listening on the bus.

Returns a pair (daemon Popen object, main dbus object).

This is a legacy method kept for backwards compatibility, use SpawnedMock.spawn_with_template() instead.

static enable_service(service, system_bus: bool = False) None[source]

Enable the given well known service name inside dbusmock

This symlinks a service file from the usual dbus service directories into the dbusmock environment. Doing that allows the service to be launched automatically if they are defined within $XDG_DATA_DIRS.

The daemon configuration is reloaded if a test bus is running.

This is a legacy method kept for backwards compatibility. Use PrivateDBus.enable_service() instead.

static disable_service(service, system_bus: bool = False) None[source]

Disable the given well known service name inside dbusmock

This unlink’s the .service file for the service and reloads the daemon configuration if a test bus is running.

class dbusmock.PrivateDBus(bustype: BusType)[source]

A D-Bus daemon instance that represents a private session or system bus.

If used as a context manager it will automatically start the bus and clean up after itself on exit:

>>> with PrivateDBus(BusType.SESSION) as bus:
>>>    do_something(bus)

Otherwise, start() and stop() manually.

bustype
__enter__() PrivateDBus[source]
__exit__(exc_type, exc_val, exc_tb)[source]
property address: str

Returns this D-Bus’ address in the environment variable format, i.e. something like unix:path=/path/to/socket

property servicedir: pathlib.Path

The services directory (full path) for any .service files that need to be known to this D-Bus.

property pid: int

Return the pid of this D-Bus daemon process

start()[source]

Start the D-Bus daemon

stop()[source]

Stop the D-Bus daemon

enable_service(service: str)[source]

Enable the given well-known service name inside dbusmock

This symlinks a service file from the usual dbus service directories into the dbusmock environment. Doing that allows the service to be launched automatically if they are defined within $XDG_DATA_DIRS.

The daemon configuration is reloaded if a test bus is running.

disable_service(service)[source]

Disable the given well known service name inside dbusmock

This unlink’s the .service file for the service and reloads the daemon configuration if a test bus is running.

class dbusmock.SpawnedMock(process: subprocess.Popen, obj: dbus.proxies.ProxyObject)[source]

An instance of a D-Bus mock template instance in a separate process.

See SpawnedMock.spawn_for_name() and SpawnedMock.spawn_with_template() the typical entry points.

property process: subprocess.Popen

Returns the process that is this mock template

property obj

The D-Bus object this server was spawned for

__enter__() SpawnedMock[source]
__exit__(exc_type, exc_val, exc_tb)[source]
terminate()[source]

Terminate the process

property stdout

The stdout of the process, if no caller-specific stdout was specified in spawn_for_name() or spawn_with_template().

property stderr

The stderr of the process, if no caller-specific stderr was specified in spawn_for_name() or spawn_with_template().

classmethod spawn_for_name(name: str, path: str, interface: str, bustype: BusType = BusType.SESSION, stdout=subprocess.PIPE, stderr=subprocess.PIPE) SpawnedMock[source]

Run a DBusMockObject instance in a separate process

The daemon will terminate automatically when the D-Bus that it connects to goes down. If that does not happen (e. g. you test on the actual system/session bus), you need to kill it manually.

This function blocks until the spawned DBusMockObject is ready and listening on the bus.

By default, stdout and stderr of the spawned process is available via the SpawnedMock.stdout and SpawnedMock.stderr properties on the returned object.

classmethod spawn_with_template(template: str, parameters: Dict[str, Any] | None = None, bustype: BusType | None = None, stdout=subprocess.PIPE, stderr=subprocess.PIPE)[source]

Run a D-Bus mock template instance in a separate process

This starts a D-Bus mock process and loads the given template with (optional) parameters into it. For details about templates see dbusmock.DBusMockObject.AddTemplate().

Usually a template should specify SYSTEM_BUS = False/True to select whether it gets loaded on the session or system bus. This can be overridden with the system_bus parameter. For templates which don’t set SYSTEM_BUS, this parameter has to be set.

The daemon will terminate automatically when the D-Bus that it connects to goes down. If that does not happen (e. g. you test on the actual system/session bus), you need to kill it manually.

This function blocks until the spawned DBusMockObject is ready and listening on the bus.

Returns a pair (daemon Popen object, main dbus object).