Package: python-dbusmock
python-dbusmockPurposeWith this program/Python library you can easily create mock objects on
D-Bus. This is useful for writing tests for software which talks to
D-Bus services such as upower, systemd, logind, gnome-session or others,
and it is hard (or impossible without root privileges) to set the state
of the real services to what you expect in your tests.Suppose you want to write tests for gnome-settings-daemon's power
plugin, or another program that talks to upower. You want to verify that
after the configured idle time the program suspends the machine. So your
program callsorg.freedesktop.UPower.Suspend()on the system D-Bus.Now, your test suite should not really talk to the actual system D-Bus
and the real upower; amake checkthat suspends your machine will not
be considered very friendly by most people, and if you want to run this
in continuous integration test servers or package build environments,
chances are that your process does not have the privilege to suspend, or
there is no system bus or upower to begin with. Likewise, there is no
way for an user process to forcefully set the system/seat idle flag in
logind, so your tests cannot set up the expected test environment on the
real daemon.That's where mock objects come into play: They look like the real API
(or at least the parts that you actually need), but they do not actually
do anything (or only some action that you specify yourself). You can
configure their state, behaviour and responses as you like in your test,
without making any assumptions about the real system status.When using a local system/session bus, you can do unit or integration
testing without needing root privileges or disturbing a running system.
The Python API offers some convenience functions likestart_session_bus()andstart_system_bus()for this, in aDBusTestCaseclass (subclass of the standardunittest.TestCase) or
alternatively as a@pytest.fixture.You can use this with any programming language, as you can run the
mocker as a normal program. The actual setup of the mock (adding
objects, methods, properties, and signals) all happen via D-Bus methods
on theorg.freedesktop.DBus.Mockinterface. You just don't have the
convenience D-Bus launch API that way.Simple example using Python's unittestPicking up the above example about mocking upower'sSuspend()method,
this is how you would set up a mock upower in your test case:importsubprocessimportdbusimportdbusmockclassTestMyProgram(dbusmock.DBusTestCase):@classmethoddefsetUpClass(cls):cls.start_system_bus()cls.dbus_con=cls.get_dbus(system_bus=True)defsetUp(self):self.p_mock=self.spawn_server('org.freedesktop.UPower','/org/freedesktop/UPower','org.freedesktop.UPower',system_bus=True,stdout=subprocess.PIPE)# Get a proxy for the UPower object's Mock interfaceself.dbus_upower_mock=dbus.Interface(self.dbus_con.get_object('org.freedesktop.UPower','/org/freedesktop/UPower'),dbusmock.MOCK_IFACE)self.dbus_upower_mock.AddMethod('','Suspend','','','')deftearDown(self):self.p_mock.stdout.close()self.p_mock.terminate()self.p_mock.wait()deftest_suspend_on_idle(self):# run your program in a way that should trigger one suspend call# now check the log that we got one Suspend() callself.assertRegex(self.p_mock.stdout.readline(),b'^[0-9.]+ Suspend$')Let's walk through:We derive our tests fromdbusmock.DBusTestCaseinstead ofunittest.TestCasedirectly, to make use of the convenience API
to start a local system bus.setUpClass()starts a local system bus, and makes a connection
to it available to all methods asdbus_con.Truemeans that we
connect to the system bus, not the session bus. We can use the
same bus for all tests, so doing this once insetUpClass()instead ofsetUp()is enough.setUp()spawns the mock D-Bus server process for an initial/org/freedesktop/UPowerobject with anorg.freedesktop.UPowerD-Bus interface on the system bus. We capture its stdout to be
able to verify that methods were called.We then callorg.freedesktop.DBus.Mock.AddMethod()to add aSuspend()method to our new object to the default D-Bus
interface. This will not do anything (except log its call to
stdout). It takes no input arguments, returns nothing, and does
not run any custom code.tearDown()stops our mock D-Bus server again. We do this so that
each test case has a fresh and clean upower instance, but of
course you can also set up everything insetUpClass()if tests
do not interfere with each other on setting up the mock.test_suspend_on_idle()is the actual test case. It needs to run
your program in a way that should trigger one suspend call. Your
program will try to callSuspend(), but as that's now being
served by our mock instead of upower, there will not be any actual
machine suspend. Our mock process will log the method call
together with a time stamp; you can use the latter for doing
timing related tests, but we just ignore it here.Simple example using pytestThe same functionality as above but instead using the pytest fixture provided
by this package.importsubprocessimportdbusimportpytestimportdbusmock@pytest.fixturedefupower_mock(dbusmock_system):p_mock=dbusmock_system.spawn_server('org.freedesktop.UPower','/org/freedesktop/UPower','org.freedesktop.UPower',system_bus=True,stdout=subprocess.PIPE)# Get a proxy for the UPower object's Mock interfacedbus_upower_mock=dbus.Interface(dbusmock_system.get_dbus(True).get_object('org.freedesktop.UPower','/org/freedesktop/UPower'),dbusmock.MOCK_IFACE)dbus_upower_mock.AddMethod('','Suspend','','','')yieldp_mockp_mock.stdout.close()p_mock.terminate()p_mock.wait()deftest_suspend_on_idle(upower_mock):# run your program in a way that should trigger one suspend call# now check the log that we got one Suspend() callassertupower_mock.stdout.readline()==b'^[0-9.]+ Suspend$'Let's walk through:We import thedbusmock_systemfixture from dbusmock which provides us
with a system bus started for our test case wherever thedbusmock_systemargument is used by a test case and/or a pytest
fixture.Theupower_mockfixture spawns the mock D-Bus server process for an initial/org/freedesktop/UPowerobject with anorg.freedesktop.UPowerD-Bus interface on the system bus. We capture its stdout to be
able to verify that methods were called.We then callorg.freedesktop.DBus.Mock.AddMethod()to add aSuspend()method to our new object to the default D-Bus
interface. This will not do anything (except log its call to
stdout). It takes no input arguments, returns nothing, and does
not run any custom code.This mock server process is yielded to the test function that uses
theupower_mockfixture - once the test is complete the process is
terminated again.test_suspend_on_idle()is the actual test case. It needs to run
your program in a way that should trigger one suspend call. Your
program will try to callSuspend(), but as that's now being
served by our mock instead of upower, there will not be any actual
machine suspend. Our mock process will log the method call
together with a time stamp; you can use the latter for doing
timing related tests, but we just ignore it here.Simple example from shellWe use the actual session bus for this example. You can usedbus-run-sessionto start a private one as well if you want, but that
is not part of the actual mocking.So let's start a mock at the D-Bus namecom.example.Foowith an
initial "main" object on path /, with the main D-Bus interfacecom.example.Foo.Manager:python3 -m dbusmock com.example.Foo / com.example.Foo.ManagerOn another terminal, let's first see what it does:gdbus introspect --session -d com.example.Foo -o /You'll see that it supports the standard D-BusIntrospectableandPropertiesinterfaces, as well as theorg.freedesktop.DBus.Mockinterface for controlling the mock, but no "real" functionality yet.
So let's add a method:gdbus call --session -d com.example.Foo -o / -m org.freedesktop.DBus.Mock.AddMethod '' Ping '' '' ''Now you can see the new method inintrospect, and call it:gdbus call --session -d com.example.Foo -o / -m com.example.Foo.Manager.PingThe mock process in the other terminal will log the method call with a
time stamp, and you'll see something like1348832614.970 Ping.Now add another method with two int arguments and a return value and
call it:gdbus call --session -d com.example.Foo -o / -m org.freedesktop.DBus.Mock.AddMethod \
    '' Add 'ii' 'i' 'ret = args[0] + args[1]'
