Debian Codegraph @

tests/test_usb.py

raw
1 # SPDX-License-Identifier: LGPL-2.1-or-later
2 #
3 # This file is formatted with Python Black
4
5 import tests as xdp
6
7 import pytest
8 import os
9 import gi
10 import subprocess
11 import re
12
13 gi.require_version("UMockdev", "1.0")
14 from gi.repository import GLib, UMockdev # noqa E402
15
16
17 @pytest.fixture
18 def required_templates():
19 return {"usb": {}}
20
21
22 @pytest.fixture
23 def umockdev():
24 return UMockdev.Testbed.new()
25
26
27 def umockdev_has_working_remove():
28 # umockdev only generates remove events since version 0.18.4
29 # https://github.com/martinpitt/umockdev/releases/tag/0.18.4
30 required = (0, 18, 4)
31
32 result = subprocess.run(["umockdev-run", "--version"], stdout=subprocess.PIPE)
33 if result.returncode != 0:
34 return False
35 match = re.match(r"^(\d+)\.(\d+)\.(\d+)", result.stdout.decode("UTF-8").strip())
36 if not match:
37 return False
38 version = tuple(map(int, match.groups()))
39 return version >= required
40
41
42 class TestUsb:
43 _num_devices = 0
44
45 def generate_device(
46 self, testbed, vendor, vendor_name, product, product_name, serial
47 ):
48 n = self._num_devices
49 self._num_devices += 1
50
51 testbed.add_from_string(f"""P: /devices/usb{n}
52 N: bus/usb/001/{n:03d}
53 E: BUSNUM=001
54 E: DEVNUM={n:03d}
55 E: DEVNAME=/dev/bus/usb/001/{n:03d}
56 E: DEVTYPE=usb_device
57 E: DRIVER=usb
58 E: ID_BUS=usb
59 E: ID_MODEL={product_name}
60 E: ID_MODEL_ID={product}
61 E: ID_REVISION=0002
62 E: ID_SERIAL={vendor_name}_{product_name}_{serial}
63 E: ID_SERIAL_SHORT={serial}
64 E: ID_VENDOR={vendor_name}
65 E: ID_VENDOR_ID={vendor}
66 E: SUBSYSTEM=usb
67 A: idProduct={product}
68 A: idVendor={vendor}
69 """)
70
71 return f"/sys/devices/usb{n}"
72
73 def test_version(self, portals, dbus_con):
74 xdp.check_version(dbus_con, "Usb", 1)
75
76 def test_create_close_session(self, portals, dbus_con, app_id):
77 usb_intf = xdp.get_portal_iface(dbus_con, "Usb")
78
79 session = xdp.Session(
80 dbus_con,
81 usb_intf.CreateSession({"session_handle_token": "session_token0"}),
82 )
83 session.close()
84
85 def test_empty_initial_devices(self, portals, dbus_con, app_id):
86 usb_intf = xdp.get_portal_iface(dbus_con, "Usb")
87
88 xdp.Session(
89 dbus_con,
90 usb_intf.CreateSession({"session_handle_token": "session_token0"}),
91 )
92
93 device_events_signal_received = False
94
95 def cb_device_events(session_handle, events):
96 nonlocal device_events_signal_received
97 device_events_signal_received = True
98
99 usb_intf.connect_to_signal("DeviceEvents", cb_device_events)
100 xdp.wait(300)
101 assert not device_events_signal_received
102
103 @pytest.mark.parametrize("usb_queries", ["vnd:04a9", None])
104 def test_initial_devices(self, portals, dbus_con, app_id, usb_queries, umockdev):
105 usb_intf = xdp.get_portal_iface(dbus_con, "Usb")
106
107 self.generate_device(
108 umockdev,
109 "04a9",
110 "Canon_Inc.",
111 "31c0",
112 "Canon_Digital_Camera",
113 "C767F1C714174C309255F70E4A7B2EE2",
114 )
115
116 # TODO: to make this more robust, we should find a way to wait for
117 # the portal to pick up the device
118 xdp.wait(300)
119
120 session = xdp.Session(
121 dbus_con,
122 usb_intf.CreateSession({"session_handle_token": "session_token0"}),
123 )
124
125 device_events_signal_received = False
126 devices_received = 0
127
128 def cb_device_events(session_handle, events):
129 nonlocal device_events_signal_received
130 nonlocal devices_received
131 assert session.handle == session_handle
132
133 for action, id, device in events:
134 assert action == "add"
135 devices_received += 1
136
137 device_events_signal_received = True
138
139 usb_intf.connect_to_signal("DeviceEvents", cb_device_events)
140
141 if usb_queries is None:
142 xdp.wait(300)
143 assert not device_events_signal_received
144 assert devices_received == 0
145 else:
146 xdp.wait_for(lambda: device_events_signal_received)
147 assert devices_received == 1
148
149 @pytest.mark.parametrize("usb_queries", ["vnd:04a9", None])
150 def test_device_add(self, portals, dbus_con, app_id, usb_queries, umockdev):
151 usb_intf = xdp.get_portal_iface(dbus_con, "Usb")
152
153 session = xdp.Session(
154 dbus_con,
155 usb_intf.CreateSession({"session_handle_token": "session_token0"}),
156 )
157
158 device_events_signal_received = False
159 devices_received = 0
160 device = None
161
162 def cb_device_events(session_handle, events):
163 nonlocal device_events_signal_received
164 nonlocal devices_received
165 nonlocal device
166 assert session.handle == session_handle
167
168 for action, _, dev in events:
169 assert action == "add"
170 device = dev
171 devices_received += 1
172
173 device_events_signal_received = True
174
175 usb_intf.connect_to_signal("DeviceEvents", cb_device_events)
176 xdp.wait(300)
177 assert not device_events_signal_received
178
179 self.generate_device(
180 umockdev,
181 "04a9",
182 "Canon_Inc.",
183 "31c0",
184 "Canon_Digital_Camera",
185 "C767F1C714174C309255F70E4A7B2EE2",
186 )
187
188 if usb_queries is None:
189 xdp.wait(300)
190 assert not device_events_signal_received
191 assert devices_received == 0
192 else:
193 xdp.wait_for(lambda: device_events_signal_received)
194 assert devices_received == 1
195
196 assert device
197 assert device["readable"]
198 assert device["writable"]
199 assert device["device-file"] == "/dev/bus/usb/001/000"
200 assert device["properties"]["ID_VENDOR_ID"] == "04a9"
201 assert device["properties"]["ID_MODEL_ID"] == "31c0"
202 assert (
203 device["properties"]["ID_SERIAL"]
204 == "Canon_Inc._Canon_Digital_Camera_C767F1C714174C309255F70E4A7B2EE2"
205 )
206
207 @pytest.mark.parametrize("usb_queries", ["vnd:04a9", None])
208 @pytest.mark.skipif(
209 not umockdev_has_working_remove(), reason="UMockdev version 0.18.4 required"
210 )
211 def test_device_remove(self, portals, dbus_con, app_id, usb_queries, umockdev):
212 usb_intf = xdp.get_portal_iface(dbus_con, "Usb")
213
214 dev_path = self.generate_device(
215 umockdev,
216 "04a9",
217 "Canon_Inc.",
218 "31c0",
219 "Canon_Digital_Camera",
220 "C767F1C714174C309255F70E4A7B2EE2",
221 )
222
223 session = xdp.Session(
224 dbus_con,
225 usb_intf.CreateSession({"session_handle_token": "session_token0"}),
226 )
227
228 device_events_signal_count = 0
229 devices_received = 0
230 devices_removed = 0
231
232 def cb_device_events(session_handle, events):
233 nonlocal device_events_signal_count
234 nonlocal devices_received
235 nonlocal devices_removed
236
237 assert session.handle == session_handle
238
239 for action, id, device in events:
240 if action == "add":
241 devices_received += 1
242 elif action == "remove":
243 devices_removed += 1
244 else:
245 assert False
246
247 device_events_signal_count += 1
248
249 usb_intf.connect_to_signal("DeviceEvents", cb_device_events)
250
251 if usb_queries is None:
252 xdp.wait(300)
253 assert device_events_signal_count == 0
254 assert devices_received == 0
255 assert devices_removed == 0
256 else:
257 xdp.wait_for(lambda: device_events_signal_count == 1)
258 assert devices_received == 1
259 assert devices_removed == 0
260
261 umockdev.remove_device(dev_path)
262
263 if usb_queries is None:
264 xdp.wait(300)
265 assert device_events_signal_count == 0
266 assert devices_received == 0
267 assert devices_removed == 0
268 else:
269 xdp.wait_for(lambda: device_events_signal_count == 2)
270 assert devices_received == 1
271 assert devices_removed == 1
272
273 @pytest.mark.parametrize("usb_queries", ["vnd:04a9;vnd:04aa"])
274 @pytest.mark.parametrize(
275 "template_params", [{"usb": {"filters": {"vendor": "04a9"}}}]
276 )
277 def test_acquire(self, portals, dbus_con, app_id, umockdev):
278 usb_intf = xdp.get_portal_iface(dbus_con, "Usb")
279
280 self.generate_device(
281 umockdev,
282 "04a9",
283 "Canon_Inc.",
284 "31c0",
285 "Canon_Digital_Camera",
286 "C767F1C714174C309255F70E4A7B2EE2",
287 )
288
289 self.generate_device(
290 umockdev,
291 "04aa",
292 "Someone Else.",
293 "31c0",
294 "SomeProduct",
295 "00001",
296 )
297
298 possible_vendors = ["04a9", "04aa"]
299
300 devices = usb_intf.EnumerateDevices({})
301 assert len(devices) == 2
302 (id1, dev_info1) = devices[0]
303 assert id1
304 assert dev_info1
305 vendor_id = dev_info1["properties"]["ID_VENDOR_ID"]
306 assert vendor_id in possible_vendors
307 possible_vendors.remove(vendor_id)
308 (id2, dev_info2) = devices[1]
309 assert id2
310 assert dev_info2
311 vendor_id = dev_info2["properties"]["ID_VENDOR_ID"]
312 assert vendor_id in possible_vendors
313 possible_vendors.remove(vendor_id)
314
315 request = xdp.Request(dbus_con, usb_intf)
316 response = request.call(
317 "AcquireDevices",
318 parent_window="",
319 devices=[
320 (id1, {"writable": True}),
321 (id2, {"writable": True}),
322 ],
323 options={},
324 )
325 assert response
326 assert response.response == 0
327
328 (results, finished) = usb_intf.FinishAcquireDevices(request.handle, {})
329 assert finished
330 assert len(results) == 1
331 (res_id, device) = results[0]
332 assert res_id == id1 or res_id == id2
333 assert device["success"]
334 fd = device["fd"].take()
335 assert fd > 0
336 with os.fdopen(fd, "r") as f:
337 assert f
338 assert "error" not in device
339
340 usb_intf.ReleaseDevices([res_id], {})
341
342 @pytest.mark.parametrize("usb_queries", ["vnd:0001"])
343 @pytest.mark.parametrize(
344 "expected,template_params",
345 [
346 (1, {"usb": {"filters": {"model": "0000"}}}),
347 (1, {"usb": {"filters": {"model": "0001"}}}),
348 (0, {"usb": {"filters": {"model": "0002"}}}),
349 (2, {"usb": {"filters": {"vendor": "0001"}}}),
350 (0, {"usb": {"filters": {"vendor": "0002"}}}),
351 (1, {"usb": {"filters": {"vendor": "0001", "model": "0000"}}}),
352 (0, {"usb": {"filters": {"vendor": "0002", "model": "0000"}}}),
353 ],
354 )
355 def test_queries(self, portals, dbus_con, expected, app_id, usb_queries, umockdev):
356 usb_intf = xdp.get_portal_iface(dbus_con, "Usb")
357
358 for i in range(2):
359 self.generate_device(
360 umockdev,
361 "0001",
362 "example_org",
363 f"000{i}",
364 f"model{i}",
365 "0001",
366 )
367
368 devices = usb_intf.EnumerateDevices({})
369 assert len(devices) == 2
370 acquire_devices = [(id, {"writable": True}) for (id, _) in devices]
371
372 request = xdp.Request(dbus_con, usb_intf)
373 response = request.call(
374 "AcquireDevices",
375 parent_window="",
376 devices=acquire_devices,
377 options={},
378 )
379 assert response
380 assert response.response == 0
381
382 (results, finished) = usb_intf.FinishAcquireDevices(request.handle, {})
383 assert finished
384 assert len(results) == expected