Debian Codegraph @

tests/_device_tests/_device_tests.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2010, 2011, 2012 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 Tests methods belonging to Device class.
19
20 .. moduleauthor:: mulhern <[email protected]>
21 """
22
23 # isort: STDLIB
24 import gc
25 import operator
26 import os
27 import re
28 from datetime import timedelta
29
30 # isort: THIRDPARTY
31 import pytest
32 from hypothesis import given, settings, strategies
33
34 # isort: LOCAL
35 from pyudev import Device, Devices
36 from pyudev.device import Attributes, Tags
37
38 from .._constants import _CONTEXT, _CONTEXT_STRATEGY, _DEVICE_DATA, _DEVICES, _UDEV_TEST
39 from ..utils import is_unicode_string
40
41 try:
42 # isort: STDLIB
43 from unittest import mock
44 except ImportError:
45 # isort: THIRDPARTY
46 import mock
47
48
49 class TestDevice:
50 """
51 Test ``Device`` methods.
52 """
53
54 @given(strategies.sampled_from(_DEVICES))
55 @settings(max_examples=5)
56 def test_parent(self, a_device):
57 assert a_device.parent is None or isinstance(a_device.parent, Device)
58
59 _devices = [d for d in _DEVICES if d.parent is not None]
60
61 @pytest.mark.skipif(len(_devices) == 0, reason="no device with a parent")
62 @_UDEV_TEST(172, "test_child_of_parents")
63 @given(strategies.sampled_from(_devices))
64 @settings(max_examples=5)
65 def test_child_of_parent(self, a_device):
66 assert a_device in a_device.parent.children
67
68 _devices = [d for d in _DEVICES if list(d.children)]
69
70 @pytest.mark.skipif(len(_devices) == 0, reason="no device with a child")
71 @_UDEV_TEST(172, "test_children")
72 @given(strategies.sampled_from(_devices))
73 @settings(max_examples=5)
74 def test_children(self, a_device):
75 children = list(a_device.children)
76 for child in children:
77 assert child != a_device
78 assert a_device in child.ancestors
79
80 @given(strategies.sampled_from(_DEVICES))
81 @settings(max_examples=5)
82 def test_ancestors(self, a_device):
83 child = a_device
84 for ancestor in a_device.ancestors:
85 assert ancestor == child.parent
86 child = ancestor
87
88 _devices = [d for d in _DEVICES if d.find_parent(d.subsystem) is not None]
89
90 @pytest.mark.skipif(
91 len(_devices) == 0, reason="no device with a parent in the same subsystem"
92 )
93 @given(strategies.sampled_from(_devices))
94 @settings(max_examples=5)
95 def test_find_parent(self, a_device):
96 parent = a_device.find_parent(a_device.subsystem)
97 assert parent.subsystem == a_device.subsystem
98 assert parent in a_device.ancestors
99
100 @given(strategies.sampled_from(_DEVICES))
101 @settings(max_examples=5)
102 def test_find_parent_no_devtype_mock(self, a_device):
103 funcname = "udev_device_get_parent_with_subsystem_devtype"
104 spec = lambda d, s, t: None
105 with mock.patch.object(
106 a_device._libudev, funcname, autospec=spec
107 ) as get_parent:
108 get_parent.return_value = mock.sentinel.parent_device
109 funcname = "udev_device_ref"
110 spec = lambda d: None
111 with mock.patch.object(
112 a_device._libudev, funcname, autospec=spec
113 ) as device_ref:
114 device_ref.return_value = mock.sentinel.referenced_device
115 parent = a_device.find_parent("subsystem")
116 assert isinstance(parent, Device)
117 assert parent._as_parameter_ is mock.sentinel.referenced_device
118 get_parent.assert_called_once_with(a_device, b"subsystem", None)
119 device_ref.assert_called_once_with(mock.sentinel.parent_device)
120
121 @given(strategies.sampled_from(_DEVICES))
122 @settings(max_examples=5)
123 def test_find_parent_with_devtype_mock(self, a_device):
124 funcname = "udev_device_get_parent_with_subsystem_devtype"
125 spec = lambda d, s, t: None
126 with mock.patch.object(
127 a_device._libudev, funcname, autospec=spec
128 ) as get_parent:
129 get_parent.return_value = mock.sentinel.parent_device
130 funcname = "udev_device_ref"
131 spec = lambda d: None
132 with mock.patch.object(
133 a_device._libudev, funcname, autospec=spec
134 ) as device_ref:
135 device_ref.return_value = mock.sentinel.referenced_device
136 parent = a_device.find_parent("subsystem", "devtype")
137 assert isinstance(parent, Device)
138 assert parent._as_parameter_ is mock.sentinel.referenced_device
139 get_parent.assert_called_once_with(a_device, b"subsystem", b"devtype")
140 device_ref.assert_called_once_with(mock.sentinel.parent_device)
141
142 @given(strategies.sampled_from(_DEVICES))
143 @settings(max_examples=5)
144 def test_traverse(self, a_device):
145 child = a_device
146 for parent in pytest.deprecated_call(a_device.traverse):
147 assert parent == child.parent
148 child = parent
149
150 @given(_CONTEXT_STRATEGY, strategies.sampled_from(_DEVICE_DATA))
151 @settings(max_examples=5)
152 def test_sys_path(self, a_context, device_datum):
153 device = Devices.from_path(a_context, device_datum.device_path)
154 assert device.sys_path == device_datum.sys_path
155 assert is_unicode_string(device.sys_path)
156
157 @given(_CONTEXT_STRATEGY, strategies.sampled_from(_DEVICE_DATA))
158 @settings(max_examples=5)
159 def test_device_path(self, a_context, device_datum):
160 device = Devices.from_path(a_context, device_datum.device_path)
161 assert device.device_path == device_datum.device_path
162 assert is_unicode_string(device.device_path)
163
164 @given(_CONTEXT_STRATEGY, strategies.sampled_from(_DEVICE_DATA))
165 @settings(max_examples=5)
166 def test_subsystem(self, a_context, device_datum):
167 device = Devices.from_path(a_context, device_datum.device_path)
168 assert device.subsystem == device_datum.properties["SUBSYSTEM"]
169 assert is_unicode_string(device.subsystem)
170
171 @given(strategies.sampled_from(_DEVICES))
172 @settings(max_examples=5)
173 def test_device_sys_name(self, a_device):
174 assert a_device.sys_name.replace("/", "!") == os.path.basename(
175 a_device.device_path
176 )
177 assert is_unicode_string(a_device.sys_name)
178
179 @given(strategies.sampled_from(_DEVICES))
180 @settings(max_examples=5)
181 def test_sys_number(self, a_device):
182 match = re.search(r"\d+$", a_device.sys_name)
183 # filter out devices with completely nummeric names (first character
184 # doesn't count according to the implementation of libudev)
185 if match and match.start() > 1:
186 assert a_device.sys_number == match.group(0)
187 assert is_unicode_string(a_device.sys_name)
188 else:
189 assert a_device.sys_number is None
190
191 @given(_CONTEXT_STRATEGY, strategies.sampled_from(_DEVICE_DATA))
192 @settings(max_examples=5)
193 def test_type(self, a_context, device_datum):
194 device = Devices.from_path(a_context, device_datum.device_path)
195 assert device.device_type == device_datum.properties.get("DEVTYPE")
196 if device.device_type:
197 assert is_unicode_string(device.device_type)
198
199 @given(_CONTEXT_STRATEGY, strategies.sampled_from(_DEVICE_DATA))
200 @settings(max_examples=5)
201 def test_driver(self, a_context, device_datum):
202 device = Devices.from_path(a_context, device_datum.device_path)
203 assert device.driver == device_datum.properties.get("DRIVER")
204 if device.driver:
205 assert is_unicode_string(device.driver)
206
207 @given(_CONTEXT_STRATEGY, strategies.sampled_from(_DEVICE_DATA))
208 @settings(max_examples=5)
209 def test_device_node(self, a_context, device_datum):
210 device = Devices.from_path(a_context, device_datum.device_path)
211 assert device.device_node == device_datum.device_node
212 if device.device_node:
213 assert is_unicode_string(device.device_node)
214
215 @given(_CONTEXT_STRATEGY, strategies.sampled_from(_DEVICE_DATA))
216 @settings(max_examples=5)
217 def test_device_number(self, a_context, device_datum):
218 device = Devices.from_path(a_context, device_datum.device_path)
219 assert device.device_number == device_datum.device_number
220
221 @_UDEV_TEST(165, "test_is_initialized")
222 @given(strategies.sampled_from(_DEVICES))
223 @settings(max_examples=5)
224 def test_is_initialized(self, a_device):
225 assert isinstance(a_device.is_initialized, bool)
226
227 @_UDEV_TEST(165, "test_is_initialized_mock")
228 @given(strategies.sampled_from(_DEVICES))
229 @settings(max_examples=5)
230 def test_is_initialized_mock(self, a_device):
231 funcname = "udev_device_get_is_initialized"
232 spec = lambda d: None
233 with mock.patch.object(a_device._libudev, funcname, autospec=spec) as func:
234 func.return_value = False
235 assert not a_device.is_initialized
236 func.assert_called_once_with(a_device)
237
238 @_UDEV_TEST(165, "test_time_since_initialized")
239 @given(strategies.sampled_from(_DEVICES))
240 @settings(max_examples=5)
241 def test_time_since_initialized(self, a_device):
242 assert isinstance(a_device.time_since_initialized, timedelta)
243
244 @_UDEV_TEST(165, "test_time_since_initialized_mock")
245 @given(strategies.sampled_from(_DEVICES))
246 @settings(max_examples=5)
247 def test_time_since_initialized_mock(self, a_device):
248 funcname = "udev_device_get_usec_since_initialized"
249 spec = lambda d: None
250 with mock.patch.object(a_device._libudev, funcname, autospec=spec) as func:
251 func.return_value = 100
252 assert a_device.time_since_initialized.microseconds == 100
253 func.assert_called_once_with(a_device)
254
255 @given(_CONTEXT_STRATEGY, strategies.sampled_from(_DEVICE_DATA))
256 @settings(max_examples=5)
257 def test_links(self, a_context, device_datum):
258 device = Devices.from_path(a_context, device_datum.device_path)
259 assert sorted(device.device_links) == sorted(device_datum.device_links)
260 for link in device.device_links:
261 assert is_unicode_string(link)
262
263 @given(strategies.sampled_from(_DEVICES))
264 @settings(max_examples=5)
265 def test_action(self, a_device):
266 assert a_device.action is None
267
268 @given(strategies.sampled_from(_DEVICES))
269 @settings(max_examples=5)
270 def test_action_mock(self, a_device):
271 funcname = "udev_device_get_action"
272 spec = lambda d: None
273 with mock.patch.object(a_device._libudev, funcname, autospec=spec) as func:
274 func.return_value = b"spam"
275 assert a_device.action == "spam"
276 func.assert_called_once_with(a_device)
277 func.reset_mock()
278 assert is_unicode_string(a_device.action)
279 func.assert_called_once_with(a_device)
280
281 @given(strategies.sampled_from(_DEVICES))
282 @settings(max_examples=5)
283 def test_sequence_number(self, a_device):
284 assert a_device.sequence_number == 0
285
286 @given(strategies.sampled_from(_DEVICES))
287 @settings(max_examples=5)
288 def test_attributes(self, a_device):
289 # see TestAttributes for complete attribute tests
290 assert isinstance(a_device.attributes, Attributes)
291
292 def test_no_leak(self):
293 """
294 Regression test for issue #32, modelled after the script which revealed
295 this issue.
296
297 The leak was caused by the following reference cycle between
298 ``Attributes`` and ``Device``:
299
300 Device._attributes -> Attributes.device
301
302 https://github.com/lunaryorn/pyudev/issues/32
303 """
304 for _ in _CONTEXT.list_devices(subsystem="usb"):
305 pass
306 # make sure that no memory leaks
307 assert not gc.garbage
308
309 @given(strategies.sampled_from(_DEVICES))
310 @settings(max_examples=5)
311 def test_tags(self, a_device):
312 # see TestTags for complete tag tests
313 assert isinstance(a_device.tags, Tags)
314
315 @given(_CONTEXT_STRATEGY, strategies.sampled_from(_DEVICE_DATA))
316 @settings(max_examples=5)
317 def test_iteration(self, a_context, device_datum):
318 device = Devices.from_path(a_context, device_datum.device_path)
319 for prop in device.properties:
320 assert is_unicode_string(prop)
321 # test that iteration really yields all properties
322 device_properties = set(device.properties)
323 for prop in device_datum.properties:
324 assert prop in device_properties
325
326 @given(_CONTEXT_STRATEGY, strategies.sampled_from(_DEVICE_DATA))
327 @settings(max_examples=100)
328 @_UDEV_TEST(230, "check exact equivalence of device_datum and device")
329 def test_length(self, a_context, device_datum):
330 """
331 Verify that the keys in the device and in the datum are equal.
332 """
333 device = Devices.from_path(a_context, device_datum.device_path)
334 assert frozenset(device_datum.properties.keys()) == frozenset(
335 device.properties.keys()
336 )
337
338 @given(_CONTEXT_STRATEGY, strategies.sampled_from(_DEVICE_DATA))
339 @settings(max_examples=100)
340 def test_key_subset(self, a_context, device_datum):
341 """
342 Verify that the device contains all the keys in the device datum.
343 """
344 device = Devices.from_path(a_context, device_datum.device_path)
345 assert frozenset(device_datum.properties.keys()) <= frozenset(
346 device.properties.keys()
347 )
348
349 @given(_CONTEXT_STRATEGY, strategies.sampled_from(_DEVICE_DATA))
350 @settings(max_examples=1)
351 def test_getitem(self, a_context, device_datum):
352 device = Devices.from_path(a_context, device_datum.device_path)
353 for prop in device_datum.properties:
354 if prop == "DEVLINKS":
355 assert sorted(
356 device.properties[prop].split(),
357 ) == sorted(
358 device_datum.properties[prop].split(),
359 )
360 elif prop == "TAGS":
361 assert sorted(
362 device.properties[prop].split(":"),
363 ) == sorted(
364 device_datum.properties[prop].split(":"),
365 )
366 else:
367 # Do not test equality of device properties with udevadm oracle.
368 # https://bugzilla.redhat.com/show_bug.cgi?id=1787089
369 pass
370
371 _device_data = [d for d in _DEVICE_DATA if "DEVNAME" in d.properties]
372
373 @pytest.mark.skipif(
374 len(_device_data) == 0, reason="no device with a DEVNAME property"
375 )
376 @given(_CONTEXT_STRATEGY, strategies.sampled_from(_device_data))
377 @settings(max_examples=5)
378 def test_getitem_devname(self, a_context, device_datum):
379 device = Devices.from_path(a_context, device_datum.device_path)
380 data_devname = os.path.join(
381 a_context.device_path, device_datum.properties["DEVNAME"]
382 )
383 device_devname = os.path.join(
384 a_context.device_path, device.properties["DEVNAME"]
385 )
386 assert device_devname == data_devname
387
388 @given(strategies.sampled_from(_DEVICES))
389 @settings(max_examples=5)
390 def test_getitem_nonexisting(self, a_device):
391 with pytest.raises(KeyError) as excinfo:
392 # pylint: disable=pointless-statement
393 a_device.properties["a non-existing property"]
394 assert str(excinfo.value) == repr("a non-existing property")
395
396 @given(_CONTEXT_STRATEGY, strategies.sampled_from(_DEVICE_DATA))
397 @settings(max_examples=5)
398 def test_asint(self, a_context, device_datum):
399 device = Devices.from_path(a_context, device_datum.device_path)
400 for prop, value in device_datum.properties.items():
401 try:
402 value = int(value)
403 except ValueError:
404 with pytest.raises(ValueError):
405 device.properties.asint(prop)
406 else:
407 assert device.properties.asint(prop) == value
408
409 @given(_CONTEXT_STRATEGY, strategies.sampled_from(_DEVICE_DATA))
410 @settings(max_examples=5)
411 def test_asbool(self, a_context, device_datum):
412 """
413 Test that values of 1 and 0 get properly interpreted as bool
414 and that all other values raise a ValueError.
415
416 :param Context a_context: libudev context
417 :param device_datum: a device datum
418 """
419 device = Devices.from_path(a_context, device_datum.device_path)
420 for prop, value in device_datum.properties.items():
421 if value == "1":
422 assert device.properties.asbool(prop)
423 elif value == "0":
424 assert not device.properties.asbool(prop)
425 else:
426 with pytest.raises(ValueError) as exc_info:
427 device.properties.asbool(prop)
428
429 @given(strategies.sampled_from(_DEVICES))
430 @settings(max_examples=5)
431 def test_hash(self, a_device):
432 assert hash(a_device) == hash(a_device.device_path)
433 assert hash(a_device.parent) == hash(a_device.parent)
434 assert hash(a_device.parent) != hash(a_device)
435
436 @given(strategies.sampled_from(_DEVICES))
437 @settings(max_examples=5)
438 def test_equality(self, a_device):
439 assert a_device == a_device.device_path
440 assert a_device == a_device
441 assert a_device.parent == a_device.parent
442 # pylint: disable=superfluous-parens
443 assert not (a_device == a_device.parent)
444
445 @given(strategies.sampled_from(_DEVICES))
446 @settings(max_examples=5)
447 def test_inequality(self, a_device):
448 # pylint: disable=superfluous-parens
449 assert not (a_device != a_device.device_path)
450 assert not (a_device != a_device)
451 assert not (a_device.parent != a_device.parent)
452 assert a_device != a_device.parent
453
454 @given(strategies.sampled_from(_DEVICES))
455 @settings(max_examples=1)
456 def test_device_ordering(self, a_device):
457 """
458 Verify that devices are incomparable.
459 """
460 operators = [operator.ge, operator.gt, operator.le, operator.lt]
461 for comp_op in operators:
462 with pytest.raises(TypeError) as exc_info:
463 comp_op(a_device, a_device)
464 assert str(exc_info.value) == "Device not orderable"
465
466 _devices = [
467 d
468 for d in _DEVICES
469 if d.device_type == "disk"
470 and "ID_WWN_WITH_EXTENSION" in d.properties
471 and "DM_MULTIPATH_TIMESTAMP" not in d.properties
472 ]
473
474 @pytest.mark.skipif(
475 len(_devices) == 0, reason="unsafe to check ID_WWN_WITH_EXTENSION"
476 )
477 @given(strategies.sampled_from(_devices))
478 @settings(max_examples=5)
479 def test_id_wwn_with_extension(self, a_device):
480 """
481 Test that the ID_WWN_WITH_EXTENSION has a corresponding link.
482
483 Assert that the device is a block device if it has an
484 ID_WWN_WITH_EXTENSION property.
485
486 Skip any multipathed paths, see:
487 https://bugzilla.redhat.com/show_bug.cgi?id=1263441.
488 """
489 id_wwn = a_device.properties["ID_WWN_WITH_EXTENSION"]
490 assert a_device.subsystem == "block"
491
492 id_path = "/dev/disk/by-id"
493 link_name = "wwn-%s" % id_wwn
494 match = next((d for d in os.listdir(id_path) if d == link_name), None)
495 assert match is not None
496
497 link_path = os.path.join(id_path, match)
498 link_target = os.readlink(link_path)
499 target_path = os.path.normpath(os.path.join(id_path, link_target))
500 assert target_path == a_device.device_node