gdbus call --session -d com.example.Foo -o / -m com.example.Foo.Manager.Add 2 3This will print(5,)as expected (remember that the return value is
always a tuple), and again the mock process will log the Add method
call.You can do the same operations in e. g. d-feet or any other D-Bus
language binding.Interactive debuggingIt's possible to use dbus-mock to run interactive sessions using something like:python3 -m dbusmock com.example.Foo / com.example.Foo.Manager -e $SHELLWhere a shell session with the defined mocks is set and others can be added.Or more complex ones such as:python3 -m dbusmock --session -t upower -e \
  python3 -m dbusmock com.example.Foo / com.example.Foo.Manager -e \
    gdbus introspect --session -d com.example.Foo -o /LoggingUsually you want to verify which methods have been called on the mock
with which arguments. There are three ways to do that:By default, the mock process writes the call log to stdout.You can call the mock process with the-l/--logfileargument,
or specify a log file object in thespawn_server()method if you
are using Python.You can use theGetCalls(),GetMethodCalls()andClearCalls()methods on theorg.freedesktop.DBus.MockD-Bus
interface to get an array of tuples describing the calls.TemplatesSome D-Bus services are commonly used in test suites, such as UPower or
NetworkManager. python-dbusmock provides "templates" which set up the
common structure of these services (their main objects, properties, and
methods) so that you do not need to carry around this common code, and
only need to set up the particular properties and specific D-Bus objects
that you need. These templates can be parameterized for common
customizations, and they can provide additional convenience methods on
theorg.freedesktop.DBus.Mockinterface to provide more abstract
functionality like "add a battery".For example, for starting a server with theupowertemplate in
Python you can run(self.p_mock, self.obj_upower) = self.spawn_server_template(
    'upower', {'OnBattery': True}, stdout=subprocess.PIPE)or load a template into an already running server with theAddTemplate()method; this is particularly useful if you are not using
