File: mockobject.py

package info (click to toggle)
python-dbusmock 0.36.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 812 kB
  • sloc: python: 7,324; sh: 73; makefile: 4
file content (889 lines) | stat: -rw-r--r-- 36,772 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
"""Mock D-Bus objects for test suites."""

# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 3 of the License, or (at your option) any
# later version.  See http://www.gnu.org/copyleft/lgpl.html for the full text
# of the license.

__author__ = "Martin Pitt"
__copyright__ = """
(c) 2012 Canonical Ltd.
(c) 2017 - 2022 Martin Pitt <martin@piware.de>
"""

import copy
import functools
import importlib
import importlib.util
import os
import sys
import time
import types
from pathlib import Path
from typing import Any, Dict, KeysView, List, Optional, Sequence, Tuple
from xml.etree import ElementTree as ET

import dbus
import dbus.service

# we do not use this ourselves, but mock methods often want to use this
os  # pyflakes pylint: disable=pointless-statement  # noqa: B018

# global path -> DBusMockObject mapping
objects: Dict[str, "DBusMockObject"] = {}

MOCK_IFACE = "org.freedesktop.DBus.Mock"
OBJECT_MANAGER_IFACE = "org.freedesktop.DBus.ObjectManager"


PropsType = Dict[str, Any]
# (in_signature, out_signature, code, dbus_wrapper_fn)
MethodType = Tuple[str, str, str, str]
# (timestamp, method_name, call_args)
CallLogType = Tuple[int, str, Sequence[Any]]


def load_module_from_path(path: Path, template_name: str):
    """Load a mock template from a file path"""
    spec = importlib.util.spec_from_file_location(template_name, path)
    assert spec
    mod = importlib.util.module_from_spec(spec)
    exec(path.read_text("UTF-8"), mod.__dict__, mod.__dict__)  # pylint: disable=exec-used
    return mod


