dbusmock.mockobject
===================
.. py:module:: dbusmock.mockobject
.. autoapi-nested-parse::
Mock D-Bus objects for test suites.
Attributes
----------
.. autoapisummary::
dbusmock.mockobject.__author__
dbusmock.mockobject.__copyright__
dbusmock.mockobject.objects
dbusmock.mockobject.MOCK_IFACE
dbusmock.mockobject.OBJECT_MANAGER_IFACE
dbusmock.mockobject.PropsType
dbusmock.mockobject.MethodType
dbusmock.mockobject.CallLogType
dbusmock.mockobject.orig_method_lookup
Classes
-------
.. autoapisummary::
dbusmock.mockobject.DBusMockObject
Functions
---------
.. autoapisummary::
dbusmock.mockobject.load_module_from_path
dbusmock.mockobject.load_module
dbusmock.mockobject.loggedmethod
dbusmock.mockobject.get_objects
dbusmock.mockobject.get_object
Module Contents
---------------
.. py:data:: __author__
:value: 'Martin Pitt'
.. py:data:: __copyright__
:value: Multiline-String
.. raw:: html
Show Value
.. code-block:: python
"""
(c) 2012 Canonical Ltd.
(c) 2017 - 2022 Martin Pitt
"""
.. raw:: html
.. py:data:: objects
:type: Dict[str, DBusMockObject]
.. py:data:: MOCK_IFACE
:value: 'org.freedesktop.DBus.Mock'
.. py:data:: OBJECT_MANAGER_IFACE
:value: 'org.freedesktop.DBus.ObjectManager'
.. py:data:: PropsType
.. py:data:: MethodType
.. py:data:: CallLogType
.. py:function:: load_module_from_path(path: pathlib.Path, template_name: str)
Load a mock template from a file path
.. py:function:: load_module(name: str)
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.
.. py:function:: loggedmethod(self, func)
Decorator for a method to end in the call log
.. py:class:: DBusMockObject(bus_name: str, path: str, interface: str, props: PropsType, logfile: Optional[str] = None, is_object_manager: bool = False, mock_data: Any = None)
Bases: :py:obj:`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 `_.
.. py:attribute:: bus_name
.. py:attribute:: path
.. py:attribute:: interface
.. py:attribute:: is_object_manager
:value: False
.. py:attribute:: object_manager
:type: Optional[DBusMockObject]
:value: None
.. py:attribute:: logfile
:value: None
.. py:attribute:: is_logfile_owner
:value: True
.. py:attribute:: call_log
:type: List[CallLogType]
:value: []
.. py:attribute:: mock_data
:value: None
.. py:method:: __del__() -> None
.. py:method:: Get(interface_name: str, property_name: str) -> Any
Standard D-Bus API for getting a property value
.. py:method:: GetAll(interface_name: str, *_, **__) -> PropsType
Standard D-Bus API for getting all property values
.. py:method:: Set(interface_name: str, property_name: str, value: Any, *_, **__) -> None
Standard D-Bus API for setting a property value
.. py:method:: AddObject(path: str, interface: str, properties: PropsType, methods: List[MethodType], **kwargs) -> None
Dynamically add a new D-Bus object to the mock
:param path: D-Bus object path
:param interface: Primary D-Bus interface name of this object (where
properties and methods will be put on)
:param properties: A property_name (string) → value map with initial
properties on "interface"
:param 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)
:param 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)
.. py:method:: RemoveObject(path: str) -> None
Remove a D-Bus object from the mock
As with AddObject, this will *not* emit the InterfacesRemoved signal if
it's an ObjectManager instance.
.. py:method:: Reset() -> None
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.
.. py:method:: AddMethod(interface, name: str, in_sig: str, out_sig: str, code: str) -> None
Dynamically add a method to this object
:param 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).
:param name: Name of the method
:param 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 `_.
:param out_sig: Signature of output arguments; for example "s" for a method
that returns a string; use '' for methods that do not return
anything.
:param 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.
.. py:method:: AddMethods(interface: str, methods: List[MethodType]) -> None
Add several methods to this object
:param 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).
:param methods: list of 4-tuples (name, in_sig, out_sig, code) describing one
method each. See AddMethod() for details of the tuple values.
.. py:method:: UpdateProperties(interface: str, properties: PropsType) -> None
Update properties on this object and send a PropertiesChanged signal
:param 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).
:param properties: A property_name (string) → value map
.. py:method:: AddProperty(interface: str, name: str, value: Any) -> None
Add property to this object
:param 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).
:param name: Property name.
:param value: Property value.
.. py:method:: AddProperties(interface: str, properties: PropsType) -> None
Add several properties to this object
:param 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).
:param properties: A property_name (string) → value map
.. py:method:: AddTemplate(template: str, parameters: PropsType) -> None
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.
:param 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.
:param parameters: A parameter (string) → value (variant) map, for
parameterizing templates. Each template can define their
own, see documentation of that particular template for
details.
.. py:method:: EmitSignal(interface: str, name: str, signature: str, sigargs: Tuple[Any, Ellipsis]) -> None
Emit a signal from the object.
:param 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).
:param name: Name of the signal
:param 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
:param args: variant array with signal arguments; must match order and type in
"signature"
.. py:method:: EmitSignalDetailed(interface: str, name: str, signature: str, sigargs: Tuple[Any, Ellipsis], details: PropsType) -> None
Emit a signal from the object with extra details.
:param 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).
:param name: Name of the signal
:param 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
:param args: variant array with signal arguments; must match order and type in
"signature"
:param 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
.. py:method:: GetCalls() -> List[CallLogType]
List all the logged calls since the last call to ClearCalls().
Return a list of (timestamp, method_name, args_list) tuples.
.. py:method:: GetMethodCalls(method: str) -> List[Tuple[int, Sequence[Any]]]
List all the logged calls of a particular method.
Return a list of (timestamp, args_list) tuples.
.. py:method:: ClearCalls() -> None
Empty the log of mock call signatures.
.. py:method:: MethodCalled(name, args)
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().
.. py:method:: object_manager_emit_added(path: str) -> None
Emit ObjectManager.InterfacesAdded signal
.. py:method:: object_manager_emit_removed(path: str) -> None
Emit ObjectManager.InterfacesRemoved signal
.. py:method:: mock_method(interface: str, dbus_method: str, in_signature: str, *m_args, **_) -> Any
Master mock method.
This gets "instantiated" in AddMethod(). Execute the code snippet of
the method and return the "ret" variable if it was set.
.. py:method:: log(msg: str) -> None
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.
.. py:method:: Introspect(object_path: str, connection: dbus.connection.Connection) -> str
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.
.. py:data:: orig_method_lookup
.. py:function:: get_objects() -> KeysView[str]
Return all existing object paths
.. py:function:: get_object(path) -> DBusMockObject
Return object for a given object path