Python:python3 -m dbusmock --system org.freedesktop.UPower /org/freedesktop/UPower org.freedesktop.UPower

gdbus call --system -d org.freedesktop.UPower -o /org/freedesktop/UPower -m org.freedesktop.DBus.Mock.AddTemplate 'upower' '{"OnBattery": <true>}'This creates all expected properties such asDaemonVersion, and
changes the default for one of them (OnBattery) through the (optional)
parameters dict.If you do not need to specify parameters, you can do this in a simpler
way withpython3 -m dbusmock --template upowerThe template does not create any devices by default. You can add some
with the template's convenience methods likeac_path = self.dbusmock.AddAC('mock_AC', 'Mock AC')
bt_path = self.dbusmock.AddChargingBattery('mock_BAT', 'Mock Battery', 30.0, 1200)or callingAddObject()yourself with the desired properties, of
course.Templates commonly implement some non-trivial functionality with actual Python
methods and the standarddbus-python@dbus.service.methoddecorator.To build your own template, you can copydbusmock/templates/SKELETONto your
new template file name and replaceCHANGEMEwith the actual code/values.
Look atdbusmock/templates/upower.pyfor
a real-life implementation.A template can be loaded from these locations:Provide a path to its.pyfile. This is intended for running tests out of
git/build trees with very project specific or unstable templates.From$XDG_DATA_DIRS/python-dbusmock/templates/name.py.
This is intended for shipping reusable templates in distribution development
packages. Load them by module name.python-dbusmockships a set of widely applicable templateswhich are collaboratively maintained, like theupowerone in the example
above. Load them by module name.More ExamplesHave a look at the test suite for two real-live use cases:tests/test_upower.pysimulates upowerd, in a more complete way
than in above example and using theupowertemplate. It verifies
thatupower --dumpis convinced that it's talking to upower.tests/test_api.pyruns a mock on the session bus and exercises
all available functionality, such as adding additional objects,
properties, multiple methods, input arguments, return values, code
in methods, sending signals, raising exceptions, and introspection.DocumentationThedbusmockmodule has extensive documentation built in, which you
can read with e. g.pydoc3 dbusmockor online athttps://martinpitt.github.io/python-dbusmock/pydoc3 dbusmock.DBusMockObjectshows the D-Bus API of the mock object,
i. e. methods likeAddObject(),AddMethod()etc. which are used to
set up your mock object.pydoc3 dbusmock.DBusTestCaseshows the convenience Python API for
writing test cases with local private session/system buses and launching
the server.pydoc3 dbusmock.templatesshows all available templates.pydoc3 dbusmock.templates.NAMEshows the documentation and available
parameters for theNAMEtemplate.python3 -m dbusmock --helpshows the arguments and options for running
the mock server as a program.Developmentpython-dbusmock is hosted onhttps://github.com/martinpitt/python-dbusmockRun the unit tests withpython3 -m unittestorpytest.In CI, the unit tests run in containers. You can run them locally with e.g.tests/run registry.fedoraproject.org/fedora:latestCheck theunit-tests GitHub workflowfor the
operating systems/container images on which python-dbusmock is tested and
supported.To debug failures interactively, runDEBUG=1 tests/run [image]which will sleep on failures. You can then attach to the running container
image with e.g.podman exec -itl bash. The/sourcedirectory is mounted from the
host, i.e. edit files in your normal git checkout outside of the container, and
re-run all tests in the container shell like above. You can also run a specific
test:python3 -m unittest tests.test_api.TestAPI.test_onearg_ret