Debian Codegraph @

tests/test_monitor.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2010, 2011, 2012, 2013 Sebastian Wiesner <[email protected]>
3
4 # This library is free software; you can redistribute it and/or modify it
5 # under the terms of the GNU Lesser General Public License as published by the
6 # Free Software Foundation; either version 2.1 of the License, or (at your
7 # option) any later version.
8
9 # This library is distributed in the hope that it will be useful, but WITHOUT
10 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
12 # for more details.
13
14 # You should have received a copy of the GNU Lesser General Public License
15 # along with this library; if not, write to the Free Software Foundation,
16 # Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
17
18 # isort: STDLIB
19 import random
20 from contextlib import contextmanager
21 from datetime import datetime, timedelta
22 from select import select
23
24 # isort: THIRDPARTY
25 import pytest
26
27 # isort: FIRSTPARTY
28 from tests._constants import _UDEV_TEST
29 from tests.utils.udev import DeviceDatabase
30
31 # isort: LOCAL
32 from pyudev import Devices, Monitor, MonitorObserver
33
34 try:
35 # isort: STDLIB
36 from unittest import mock
37 except ImportError:
38 # isort: THIRDPARTY
39 import mock
40
41
42 # many tests just consist of some monkey patching to test, that the Monitor
43 # class actually calls out to udev, correctly passing arguments and handling
44 # return value. Actual udev calls are difficult to test, as return values
45 # and side effects are dynamic and environment-dependent. It isn't
46 # necessary anyway, libudev can just assumed to be correct.
47
48
49 @pytest.fixture
50 def monitor(request):
51 return Monitor.from_netlink(request.getfixturevalue("context"))
52
53
54 @pytest.fixture
55 def fake_monitor_device(request):
56 context = request.getfixturevalue("context")
57 device = random.choice(list(DeviceDatabase.db()))
58 return Devices.from_path(context, device.device_path)
59
60
61 @contextmanager
62 def patch_filter_by(type):
63 add_match = "udev_monitor_filter_add_match_{0}".format(type)
64 filter_update = "udev_monitor_filter_update"
65 with pytest.patch_libudev(add_match) as add_match:
66 add_match.return_value = 0
67 with pytest.patch_libudev(filter_update) as filter_update:
68 filter_update.return_value = 0
69 yield add_match, filter_update
70
71
72 class TestMonitor:
73 def test_from_netlink_invalid_source(self, context):
74 with pytest.raises(ValueError) as exc_info:
75 Monitor.from_netlink(context, source="invalid_source")
76 message = 'Invalid source: {0!r}. Must be one of "udev" ' 'or "kernel"'.format(
77 "invalid_source"
78 )
79 assert str(exc_info.value) == message
80
81 def test_from_netlink_source_udev(self, context):
82 monitor = Monitor.from_netlink(context)
83 assert monitor._as_parameter_
84 assert not monitor.started
85 monitor = Monitor.from_netlink(context, source="udev")
86 assert monitor._as_parameter_
87 assert not monitor.started
88
89 def test_from_netlink_source_udev_mock(self, context):
90 funcname = "udev_monitor_new_from_netlink"
91 spec = lambda c, s: None
92 with mock.patch.object(context._libudev, funcname, autospec=spec) as func:
93 func.return_value = mock.sentinel.monitor
94 monitor = Monitor.from_netlink(context)
95 assert monitor._as_parameter_ is mock.sentinel.monitor
96 assert not monitor.started
97 func.assert_called_once_with(context, b"udev")
98 func.reset_mock()
99 monitor = Monitor.from_netlink(context, "udev")
100 assert monitor._as_parameter_ is mock.sentinel.monitor
101 assert not monitor.started
102 func.assert_called_once_with(context, b"udev")
103
104 def test_from_netlink_source_kernel(self, context):
105 monitor = Monitor.from_netlink(context, source="kernel")
106 assert monitor._as_parameter_
107 assert not monitor.started
108
109 def test_from_netlink_source_kernel_mock(self, context):
110 funcname = "udev_monitor_new_from_netlink"
111 spec = lambda c, s: None
112 with mock.patch.object(context._libudev, funcname, autospec=spec) as func:
113 func.return_value = mock.sentinel.monitor
114 monitor = Monitor.from_netlink(context, "kernel")
115 assert monitor._as_parameter_ is mock.sentinel.monitor
116 assert not monitor.started
117 func.assert_called_once_with(context, b"kernel")
118
119 def test_fileno(self, monitor):
120 # we can't do more than check that no exception is thrown
121 monitor.fileno()
122
123 def test_fileno_mock(self, monitor):
124 funcname = "udev_monitor_get_fd"
125 spec = lambda m: None
126 with mock.patch.object(monitor._libudev, funcname, autospec=spec) as func:
127 func.return_value = mock.sentinel.fileno
128 assert monitor.fileno() is mock.sentinel.fileno
129 func.assert_called_once_with(monitor)
130
131 def test_filter_by_no_subsystem(self, monitor):
132 with pytest.raises(AttributeError):
133 monitor.filter_by(None)
134
135 def test_filter_by_subsystem_no_dev_type(self, monitor):
136 monitor.filter_by(b"input")
137 monitor.filter_by("input")
138
139 def test_filter_by_subsystem_no_dev_type_mock(self, monitor):
140 funcname = "udev_monitor_filter_add_match_subsystem_devtype"
141 spec = lambda m, s, t: None
142 libudev = monitor._libudev
143 with mock.patch.object(libudev, funcname, autospec=spec) as match:
144 funcname = "udev_monitor_filter_update"
145 spec = lambda m: None
146 with mock.patch.object(libudev, funcname, autospec=spec) as update:
147 monitor.filter_by("input")
148 match.assert_called_once_with(monitor, b"input", None)
149 update.assert_called_once_with(monitor)
150
151 def test_filter_by_subsystem_dev_type(self, monitor):
152 monitor.filter_by("input", b"usb_interface")
153 monitor.filter_by("input", "usb_interface")
154
155 def test_filter_by_subsystem_dev_type_mock(self, monitor):
156 funcname = "udev_monitor_filter_add_match_subsystem_devtype"
157 spec = lambda m, s, t: None
158 libudev = monitor._libudev
159 with mock.patch.object(libudev, funcname, autospec=spec) as match:
160 funcname = "udev_monitor_filter_update"
161 spec = lambda m: None
162 with mock.patch.object(libudev, funcname, autospec=spec) as update:
163 monitor.filter_by("input", "usb_interface")
164 match.assert_called_once_with(monitor, b"input", b"usb_interface")
165 update.assert_called_once_with(monitor)
166
167 @_UDEV_TEST(154, "test_filter_by_tag")
168 def test_filter_by_tag(self, monitor):
169 monitor.filter_by_tag("spam")
170
171 @_UDEV_TEST(154, "test_filter_by_tag")
172 def test_filter_by_tag_mock(self, monitor):
173 funcname = "udev_monitor_filter_add_match_tag"
174 spec = lambda m, t: None
175 libudev = monitor._libudev
176 with mock.patch.object(libudev, funcname, autospec=spec) as match:
177 funcname = "udev_monitor_filter_update"
178 spec = lambda m: None
179 with mock.patch.object(libudev, funcname, autospec=spec) as update:
180 monitor.filter_by_tag("eggs")
181 match.assert_called_once_with(monitor, b"eggs")
182 update.assert_called_once_with(monitor)
183
184 def test_remove_filter(self, monitor):
185 """
186 The underlying ``udev_monitor_filter_remove()`` is apparently broken.
187 It always causes ``EINVAL`` from ``setsockopt()``. In some version
188 it changed and it now raises FileNotFoundError.
189 """
190 with pytest.raises(Exception):
191 monitor.remove_filter()
192
193 def test_remove_filter_mock(self, monitor):
194 funcname = "udev_monitor_filter_remove"
195 libudev = monitor._libudev
196 spec = lambda m: None
197 with mock.patch.object(libudev, funcname, autospec=spec) as remove:
198 funcname = "udev_monitor_filter_update"
199 with mock.patch.object(libudev, funcname, autospec=spec) as update:
200 monitor.remove_filter()
201 remove.assert_called_once_with(monitor)
202 update.assert_called_once_with(monitor)
203
204 def test_start_netlink_kernel_source(self, context):
205 monitor = Monitor.from_netlink(context, source="kernel")
206 assert not monitor.started
207 monitor.start()
208 assert monitor.started
209
210 def test_start_mock(self, monitor):
211 funcname = "udev_monitor_enable_receiving"
212 spec = lambda m: None
213 with mock.patch.object(monitor._libudev, funcname, autospec=spec) as func:
214 assert not monitor.started
215 monitor.start()
216 assert monitor.started
217 monitor.start()
218 func.assert_called_once_with(monitor)
219
220 def test_enable_receiving(self, monitor):
221 """
222 Test that enable_receiving() is deprecated and calls out to start().
223 """
224 with mock.patch.object(monitor, "start") as start:
225 pytest.deprecated_call(monitor.enable_receiving)
226 assert start.called
227
228 def test_set_receive_buffer_size_mock(self, monitor):
229 funcname = "udev_monitor_set_receive_buffer_size"
230 spec = lambda m, s: None
231 with mock.patch.object(monitor._libudev, funcname, autospec=spec) as func:
232 monitor.set_receive_buffer_size(1000)
233 func.assert_called_once_with(monitor, 1000)
234
235 def test_poll_timeout(self, monitor):
236 assert monitor.poll(timeout=0) is None
237 now = datetime.now()
238 assert monitor.poll(timeout=1) is None
239 assert datetime.now() - now >= timedelta(seconds=1)
240
241 def test_receive_device(self, monitor):
242 """
243 Test that Monitor.receive_device is deprecated and calls out to
244 poll(), which in turn is tested by test_poll.
245 """
246 with mock.patch.object(monitor, "poll") as poll:
247 device = mock.Mock(name="device")
248 device.action = "spam"
249 poll.return_value = device
250 event = pytest.deprecated_call(monitor.receive_device)
251 assert event[0] == "spam"
252 assert event[1] is device
253
254
255 class TestMonitorObserver:
256 def callback(self, device):
257 self.events.append(device)
258 if len(self.events) >= 2:
259 self.observer.send_stop()
260
261 def event_handler(self, action, device):
262 self.events.append((action, device))
263 if len(self.events) >= 2:
264 self.observer.send_stop()
265
266 def make_observer(self, monitor, use_deprecated=False):
267 if use_deprecated:
268 if pytest.__version__ == "2.8.4":
269 self.observer = MonitorObserver(
270 monitor, event_handler=self.event_handler
271 )
272 else:
273 self.observer = pytest.deprecated_call(
274 MonitorObserver, monitor, event_handler=self.event_handler
275 )
276 else:
277 self.observer = MonitorObserver(monitor, callback=self.callback)
278 return self.observer
279
280 def setup_method(self):
281 self.events = []
282
283 def teardown_method(self):
284 self.events = None
285
286 def test_deprecated_handler(self, fake_monitor, fake_monitor_device):
287 observer = self.make_observer(fake_monitor, use_deprecated=True)
288 observer.start()
289 fake_monitor.trigger_event()
290 fake_monitor.trigger_event()
291 # wait a second for the tests to finish, and kill the observer if
292 # it is still alive then
293 observer.join(1)
294 if observer.is_alive():
295 observer.stop()
296 assert not observer.is_alive()
297 assert self.events == [(None, fake_monitor_device)] * 2
298
299 def test_fake(self, fake_monitor, fake_monitor_device):
300 observer = self.make_observer(fake_monitor)
301 observer.start()
302 fake_monitor.trigger_event()
303 fake_monitor.trigger_event()
304 # wait a second for the tests to finish
305 observer.join(1)
306 # forcibly quit the thread if it is still alive
307 if observer.is_alive():
308 observer.stop()
309 assert not observer.is_alive()
310 # check that we got two events
311 assert self.events == [fake_monitor_device] * 2