Debian Codegraph @

PKG-INFO

raw
1 Metadata-Version: 2.4
2 Name: python-dbusmock
3 Version: 0.38.1
4 Summary: Mock D-Bus objects
5 Author-email: Martin Pitt <[email protected]>
6 License: GNU LESSER GENERAL PUBLIC LICENSE
7 Version 3, 29 June 2007
8
9 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
10 Everyone is permitted to copy and distribute verbatim copies
11 of this license document, but changing it is not allowed.
12
13
14 This version of the GNU Lesser General Public License incorporates
15 the terms and conditions of version 3 of the GNU General Public
16 License, supplemented by the additional permissions listed below.
17
18 0. Additional Definitions.
19
20 As used herein, "this License" refers to version 3 of the GNU Lesser
21 General Public License, and the "GNU GPL" refers to version 3 of the GNU
22 General Public License.
23
24 "The Library" refers to a covered work governed by this License,
25 other than an Application or a Combined Work as defined below.
26
27 An "Application" is any work that makes use of an interface provided
28 by the Library, but which is not otherwise based on the Library.
29 Defining a subclass of a class defined by the Library is deemed a mode
30 of using an interface provided by the Library.
31
32 A "Combined Work" is a work produced by combining or linking an
33 Application with the Library. The particular version of the Library
34 with which the Combined Work was made is also called the "Linked
35 Version".
36
37 The "Minimal Corresponding Source" for a Combined Work means the
38 Corresponding Source for the Combined Work, excluding any source code
39 for portions of the Combined Work that, considered in isolation, are
40 based on the Application, and not on the Linked Version.
41
42 The "Corresponding Application Code" for a Combined Work means the
43 object code and/or source code for the Application, including any data
44 and utility programs needed for reproducing the Combined Work from the
45 Application, but excluding the System Libraries of the Combined Work.
46
47 1. Exception to Section 3 of the GNU GPL.
48
49 You may convey a covered work under sections 3 and 4 of this License
50 without being bound by section 3 of the GNU GPL.
51
52 2. Conveying Modified Versions.
53
54 If you modify a copy of the Library, and, in your modifications, a
55 facility refers to a function or data to be supplied by an Application
56 that uses the facility (other than as an argument passed when the
57 facility is invoked), then you may convey a copy of the modified
58 version:
59
60 a) under this License, provided that you make a good faith effort to
61 ensure that, in the event an Application does not supply the
62 function or data, the facility still operates, and performs
63 whatever part of its purpose remains meaningful, or
64
65 b) under the GNU GPL, with none of the additional permissions of
66 this License applicable to that copy.
67
68 3. Object Code Incorporating Material from Library Header Files.
69
70 The object code form of an Application may incorporate material from
71 a header file that is part of the Library. You may convey such object
72 code under terms of your choice, provided that, if the incorporated
73 material is not limited to numerical parameters, data structure
74 layouts and accessors, or small macros, inline functions and templates
75 (ten or fewer lines in length), you do both of the following:
76
77 a) Give prominent notice with each copy of the object code that the
78 Library is used in it and that the Library and its use are
79 covered by this License.
80
81 b) Accompany the object code with a copy of the GNU GPL and this license
82 document.
83
84 4. Combined Works.
85
86 You may convey a Combined Work under terms of your choice that,
87 taken together, effectively do not restrict modification of the
88 portions of the Library contained in the Combined Work and reverse
89 engineering for debugging such modifications, if you also do each of
90 the following:
91
92 a) Give prominent notice with each copy of the Combined Work that
93 the Library is used in it and that the Library and its use are
94 covered by this License.
95
96 b) Accompany the Combined Work with a copy of the GNU GPL and this license
97 document.
98
99 c) For a Combined Work that displays copyright notices during
100 execution, include the copyright notice for the Library among
101 these notices, as well as a reference directing the user to the
102 copies of the GNU GPL and this license document.
103
104 d) Do one of the following:
105
106 0) Convey the Minimal Corresponding Source under the terms of this
107 License, and the Corresponding Application Code in a form
108 suitable for, and under terms that permit, the user to
109 recombine or relink the Application with a modified version of
110 the Linked Version to produce a modified Combined Work, in the
111 manner specified by section 6 of the GNU GPL for conveying
112 Corresponding Source.
113
114 1) Use a suitable shared library mechanism for linking with the
115 Library. A suitable mechanism is one that (a) uses at run time
116 a copy of the Library already present on the user's computer
117 system, and (b) will operate properly with a modified version
118 of the Library that is interface-compatible with the Linked
119 Version.
120
121 e) Provide Installation Information, but only if you would otherwise
122 be required to provide such information under section 6 of the
123 GNU GPL, and only to the extent that such information is
124 necessary to install and execute a modified version of the
125 Combined Work produced by recombining or relinking the
126 Application with a modified version of the Linked Version. (If
127 you use option 4d0, the Installation Information must accompany
128 the Minimal Corresponding Source and Corresponding Application
129 Code. If you use option 4d1, you must provide the Installation
130 Information in the manner specified by section 6 of the GNU GPL
131 for conveying Corresponding Source.)
132
133 5. Combined Libraries.
134
135 You may place library facilities that are a work based on the
136 Library side by side in a single library together with other library
137 facilities that are not Applications and are not covered by this
138 License, and convey such a combined library under terms of your
139 choice, if you do both of the following:
140
141 a) Accompany the combined library with a copy of the same work based
142 on the Library, uncombined with any other library facilities,
143 conveyed under the terms of this License.
144
145 b) Give prominent notice with the combined library that part of it
146 is a work based on the Library, and explaining where to find the
147 accompanying uncombined form of the same work.
148
149 6. Revised Versions of the GNU Lesser General Public License.
150
151 The Free Software Foundation may publish revised and/or new versions
152 of the GNU Lesser General Public License from time to time. Such new
153 versions will be similar in spirit to the present version, but may
154 differ in detail to address new problems or concerns.
155
156 Each version is given a distinguishing version number. If the
157 Library as you received it specifies that a certain numbered version
158 of the GNU Lesser General Public License "or any later version"
159 applies to it, you have the option of following the terms and
160 conditions either of that published version or of any later version
161 published by the Free Software Foundation. If the Library as you
162 received it does not specify a version number of the GNU Lesser
163 General Public License, you may choose any version of the GNU Lesser
164 General Public License ever published by the Free Software Foundation.
165
166 If the Library as you received it specifies that a proxy can decide
167 whether future versions of the GNU Lesser General Public License shall
168 apply, that proxy's public statement of acceptance of any version is
169 permanent authorization for you to choose that version for the
170 Library.
171
172 Project-URL: homepage, https://github.com/martinpitt/python-dbusmock
173 Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)
174 Classifier: Programming Language :: Python :: 3
175 Classifier: Development Status :: 6 - Mature
176 Classifier: Operating System :: POSIX :: Linux
177 Classifier: Operating System :: POSIX :: BSD
178 Classifier: Operating System :: Unix
179 Classifier: Topic :: Software Development :: Quality Assurance
180 Classifier: Topic :: Software Development :: Testing
181 Classifier: Topic :: Software Development :: Testing :: Mocking
182 Classifier: Topic :: Software Development :: Testing :: Unit
183 Classifier: Topic :: Software Development :: Libraries :: Python Modules
184 Requires-Python: >=3.8
185 Description-Content-Type: text/markdown
186 License-File: COPYING
187 Requires-Dist: dbus-python
188 Dynamic: license-file
189
190 ![CI status](https://github.com/martinpitt/python-dbusmock/actions/workflows/tests.yml/badge.svg)
191
192 python-dbusmock
193 ===============
194
195 ## Purpose
196
197 With this program/Python library you can easily create mock objects on
198 D-Bus. This is useful for writing tests for software which talks to
199 D-Bus services such as upower, systemd, logind, gnome-session or others,
200 and it is hard (or impossible without root privileges) to set the state
201 of the real services to what you expect in your tests.
202
203 Suppose you want to write tests for a desktop environment's power management:
204 You want to verify that after the configured idle time the program suspends the
205 machine. So your program calls `org.freedesktop.login1.Manager.Suspend()` on
206 the system D-Bus.
207
208 Now, your test suite should not really talk to the actual system D-Bus and
209 the real systemd; a `make check` that suspends your machine will not be
210 considered very friendly by most people, and if you want to run this in
211 continuous integration test servers or package build environments, chances
212 are that your process does not have the privilege to suspend, or there is
213 no system bus or running systemd to begin with. Likewise, there is no way
214 for an user process to forcefully set the system/seat idle flag in logind,
215 so your tests cannot set up the expected test environment on the real
216 daemon.
217
218 That's where mock objects come into play: They look like the real API
219 (or at least the parts that you actually need), but they do not actually
220 do anything (or only some action that you specify yourself). You can
221 configure their state, behaviour and responses as you like in your test,
222 without making any assumptions about the real system status.
223
224 When using a local system/session bus, you can do unit or integration
225 testing without needing root privileges or disturbing a running system.
226 The Python API offers some convenience functions like
227 `start_session_bus()` and `start_system_bus()` for this, in a
228 `DBusTestCase` class (subclass of the standard `unittest.TestCase`) or
229 alternatively as a `@pytest.fixture`.
230
231 You can use this with any programming language, as you can run the
232 mocker as a normal program. The actual setup of the mock (adding
233 objects, methods, properties, and signals) all happen via D-Bus methods
234 on the `org.freedesktop.DBus.Mock` interface. You just don't have the
235 convenience D-Bus launch API that way.
236
237 ## Simple example using Python's unittest
238
239 Picking up the above example about mocking systemd-logind's `Suspend()`
240 method, this is how you would set up a mock logind in your test case:
241
242 ```python
243 import subprocess
244 import unittest
245
246 import dbus
247
248 import dbusmock
249
250
251 class TestMyProgram(dbusmock.DBusTestCase):
252 @classmethod
253 def setUpClass(cls):
254 cls.start_system_bus()
255 cls.dbus_con = cls.get_dbus(system_bus=True)
256
257 def setUp(self):
258 self.p_mock = self.spawn_server('org.freedesktop.login1',
259 '/org/freedesktop/login1',
260 'org.freedesktop.login1.Manager',
261 system_bus=True,
262 stdout=subprocess.PIPE)
263 self.addCleanup(self.p_mock.wait)
264 self.addCleanup(self.p_mock.terminate)
265 self.addCleanup(self.p_mock.stdout.close)
266
267 # Get a proxy for the logind object's Mock interface
268 self.dbus_logind_mock = dbus.Interface(self.dbus_con.get_object(
269 'org.freedesktop.login1', '/org/freedesktop/login1'),
270 dbusmock.MOCK_IFACE)
271
272 self.dbus_logind_mock.AddMethod('', 'Suspend', 'b', '', '')
273
274 def test_suspend_on_idle(self):
275 # run your program in a way that should trigger one suspend call
276 # represented here as direct D-Bus call
277 subprocess.check_call(
278 ["busctl", "call", "org.freedesktop.login1",
279 "/org/freedesktop/login1", "org.freedesktop.login1.Manager",
280 "Suspend", "b", "false"])
281
282 # now check the log that we got one Suspend() call
283 self.assertRegex(self.p_mock.stdout.readline(), b'^[0-9.]+ Suspend False$')
284 ```
285
286 Let's walk through:
287
288 - We derive our tests from `dbusmock.DBusTestCase` instead of
289 `unittest.TestCase` directly, to make use of the convenience API
290 to start a local system bus.
291
292 - `setUpClass()` starts a local system bus, and makes a connection
293 to it available to all methods as `dbus_con`. `True` means that we
294 connect to the system bus, not the session bus. We can use the
295 same bus for all tests, so doing this once in `setUpClass()`
296 instead of `setUp()` is enough.
297
298 - `setUp()` spawns the mock D-Bus server process for an initial
299 `/org/freedesktop/login1` object with an `org.freedesktop.login1`
300 D-Bus interface on the system bus. We capture its stdout to be
301 able to verify that methods were called.
302
303 We then call `org.freedesktop.DBus.Mock.AddMethod()` to add a
304 `Suspend()` method to our new object to the default D-Bus
305 interface. This will not do anything (except log its call to
306 stdout). It takes no input arguments, returns nothing, and does
307 not run any custom code.
308
309 We use `addCleanup()` to register cleanup handlers that will
310 stop our mock D-Bus server after each test. This ensures each
311 test case has a fresh and clean logind mock instance. Of course
312 you can also set up everything in `setUpClass()` if tests
313 do not interfere with each other on setting up the mock.
314
315 - `test_suspend_on_idle()` is the actual test case. It needs to run
316 your program in a way that should trigger one suspend call. For this
317 example this is represented by doing just a direct D-Bus call using
318 `busctl`.
319
320 That `Suspend()` call is now being served by our mock instead of the real
321 logind, there will not be any actual machine suspend. Our mock process
322 will log the method call together with a time stamp; you can use the
323 latter for doing timing related tests, but we just ignore it here.
324
325 ## Simple example using pytest
326
327 The same functionality as above but instead using the pytest fixture provided
328 by this package.
329
330 ```python
331 # Enable dbusmock's pytest fixtures (can also go in conftest.py)
332 pytest_plugins = "dbusmock.pytest_fixtures"
333
334 import subprocess
335
336 import dbus
337
338 import dbusmock
339
340
341 def test_suspend_on_idle(dbusmock_system):
342 # Spawn the mock D-Bus server for logind on the system bus
343 with dbusmock.SpawnedMock.spawn_for_name(
344 'org.freedesktop.login1',
345 '/org/freedesktop/login1',
346 'org.freedesktop.login1.Manager',
347 dbusmock.BusType.SYSTEM,
348 stdout=subprocess.PIPE) as p_mock:
349
350 # Get a proxy for the logind object's Mock interface
351 obj_logind = p_mock.obj
352 obj_logind.AddMethod('', 'Suspend', 'b', '', '', interface_name=dbusmock.MOCK_IFACE)
353
354 # Run your program in a way that should trigger one suspend call
355 # represented here as direct D-Bus call
356 subprocess.check_call(
357 ["busctl", "call", "org.freedesktop.login1",
358 "/org/freedesktop/login1", "org.freedesktop.login1.Manager",
359 "Suspend", "b", "false"])
360
361 # Check the log that we got one Suspend() call
362 assert b'Suspend False\n' in p_mock.stdout.readline()
363 ```
364
365 Let's walk through:
366
367 - We enable dbusmock's pytest fixtures with `pytest_plugins = "dbusmock.pytest_fixtures"`.
368 This makes fixtures like `dbusmock_system` and `dbusmock_session` available to your
369 tests. In a real project, you would typically put this line in your `conftest.py`
370 instead of in each test file.
371
372 - We import the `dbusmock_system` fixture from dbusmock which provides us
373 with a system bus started for our test case. Even though we don't use it
374 directly in this simple example, it ensures the test environment is set up.
375
376 - `test_suspend_on_idle()` is the actual test. It uses
377 `SpawnedMock.spawn_for_name()` to spawn the mock D-Bus server process for
378 `/org/freedesktop/login1` object with `org.freedesktop.login1.Manager`
379 interface. We capture its stdout to verify that methods were called.
380
381 We then call `org.freedesktop.DBus.Mock.AddMethod()` to add a `Suspend()`
382 method to our new logind mock object to the default D-Bus interface. This
383 will not do anything (except log its call to stdout). It takes one boolean
384 input argument, returns nothing, and does not run any custom code.
385
386 Exactly like in the unittest example above, we then run our program in a way that
387 should trigger one suspend call. For this example this is again represented
388 by doing just a direct D-Bus call using `busctl`. The log of the call gets
389 asserted.
390
391 The context manager automatically terminates the mock server process after
392 the test completes.
393
394 ## Simple example from shell
395
396 We use the actual session bus for this example. You can use
397 `dbus-run-session` to start a private one as well if you want, but that
398 is not part of the actual mocking.
399
400 So let's start a mock at the D-Bus name `com.example.Foo` with an
401 initial "main" object on path /, with the main D-Bus interface
402 `com.example.Foo.Manager`:
403
404 python3 -m dbusmock com.example.Foo / com.example.Foo.Manager
405
406 On another terminal, let's first see what it does:
407
408 gdbus introspect --session -d com.example.Foo -o /
409
410 You'll see that it supports the standard D-Bus `Introspectable` and
411 `Properties` interfaces, as well as the `org.freedesktop.DBus.Mock`
412 interface for controlling the mock, but no "real" functionality yet.
413 So let's add a method:
414
415 gdbus call --session -d com.example.Foo -o / -m org.freedesktop.DBus.Mock.AddMethod '' Ping '' '' ''
416
417 Now you can see the new method in `introspect`, and call it:
418
419 gdbus call --session -d com.example.Foo -o / -m com.example.Foo.Manager.Ping
420
421 The mock process in the other terminal will log the method call with a
422 time stamp, and you'll see something like `1348832614.970 Ping`.
423
424 Now add another method with two int arguments and a return value and
425 call it:
426
427 gdbus call --session -d com.example.Foo -o / -m org.freedesktop.DBus.Mock.AddMethod \
428 '' Add 'ii' 'i' 'ret = args[0] + args[1]'
429 gdbus call --session -d com.example.Foo -o / -m com.example.Foo.Manager.Add 2 3
430
431 This will print `(5,)` as expected (remember that the return value is
432 always a tuple), and again the mock process will log the Add method
433 call.
434
435 You can do the same operations in e. g. d-feet or any other D-Bus
436 language binding.
437
438 ## Interactive debugging
439
440 It's possible to use dbus-mock to run interactive sessions using something like:
441
442 python3 -m dbusmock com.example.Foo / com.example.Foo.Manager -e $SHELL
443
444 Where a shell session with the defined mocks is set and others can be added.
445
446 Or more complex ones such as:
447
448 python3 -m dbusmock --session -t upower -e \
449 python3 -m dbusmock com.example.Foo / com.example.Foo.Manager -e \
450 gdbus introspect --session -d com.example.Foo -o /
451
452 ## Logging
453
454 Usually you want to verify which methods have been called on the mock
455 with which arguments. There are three ways to do that:
456
457 - By default, the mock process writes the call log to stdout.
458 - You can call the mock process with the `-l`/`--logfile` argument,
459 or specify a log file object in the `spawn_server()` method if you
460 are using Python.
461 - You can use the `GetCalls()`, `GetMethodCalls()` and
462 `ClearCalls()` methods on the `org.freedesktop.DBus.Mock` D-Bus
463 interface to get an array of tuples describing the calls.
464
465 ## Templates
466
467 Some D-Bus services are commonly used in test suites, such as UPower or
468 NetworkManager. python-dbusmock provides "templates" which set up the
469 common structure of these services (their main objects, properties, and
470 methods) so that you do not need to carry around this common code, and
471 only need to set up the particular properties and specific D-Bus objects
472 that you need. These templates can be parameterized for common
473 customizations, and they can provide additional convenience methods on
474 the `org.freedesktop.DBus.Mock` interface to provide more abstract
475 functionality like "add a battery".
476
477 For example, for starting a server with the `upower` template in
478 Python you can run
479
480 (self.p_mock, self.obj_upower) = self.spawn_server_template(
481 'upower', {'OnBattery': True}, stdout=subprocess.PIPE)
482
483 or load a template into an already running server with the
484 `AddTemplate()` method; this is particularly useful if you are not using
485 Python:
486
487 python3 -m dbusmock --system org.freedesktop.UPower /org/freedesktop/UPower org.freedesktop.UPower
488
489 gdbus call --system -d org.freedesktop.UPower -o /org/freedesktop/UPower -m org.freedesktop.DBus.Mock.AddTemplate 'upower' '{"OnBattery": <true>}'
490
491 This creates all expected properties such as `DaemonVersion`, and
492 changes the default for one of them (`OnBattery`) through the (optional)
493 parameters dict.
494
495 If you do not need to specify parameters, you can do this in a simpler
496 way with
497
498 python3 -m dbusmock --template upower
499
500 The template does not create any devices by default. You can add some
501 with the template's convenience methods like
502
503 ac_path = self.dbusmock.AddAC('mock_AC', 'Mock AC')
504 bt_path = self.dbusmock.AddChargingBattery('mock_BAT', 'Mock Battery', 30.0, 1200)
505
506 or calling `AddObject()` yourself with the desired properties, of
507 course.
508
509 Templates commonly implement some non-trivial functionality with actual Python
510 methods and the standard [dbus-python](https://dbus.freedesktop.org/doc/dbus-python/)
511 [`@dbus.service.method`](https://dbus.freedesktop.org/doc/dbus-python/dbus.service.html#dbus.service.method)
512 decorator.
513
514 To build your own template, you can copy
515 [dbusmock/templates/SKELETON](./dbusmock/templates/SKELETON) to your
516 new template file name and replace `CHANGEME` with the actual code/values.
517 Look at [dbusmock/templates/upower.py](./dbusmock/templates/upower.py) for
518 a real-life implementation.
519
520 A template can be loaded from these locations:
521
522 * Provide a path to its `.py` file. This is intended for running tests out of
523 git/build trees with very project specific or unstable templates.
524
525 * From [`$XDG_DATA_DIRS/python-dbusmock/templates/`*name*`.py`](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html).
526 This is intended for shipping reusable templates in distribution development
527 packages. Load them by module name.
528
529 * python-dbusmock [ships a set of widely applicable templates](./dbusmock/templates/)
530 which are collaboratively maintained, like the `upower` one in the example
531 above. Load them by module name.
532
533 ## More Examples
534
535 Have a look at the test suite for two real-live use cases:
536
537 - `tests/test_upower.py` simulates upowerd, in a more complete way
538 than in above example and using the `upower` template. It verifies
539 that `upower --dump` is convinced that it's talking to upower.
540 - `tests/test_api.py` runs a mock on the session bus and exercises
541 all available functionality, such as adding additional objects,
542 properties, multiple methods, input arguments, return values, code
543 in methods, sending signals, raising exceptions, and introspection.
544
545 ## Documentation
546
547 The `dbusmock` module has extensive documentation built in, which you
548 can read with e. g. `pydoc3 dbusmock` or online at
549 https://martinpitt.github.io/python-dbusmock/
550
551 `pydoc3 dbusmock.DBusMockObject` shows the D-Bus API of the mock object,
552 i. e. methods like `AddObject()`, `AddMethod()` etc. which are used to
553 set up your mock object.
554
555 `pydoc3 dbusmock.DBusTestCase` shows the convenience Python API for
556 writing test cases with local private session/system buses and launching
557 the server.
558
559 `pydoc3 dbusmock.templates` shows all available templates.
560
561 `pydoc3 dbusmock.templates.NAME` shows the documentation and available
562 parameters for the `NAME` template.
563
564 `python3 -m dbusmock --help` shows the arguments and options for running
565 the mock server as a program.
566
567 ## Development
568
569 python-dbusmock is hosted on https://github.com/martinpitt/python-dbusmock
570
571 Run the unit tests with `python3 -m unittest` or `pytest`.
572
573 In CI, the unit tests run in containers. You can run them locally with e.g.
574
575 tests/run registry.fedoraproject.org/fedora:latest
576
577 Check the [unit-tests GitHub workflow](.github/workflows/tests.yml) for the
578 operating systems/container images on which python-dbusmock is tested and
579 supported.
580
581 To debug failures interactively, run
582
583 DEBUG=1 tests/run [image]
584
585 which will sleep on failures. You can then attach to the running container
586 image with e.g. `podman exec -itl bash`. The `/source` directory is mounted from the
587 host, i.e. edit files in your normal git checkout outside of the container, and
588 re-run all tests in the container shell like above. You can also run a specific
589 test:
590
591 python3 -m unittest tests.test_api.TestAPI.test_onearg_ret