File: lib_dbus.py

package info (click to toggle)
dasbus 1.7-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 880 kB
  • sloc: python: 7,550; makefile: 101; sh: 4
file content (194 lines) | stat: -rw-r--r-- 5,271 bytes parent folder | download | duplicates (2)
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
#
# Copyright (C) 2022  Red Hat, Inc.  All rights reserved.
#
# This library 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 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301
# USA
#
import multiprocessing
import sys
import unittest

from abc import abstractmethod, ABCMeta
from contextlib import contextmanager
from threading import Thread

import gi
gi.require_version("Gio", "2.0")
gi.require_version("GLib", "2.0")
from gi.repository import GLib, Gio


def run_loop(timeout=3):
    """Run an event loop for the specified timeout.

    If any of the events fail or there are some pending
    events after the timeout, raise AssertionError.

    :param int timeout: a number of seconds
    """
    loop = GLib.MainLoop()

    def _kill_loop():
        loop.quit()
        return False

    GLib.timeout_add_seconds(timeout, _kill_loop)

    with catch_errors() as errors:
        loop.run()

    assert not errors, "The loop has failed!"
    assert not loop.get_context().pending()


@contextmanager
def catch_errors():
    """Catch exceptions raised in this context.

    :return: a list of exceptions
    """
    errors = []

    def _handle_error(*exc_info):
        errors.append(exc_info)
        sys.__excepthook__(*exc_info)

    try:
        sys.excepthook = _handle_error
        yield errors
    finally:
        sys.excepthook = sys.__excepthook__


class AbstractDBusTestCase(unittest.TestCase, metaclass=ABCMeta):
    """Test DBus support with a real DBus connection."""

    def setUp(self):
        """Set up the test."""
        self.maxDiff = None

        # Initialize the service and the clients.
        self.service = self._get_service()
        self.clients = []

        # Start a testing bus.
        self.bus = Gio.TestDBus()
        self.bus.up()

        # Create a connection to the testing bus.
        self.bus_address = self.bus.get_bus_address()
        self.message_bus = self._get_message_bus(
            self.bus_address
        )

    @abstractmethod
    def _get_service(self):
        """Get a service."""
        return None

    @classmethod
    @abstractmethod
    def _get_message_bus(cls, bus_address):
        """Get a testing message bus."""
        return None

    @classmethod
    def _get_service_proxy(cls, message_bus, **proxy_args):
        """Get a proxy of the example service."""
        return message_bus.get_proxy(
            "my.testing.Example",
            "/my/testing/Example",
            **proxy_args
        )

    def _add_client(self, callback, *args, **kwargs):
        """Add a client."""
        self.clients.append(callback)

    def _publish_service(self):
        """Publish the service on DBus."""
        self.message_bus.publish_object(
            "/my/testing/Example",
            self.service
        )
        self.message_bus.register_service(
            "my.testing.Example"
        )

    def _run_test(self):
        """Run a test."""
        self._publish_service()

        for client in self.clients:
            client.start()

        run_loop()

        for client in self.clients:
            client.join()

    def tearDown(self):
        """Tear down the test."""
        if self.message_bus:
            self.message_bus.disconnect()

        if self.bus:
            self.bus.down()


class DBusThreadedTestCase(AbstractDBusTestCase, metaclass=ABCMeta):
    """Test DBus support with a real DBus connection and threads."""

    def _add_client(self, callback, *args, **kwargs):
        """Add a client thread."""
        thread = Thread(
            target=callback,
            args=args,
            kwargs=kwargs,
            daemon=True,
        )
        super()._add_client(thread)


class DBusSpawnedTestCase(AbstractDBusTestCase, metaclass=ABCMeta):
    """Test DBus support with a real DBus connections and spawned processes."""

    def setUp(self):
        """Set up the test."""
        super().setUp()
        self.context = multiprocessing.get_context('spawn')

    def _add_client(self, callback, *args, **kwargs):
        """Add a client process."""
        process = self.context.Process(
            name=callback.__name__,
            target=callback,
            args=(self.bus_address, *args),
            kwargs=kwargs,
            daemon=True,
        )
        super()._add_client(process)

    def _run_test(self):
        """Run a test."""
        super()._run_test()

        # Check the exit codes of the clients.
        for client in self.clients:
            msg = "{} has finished with {}".format(
                client.name,
                client.exitcode
            )
            self.assertEqual(client.exitcode, 0, msg)