dbusmock ======== .. py:module:: dbusmock .. autoapi-nested-parse:: Mock D-Bus objects for test suites. Submodules ---------- .. toctree:: :maxdepth: 1 /autoapi/dbusmock/__main__/index /autoapi/dbusmock/mockobject/index /autoapi/dbusmock/pytest_fixtures/index /autoapi/dbusmock/templates/index /autoapi/dbusmock/testcase/index Attributes ---------- .. autoapisummary:: dbusmock.MOCK_IFACE dbusmock.OBJECT_MANAGER_IFACE Classes ------- .. autoapisummary:: dbusmock.DBusMockObject dbusmock.BusType dbusmock.DBusTestCase dbusmock.PrivateDBus dbusmock.SpawnedMock Functions --------- .. autoapisummary:: dbusmock.get_object dbusmock.get_objects Package Contents ---------------- .. py:data:: MOCK_IFACE :value: 'org.freedesktop.DBus.Mock' .. py:data:: OBJECT_MANAGER_IFACE :value: 'org.freedesktop.DBus.ObjectManager' .. 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:function:: get_object(path) -> DBusMockObject Return object for a given object path .. py:function:: get_objects() -> KeysView[str] Return all existing object paths .. py:class:: BusType Bases: :py:obj:`enum.Enum` Represents a system or session bus .. py:attribute:: SESSION :value: 'session' .. py:attribute:: SYSTEM :value: 'system' .. py:property:: environ :type: Tuple[str, Optional[str]] Returns the name and value of this bus' address environment variable .. py:method:: get_connection() -> dbus.bus.Connection 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. .. py:method:: reload_configuration() Notify this bus that it needs to reload the configuration .. py:method:: wait_for_bus_object(dest: str, path: str, timeout: float = 60.0) 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. .. py:class:: DBusTestCase(methodName='runTest') Bases: :py:obj:`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. .. py:attribute:: session_bus_pid :value: None .. py:attribute:: system_bus_pid :value: None .. py:method:: get_services_dir(system_bus: bool = False) -> str :staticmethod: 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. .. py:method:: tearDownClass() :classmethod: Hook method for deconstructing the class fixture after running all tests in the class. .. py:method:: start_session_bus() -> None :classmethod: Set up a private local session bus This gets stopped automatically at class teardown. .. py:method:: start_system_bus() -> None :classmethod: Set up a private local system bus This gets stopped automatically at class teardown. .. py:method:: start_dbus(conf: Optional[str] = None) -> Tuple[int, str] :staticmethod: 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. .. py:method:: stop_dbus(pid: int) -> None :staticmethod: 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(). .. py:method:: get_dbus(system_bus: bool = False) -> dbus.Bus :staticmethod: 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. .. py:method:: wait_for_bus_object(dest: str, path: str, system_bus: bool = False, timeout: int = 600) :staticmethod: 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. .. py:method:: spawn_server(name: str, path: str, interface: str, system_bus: bool = False, stdout=None) -> subprocess.Popen :staticmethod: 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. .. py:method:: spawn_server_template(template: str, parameters: Optional[Dict[str, Any]] = None, stdout=None, system_bus: Optional[bool] = None) -> Tuple[subprocess.Popen, dbus.proxies.ProxyObject] :staticmethod: 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. .. py:method:: enable_service(service, system_bus: bool = False) -> None :staticmethod: 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. .. py:method:: disable_service(service, system_bus: bool = False) -> None :staticmethod: 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. .. py:class:: PrivateDBus(bustype: BusType) 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. .. py:attribute:: bustype .. py:method:: __enter__() -> PrivateDBus .. py:method:: __exit__(exc_type, exc_val, exc_tb) .. py:property:: address :type: str Returns this D-Bus' address in the environment variable format, i.e. something like unix:path=/path/to/socket .. py:property:: servicedir :type: pathlib.Path The services directory (full path) for any ``.service`` files that need to be known to this D-Bus. .. py:property:: pid :type: int Return the pid of this D-Bus daemon process .. py:method:: start() Start the D-Bus daemon .. py:method:: stop() Stop the D-Bus daemon .. py:method:: enable_service(service: str) 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. .. py:method:: disable_service(service) 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. .. py:class:: SpawnedMock(process: subprocess.Popen, obj: dbus.proxies.ProxyObject) 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. .. py:property:: process :type: subprocess.Popen Returns the process that is this mock template .. py:property:: obj The D-Bus object this server was spawned for .. py:method:: __enter__() -> SpawnedMock .. py:method:: __exit__(exc_type, exc_val, exc_tb) .. py:method:: terminate() Terminate the process .. py:property:: stdout The stdout of the process, if no caller-specific stdout was specified in spawn_for_name() or spawn_with_template(). .. py:property:: stderr The stderr of the process, if no caller-specific stderr was specified in spawn_for_name() or spawn_with_template(). .. py:method:: spawn_for_name(name: str, path: str, interface: str, bustype: BusType = BusType.SESSION, stdout=subprocess.PIPE, stderr=subprocess.PIPE) -> SpawnedMock :classmethod: 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. .. py:method:: spawn_with_template(template: str, parameters: Optional[Dict[str, Any]] = None, bustype: Optional[BusType] = None, stdout=subprocess.PIPE, stderr=subprocess.PIPE) :classmethod: 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).