def 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.
    """
    # specified by path
    pname = Path(name)
    if pname.exists() and pname.suffix == ".py":
        return load_module_from_path(pname, pname.stem)

    # XDG_DATA_DIRS
    xdg_data_dirs = os.environ.get("XDG_DATA_DIRS") or "/usr/local/share/:/usr/share/"
    for d in xdg_data_dirs.split(":"):
        src = Path(d, "python-dbusmock", "templates", name + ".py")
        if src.exists():
            return load_module_from_path(src, name)

    # shipped inside dbusmock package
    return importlib.import_module("dbusmock.templates." + name)


def _format_args(args):
    """Format a D-Bus argument tuple into an appropriate logging string"""

    def format_arg(a):
        if isinstance(a, dbus.Boolean):
            return str(bool(a))
        if isinstance(a, (dbus.Byte, int)):
            return str(int(a))
        if isinstance(a, str):
            return '"' + str(a) + '"'
        if isinstance(a, list):
            return "[" + ", ".join([format_arg(x) for x in a]) + "]"
        if isinstance(a, dict):
            fmta = "{"
            first = True
            for k, v in a.items():
                if first:
                    first = False
                else:
                    fmta += ", "
                fmta += format_arg(k) + ": " + format_arg(v)
            return fmta + "}"

        # fallback
        return repr(a)

    s = ""
    for a in args:
        if s:
            s += " "
        s += format_arg(a)
    if s:
        s = " " + s
    return s


def _wrap_in_dbus_variant(value):
    dbus_types = [
        dbus.types.ByteArray,
        dbus.types.Int16,
        dbus.types.ObjectPath,
        dbus.types.UInt64,
        dbus.types.Boolean,
        dbus.types.Int32,
        dbus.types.Signature,
        dbus.types.UInt16,
        dbus.types.UnixFd,
        dbus.types.Byte,
        dbus.types.Double,
        dbus.types.Int64,
        dbus.types.String,
        dbus.types.UInt32,
    ]
    container_types = [
        dbus.types.Array,
        dbus.types.Struct,
        dbus.types.Dictionary,
    ]
    if isinstance(value, dbus.String):
        return dbus.String(str(value), variant_level=1)
    if type(value) in container_types:
        return value
    if type(value) in dbus_types:
        return type(value)(value.conjugate(), variant_level=1)
    if isinstance(value, str):
        return dbus.String(value, variant_level=1)
    raise dbus.exceptions.DBusException(f"could not wrap type {type(value)}")


def _convert_args(signature: str, args: Tuple[Any, ...]) -> List[Any]:
    """
    Convert types of arguments according to signature, using
    MethodCallMessage.append(); this will also provide type/length
    checks, except for the case of an empty signature
    """
    try:
        if signature == "" and len(args) > 0:
            raise TypeError("Fewer items found in D-Bus signature than in Python arguments")
        m = dbus.connection.MethodCallMessage("a.b", "/a", "a.b", "a")
        m.append(*args, signature=signature)
        return m.get_args_list()
    except Exception as e:
        raise dbus.exceptions.DBusException(
            f"Invalid arguments: {e!s}", name="org.freedesktop.DBus.Error.InvalidArgs"
        ) from e


def loggedmethod(self, func):
    """Decorator for a method to end in the call log"""

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        fname = func.__name__
        self_arg, args = args[0], args[1:]

        in_signature = getattr(func, "_dbus_in_signature", "")
        args = _convert_args(in_signature, args)

        self.log(fname + _format_args(args))
        self.call_log.append((int(time.time()), fname, args))
        self.MethodCalled(fname, args)

        return func(*[self_arg, *args], **kwargs)

    return wrapper


class DBusMockObject(dbus.service.Object):  # pylint: disable=too-many-instance-attributes
    """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 <https://dbus.freedesktop.org/doc/dbus-python/tutorial.html#exporting-objects>`_.
    """

    def __init__(
        self,
        bus_name: str,
        path: str,
        interface: str,
        props: PropsType,
        logfile: Optional[str] = None,
        is_object_manager: bool = False,
        mock_data: Any = None,
    ) -> None:
        """Create a new DBusMockObject

        :param bus_name: A dbus.service.BusName instance where the object will be put on
        :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 props: A property_name (string) → property (Variant) map with initial
                      properties on "interface"
        :param logfile: When given, method calls will be logged into that file name;
                        if None, logging will be written to stdout. Note that you can
                        also query the called methods over D-Bus with GetCalls() and
                        GetMethodCalls().
        :param is_object_manager: If True, the GetManagedObjects method will
                        automatically be implemented on the object, returning
                        all objects which have this one's path as a prefix of
                        theirs. Note that the InterfacesAdded and
                        InterfacesRemoved signals will not be automatically
                        emitted.
        """
        dbus.service.Object.__init__(self, bus_name, path)

        self.bus_name = bus_name
        self.path = path
        self.interface = interface
        self.is_object_manager = is_object_manager
        self.object_manager: Optional[DBusMockObject] = None

        self._template: Optional[str] = None
        self._template_parameters: Optional[PropsType] = None

        # pylint: disable=consider-using-with
        self.logfile = open(logfile, "wb") if logfile else None  # noqa: SIM115
        self.is_logfile_owner = True
        self.call_log: List[CallLogType] = []
        self.mock_data = mock_data

        if props is None:
            props = {}

        self._reset(props)

    def __del__(self) -> None:
        try:
            if self.logfile and self.is_logfile_owner:
                self.logfile.close()
        except AttributeError:
            pass

    def _set_up_object_manager(self) -> None:
        """Set up this mock object as a D-Bus ObjectManager."""
        cond = "k != '/'" if self.path == "/" else f"k.startswith('{self.path}/')"

        code = f"ret = {{dbus.ObjectPath(k): objects[k].props for k in objects.keys() if {cond} }}"
        self.AddMethod(OBJECT_MANAGER_IFACE, "GetManagedObjects", "", "a{oa{sa{sv}}}", code)
        self.object_manager = self

    def _reset(self, props: PropsType) -> None:
        # interface -> name -> value
        self.props = {self.interface: props}

        # interface -> name -> (in_signature, out_signature, code, dbus_wrapper_fn)
        self.methods: Dict[str, Dict[str, MethodType]] = {self.interface: {}}

        if self.is_object_manager:
            self._set_up_object_manager()

    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss", out_signature="v")
    def Get(self, interface_name: str, property_name: str) -> Any:
        """Standard D-Bus API for getting a property value"""

        self.log(f"Get {self.path} {interface_name}.{property_name}")

        if not interface_name:
            interface_name = self.interface
        try:
            return self.GetAll(interface_name)[property_name]
        except KeyError as e:
            raise dbus.exceptions.DBusException(
                "no such property " + property_name, name=self.interface + ".UnknownProperty"
            ) from e

    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s", out_signature="a{sv}")
    def GetAll(self, interface_name: str, *_, **__) -> PropsType:
        """Standard D-Bus API for getting all property values"""

        self.log(f"GetAll {self.path} {interface_name}")

        if not interface_name:
            interface_name = self.interface
        try:
            return self.props[interface_name]
        except KeyError as e:
            raise dbus.exceptions.DBusException(
                "no such interface " + interface_name, name=self.interface + ".UnknownInterface"
            ) from e

    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ssv", out_signature="")
    def Set(self, interface_name: str, property_name: str, value: Any, *_, **__) -> None:
        """Standard D-Bus API for setting a property value"""

        self.log(f"Set {self.path} {interface_name}.{property_name}{_format_args((value,))}")

        try:
            iface_props = self.props[interface_name]
        except KeyError as e:
            raise dbus.exceptions.DBusException(
                "no such interface " + interface_name, name=self.interface + ".UnknownInterface"
            ) from e

        if property_name not in iface_props:
            raise dbus.exceptions.DBusException(
                "no such property " + property_name, name=self.interface + ".UnknownProperty"
            )

        iface_props[property_name] = value

        self.EmitSignal(
            "org.freedesktop.DBus.Properties",
            "PropertiesChanged",
            "sa{sv}as",
            [interface_name, dbus.Dictionary({property_name: value}, signature="sv"), dbus.Array([], signature="s")],
        )

    @dbus.service.method(MOCK_IFACE, in_signature="ssa{sv}a(ssss)", out_signature="")
    def AddObject(
        self, 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)
        """
        if path in objects:
            raise dbus.exceptions.DBusException(
                f"object {path} already exists", name="org.freedesktop.DBus.Mock.NameError"
            )

        mock_class = kwargs.get("mock_class", DBusMockObject)
        mock_data = kwargs.get("mock_data")

        obj = mock_class(self.bus_name, path, interface, properties, mock_data=mock_data)
        # make sure created objects inherit the log file stream
        obj.logfile = self.logfile
        obj.object_manager = self.object_manager
        obj.is_logfile_owner = False
        obj.AddMethods(interface, methods)

        objects[path] = obj

    @dbus.service.method(MOCK_IFACE, in_signature="s", out_signature="")
    def RemoveObject(self, 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.
        """
        try:
            objects[path].remove_from_connection()
            del objects[path]
        except KeyError as e:
            raise dbus.exceptions.DBusException(
                f"object {path} does not exist", name="org.freedesktop.DBus.Mock.NameError"
            ) from e

    @dbus.service.method(MOCK_IFACE, in_signature="", out_signature="")
    def Reset(self) -> 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.
        """
        # Clear other existing objects.
        for obj_name, obj in objects.items():
            if obj_name != self.path:
                obj.remove_from_connection()
        objects.clear()

        # Reinitialise our state. Carefully remove new methods from our dict;
        # they don't not actually exist if they are a statically defined
        # template function
        for method_name in self.methods[self.interface]:
            try:
                delattr(self.__class__, method_name)
            except AttributeError:
                pass

        self._reset({})

        if self._template is not None:
            self.AddTemplate(self._template, self._template_parameters)

        objects[self.path] = self

    @dbus.service.method(MOCK_IFACE, in_signature="sssss", out_signature="")
    def AddMethod(self, 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 <http://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-signatures>`_.
        :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 <https://dbus.freedesktop.org/doc/dbus-python/dbus.html#dbus.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.
        """
        # pylint: disable=protected-access

        if not interface:
            interface = self.interface
        n_args = len(dbus.Signature(in_sig))

        # we need to have separate methods for dbus-python, so clone
        # mock_method(); using message_keyword with this dynamic approach fails
        # because inspect cannot handle those, so pass on interface and method
        # name as first positional arguments
        # pylint: disable=unnecessary-lambda-assignment
        method = lambda self, *args, **kwargs: DBusMockObject.mock_method(  # noqa: E731
            self, interface, name, in_sig, *args, **kwargs
        )

        # we cannot specify in_signature here, as that trips over a consistency
        # check in dbus-python; we need to set it manually instead
        dbus_method = dbus.service.method(interface, out_signature=out_sig)(method)
        dbus_method.__name__ = str(name)
        dbus_method._dbus_in_signature = in_sig
        dbus_method._dbus_args = [f"arg{i}" for i in range(1, n_args + 1)]

        # for convenience, add mocked methods on the primary interface as
        # callable methods
        if interface == self.interface:
            setattr(self.__class__, name, dbus_method)

        self.methods.setdefault(interface, {})[str(name)] = (in_sig, out_sig, code, dbus_method)

    @dbus.service.method(MOCK_IFACE, in_signature="sa(ssss)", out_signature="")
    def AddMethods(self, 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.
        """
        for method in methods:
            self.AddMethod(interface, *method)

    def _set_property(self, interface, name, value):
        # copy.copy removes one level of variant-ness, which means that the
        # types get exported in introspection data correctly, but we can't do
        # this for container types.
        if not isinstance(value, (dbus.Dictionary, dbus.Array)):
            value = copy.copy(value)

        self.props.setdefault(interface, {})[name] = value

    @dbus.service.method(MOCK_IFACE, in_signature="sa{sv}", out_signature="")
    def UpdateProperties(self, 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
        """
        changed_props = {}

        for name, value in properties.items():
            if not interface:
                interface = self.interface
            if name not in self.props.get(interface, {}):
                raise dbus.exceptions.DBusException(f"property {name} not found", name=interface + ".NoSuchProperty")

            self._set_property(interface, name, value)
            changed_props[name] = _wrap_in_dbus_variant(value)

        self.EmitSignal(dbus.PROPERTIES_IFACE, "PropertiesChanged", "sa{sv}as", [interface, changed_props, []])

    @dbus.service.method(MOCK_IFACE, in_signature="ssv", out_signature="")
    def AddProperty(self, 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.
        """
        if not interface:
            interface = self.interface
        if name in self.props.get(interface, {}):
            raise dbus.exceptions.DBusException(
                f"property {name} already exists", name=self.interface + ".PropertyExists"
            )

        self._set_property(interface, name, value)

    @dbus.service.method(MOCK_IFACE, in_signature="sa{sv}", out_signature="")
    def AddProperties(self, 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
        """
        for k, v in properties.items():
            self.AddProperty(interface, k, v)

    @dbus.service.method(MOCK_IFACE, in_signature="sa{sv}", out_signature="")
    def AddTemplate(self, 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.
        """
        try:
            module = load_module(template)
        except ImportError as e:
            raise dbus.exceptions.DBusException(
                f"Cannot add template {template}: {e!s}", name="org.freedesktop.DBus.Mock.TemplateError"
            ) from e

        # If the template specifies this is an ObjectManager, set that up
        if hasattr(module, "IS_OBJECT_MANAGER") and module.IS_OBJECT_MANAGER:
            self._set_up_object_manager()

        # pick out all D-Bus service methods and add them to our interface
        for symbol in dir(module):
            # pylint: disable=protected-access
            fn = getattr(module, symbol)
            if "_dbus_interface" in dir(fn) and ("_dbus_is_signal" not in dir(fn) or not fn._dbus_is_signal):
                fn = loggedmethod(self, fn)

                # for dbus-python compatibility, add methods as callables
                setattr(self.__class__, symbol, fn)
                self.methods.setdefault(fn._dbus_interface, {})[str(symbol)] = (
                    fn._dbus_in_signature,
                    fn._dbus_out_signature,
                    "",
                    fn,
                )

        if parameters is None:
            parameters = {}

        module.load(self, parameters)
        # save the given template and parameters for re-instantiation on
        # Reset()
        self._template = template
        self._template_parameters = parameters

    def _emit_signal(
        self, interface: str, name: str, signature: str, sigargs: Tuple[Any, ...], details: PropsType
    ) -> None:
        # pylint: disable=protected-access
        if not interface:
            interface = self.interface

        args = _convert_args(signature, sigargs)

        path = details.get("path", self.path)
        sig = dbus.lowlevel.SignalMessage(path, interface, name)
        sig.append(*args, signature=signature)
        dest = details.get("destination", None)
        if dest is not None:
            sig.set_destination(dest)

        for location in self.locations:
            conn = location[0]
            conn.send_message(sig)
        self.log(f"emit {path} {interface}.{name}{_format_args(args)}")

    @dbus.service.method(MOCK_IFACE, in_signature="sssav", out_signature="")
    def EmitSignal(self, interface: str, name: str, signature: str, sigargs: Tuple[Any, ...]) -> 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"
        """
        self._emit_signal(interface, name, signature, sigargs, {})

    @dbus.service.method(MOCK_IFACE, in_signature="sssava{sv}", out_signature="")
    def EmitSignalDetailed(
        self, interface: str, name: str, signature: str, sigargs: Tuple[Any, ...], 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
        """
        self._emit_signal(interface, name, signature, sigargs, details)

    @dbus.service.method(MOCK_IFACE, in_signature="", out_signature="a(tsav)")
    def GetCalls(self) -> List[CallLogType]:
        """List all the logged calls since the last call to ClearCalls().

        Return a list of (timestamp, method_name, args_list) tuples.
        """
        return self.call_log

    @dbus.service.method(MOCK_IFACE, in_signature="s", out_signature="a(tav)")
    def GetMethodCalls(self, method: str) -> List[Tuple[int, Sequence[Any]]]:
        """List all the logged calls of a particular method.

        Return a list of (timestamp, args_list) tuples.
        """
        return [(row[0], row[2]) for row in self.call_log if row[1] == method]

    @dbus.service.method(MOCK_IFACE, in_signature="", out_signature="")
    def ClearCalls(self) -> None:
        """Empty the log of mock call signatures."""

        self.call_log = []

    @dbus.service.signal(MOCK_IFACE, signature="sav")
    def MethodCalled(self, 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().
        """

    def object_manager_emit_added(self, path: str) -> None:
        """Emit ObjectManager.InterfacesAdded signal"""

        if self.object_manager is not None:
            self.object_manager.EmitSignal(
                OBJECT_MANAGER_IFACE, "InterfacesAdded", "oa{sa{sv}}", [dbus.ObjectPath(path), objects[path].props]
            )

    def object_manager_emit_removed(self, path: str) -> None:
        """Emit ObjectManager.InterfacesRemoved signal"""

        if self.object_manager is not None:
            self.object_manager.EmitSignal(
                OBJECT_MANAGER_IFACE, "InterfacesRemoved", "oas", [dbus.ObjectPath(path), objects[path].props]
            )

    def mock_method(self, 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.
        """
        # print('mock_method', dbus_method, self, in_signature, args, _, file=sys.stderr)

        try:
            args = _convert_args(in_signature, m_args)

            self.log(dbus_method + _format_args(args))
            self.call_log.append((int(time.time()), str(dbus_method), args))
            self.MethodCalled(dbus_method, args)

            # The code may be a Python 3 string to interpret, or may be a function
            # object (if AddMethod was called from within Python itself, rather than
            # over D-Bus).
            code = self.methods[interface][dbus_method][2]
            if code and isinstance(code, types.FunctionType):
                return code(self, *args)
            if code:
                loc = locals().copy()
                exec(code, globals(), loc)  # pylint: disable=exec-used
                if "ret" in loc:
                    return loc["ret"]
        except Exception as e:
            self.log(dbus_method + " raised: " + str(e))
            raise e

        return None

    def log(self, 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.
        """
        fd = self.logfile.fileno() if self.logfile else sys.stdout.fileno()

        os.write(fd, f"{time.time():.3f} {msg}\n".encode())

    @dbus.service.method(
        dbus.INTROSPECTABLE_IFACE,
        in_signature="",
        out_signature="s",
        path_keyword="object_path",
        connection_keyword="connection",
    )
    def Introspect(self, 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.
        """
        # _dbus_class_table is an indirect private member of dbus.service.Object that pylint fails to see
        # pylint: disable=no-member

        # temporarily add our dynamic methods
        cls = self.__class__.__module__ + "." + self.__class__.__name__
        orig_interfaces = self._dbus_class_table[cls]

        mock_interfaces = orig_interfaces.copy()
        for iface, methods in self.methods.items():
            for method, impl in methods.items():
                mock_interfaces.setdefault(iface, {})[method] = impl[3]
        self._dbus_class_table[cls] = mock_interfaces

        xml = dbus.service.Object.Introspect(self, object_path, connection)

        tree = ET.fromstring(xml)

        for name, name_props in self.props.items():
            # We might have properties for new interfaces we don't know about
            # yet. Try to find an existing <interface> node named after our
            # interface to append to, and create one if we can't.
            interface = tree.find(f".//interface[@name='{name}']")
            if interface is None:
                interface = ET.Element("interface", {"name": name})
                tree.append(interface)

            for prop, val in name_props.items():
                if val is None:
                    # can't guess type from None, skip
                    continue
                elem = ET.Element(
                    "property",
                    {
                        "name": prop,
                        # We don't store the signature anywhere, so guess it.
                        "type": dbus.lowlevel.Message.guess_signature(val),
                        "access": "readwrite",
                    },
                )

                interface.append(elem)

        xml = ET.tostring(tree, encoding="utf8", method="xml").decode("utf8")

        # restore original class table
        self._dbus_class_table[cls] = orig_interfaces

        return xml


# Overwrite dbus-python's _method_lookup(), as that offers no way to have the
# same method name on different interfaces
orig_method_lookup = dbus.service._method_lookup  # pylint: disable=protected-access


def _dbusmock_method_lookup(obj, method_name, dbus_interface):
    try:
        m = obj.methods[dbus_interface or obj.interface][method_name]
        return (m[3], m[3])
    except KeyError:
        return orig_method_lookup(obj, method_name, dbus_interface)


dbus.service._method_lookup = _dbusmock_method_lookup  # pylint: disable=protected-access


#
# Helper API for templates
#


def get_objects() -> KeysView[str]:
    """Return all existing object paths"""

    return objects.keys()


def get_object(path) -> DBusMockObject:
    """Return object for a given object path"""

    return objects[path]