base.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. #!/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0
  3. # -*- coding: utf-8 -*-
  4. #
  5. # Copyright (c) 2017 Benjamin Tissoires <benjamin.tissoires@gmail.com>
  6. # Copyright (c) 2017 Red Hat, Inc.
  7. import libevdev
  8. import os
  9. import pytest
  10. import shutil
  11. import subprocess
  12. import time
  13. import logging
  14. from .base_device import BaseDevice, EvdevMatch, SysfsFile
  15. from pathlib import Path
  16. from typing import Final, List, Tuple
  17. logger = logging.getLogger("hidtools.test.base")
  18. # application to matches
  19. application_matches: Final = {
  20. # pyright: ignore
  21. "Accelerometer": EvdevMatch(
  22. req_properties=[
  23. libevdev.INPUT_PROP_ACCELEROMETER,
  24. ]
  25. ),
  26. "Game Pad": EvdevMatch( # in systemd, this is a lot more complex, but that will do
  27. requires=[
  28. libevdev.EV_ABS.ABS_X,
  29. libevdev.EV_ABS.ABS_Y,
  30. libevdev.EV_ABS.ABS_RX,
  31. libevdev.EV_ABS.ABS_RY,
  32. libevdev.EV_KEY.BTN_START,
  33. ],
  34. excl_properties=[
  35. libevdev.INPUT_PROP_ACCELEROMETER,
  36. ],
  37. ),
  38. "Joystick": EvdevMatch( # in systemd, this is a lot more complex, but that will do
  39. requires=[
  40. libevdev.EV_ABS.ABS_RX,
  41. libevdev.EV_ABS.ABS_RY,
  42. libevdev.EV_KEY.BTN_START,
  43. ],
  44. excl_properties=[
  45. libevdev.INPUT_PROP_ACCELEROMETER,
  46. ],
  47. ),
  48. "Key": EvdevMatch(
  49. requires=[
  50. libevdev.EV_KEY.KEY_A,
  51. ],
  52. excl_properties=[
  53. libevdev.INPUT_PROP_ACCELEROMETER,
  54. libevdev.INPUT_PROP_DIRECT,
  55. libevdev.INPUT_PROP_POINTER,
  56. ],
  57. ),
  58. "Mouse": EvdevMatch(
  59. requires=[
  60. libevdev.EV_REL.REL_X,
  61. libevdev.EV_REL.REL_Y,
  62. libevdev.EV_KEY.BTN_LEFT,
  63. ],
  64. excl_properties=[
  65. libevdev.INPUT_PROP_ACCELEROMETER,
  66. ],
  67. ),
  68. "Pad": EvdevMatch(
  69. requires=[
  70. libevdev.EV_KEY.BTN_0,
  71. ],
  72. excludes=[
  73. libevdev.EV_KEY.BTN_TOOL_PEN,
  74. libevdev.EV_KEY.BTN_TOUCH,
  75. libevdev.EV_ABS.ABS_DISTANCE,
  76. ],
  77. excl_properties=[
  78. libevdev.INPUT_PROP_ACCELEROMETER,
  79. ],
  80. ),
  81. "Pen": EvdevMatch(
  82. requires=[
  83. libevdev.EV_KEY.BTN_STYLUS,
  84. libevdev.EV_ABS.ABS_X,
  85. libevdev.EV_ABS.ABS_Y,
  86. ],
  87. excl_properties=[
  88. libevdev.INPUT_PROP_ACCELEROMETER,
  89. ],
  90. ),
  91. "Stylus": EvdevMatch(
  92. requires=[
  93. libevdev.EV_KEY.BTN_STYLUS,
  94. libevdev.EV_ABS.ABS_X,
  95. libevdev.EV_ABS.ABS_Y,
  96. ],
  97. excl_properties=[
  98. libevdev.INPUT_PROP_ACCELEROMETER,
  99. ],
  100. ),
  101. "Touch Pad": EvdevMatch(
  102. requires=[
  103. libevdev.EV_KEY.BTN_LEFT,
  104. libevdev.EV_ABS.ABS_X,
  105. libevdev.EV_ABS.ABS_Y,
  106. ],
  107. excludes=[libevdev.EV_KEY.BTN_TOOL_PEN, libevdev.EV_KEY.BTN_STYLUS],
  108. req_properties=[
  109. libevdev.INPUT_PROP_POINTER,
  110. ],
  111. excl_properties=[
  112. libevdev.INPUT_PROP_ACCELEROMETER,
  113. ],
  114. ),
  115. "Touch Screen": EvdevMatch(
  116. requires=[
  117. libevdev.EV_KEY.BTN_TOUCH,
  118. libevdev.EV_ABS.ABS_X,
  119. libevdev.EV_ABS.ABS_Y,
  120. ],
  121. excludes=[libevdev.EV_KEY.BTN_TOOL_PEN, libevdev.EV_KEY.BTN_STYLUS],
  122. req_properties=[
  123. libevdev.INPUT_PROP_DIRECT,
  124. ],
  125. excl_properties=[
  126. libevdev.INPUT_PROP_ACCELEROMETER,
  127. ],
  128. ),
  129. }
  130. class UHIDTestDevice(BaseDevice):
  131. def __init__(self, name, application, rdesc_str=None, rdesc=None, input_info=None):
  132. super().__init__(name, application, rdesc_str, rdesc, input_info)
  133. self.application_matches = application_matches
  134. if name is None:
  135. name = f"uhid test {self.__class__.__name__}"
  136. if not name.startswith("uhid test "):
  137. name = "uhid test " + self.name
  138. self.name = name
  139. class BaseTestCase:
  140. class TestUhid(object):
  141. syn_event = libevdev.InputEvent(libevdev.EV_SYN.SYN_REPORT) # type: ignore
  142. key_event = libevdev.InputEvent(libevdev.EV_KEY) # type: ignore
  143. abs_event = libevdev.InputEvent(libevdev.EV_ABS) # type: ignore
  144. rel_event = libevdev.InputEvent(libevdev.EV_REL) # type: ignore
  145. msc_event = libevdev.InputEvent(libevdev.EV_MSC.MSC_SCAN) # type: ignore
  146. # List of kernel modules to load before starting the test
  147. # if any module is not available (not compiled), the test will skip.
  148. # Each element is a tuple '(kernel driver name, kernel module)',
  149. # for example ("playstation", "hid-playstation")
  150. kernel_modules: List[Tuple[str, str]] = []
  151. # List of in kernel HID-BPF object files to load
  152. # before starting the test
  153. # Any existing pre-loaded HID-BPF module will be removed
  154. # before the ones in this list will be manually loaded.
  155. # Each Element is a tuple '(hid_bpf_object, rdesc_fixup_present)',
  156. # for example '("xppen-ArtistPro16Gen2.bpf.o", True)'
  157. # If 'rdesc_fixup_present' is True, the test needs to wait
  158. # for one unbind and rebind before it can be sure the kernel is
  159. # ready
  160. hid_bpfs: List[Tuple[str, bool]] = []
  161. def assertInputEventsIn(self, expected_events, effective_events):
  162. effective_events = effective_events.copy()
  163. for ev in expected_events:
  164. assert ev in effective_events
  165. effective_events.remove(ev)
  166. return effective_events
  167. def assertInputEvents(self, expected_events, effective_events):
  168. remaining = self.assertInputEventsIn(expected_events, effective_events)
  169. assert remaining == []
  170. @classmethod
  171. def debug_reports(cls, reports, uhdev=None, events=None):
  172. data = [" ".join([f"{v:02x}" for v in r]) for r in reports]
  173. if uhdev is not None:
  174. human_data = [
  175. uhdev.parsed_rdesc.format_report(r, split_lines=True)
  176. for r in reports
  177. ]
  178. try:
  179. human_data = [
  180. f'\n\t {" " * h.index("/")}'.join(h.split("\n"))
  181. for h in human_data
  182. ]
  183. except ValueError:
  184. # '/' not found: not a numbered report
  185. human_data = ["\n\t ".join(h.split("\n")) for h in human_data]
  186. data = [f"{d}\n\t ====> {h}" for d, h in zip(data, human_data)]
  187. reports = data
  188. if len(reports) == 1:
  189. print("sending 1 report:")
  190. else:
  191. print(f"sending {len(reports)} reports:")
  192. for report in reports:
  193. print("\t", report)
  194. if events is not None:
  195. print("events received:", events)
  196. def create_device(self):
  197. raise Exception("please reimplement me in subclasses")
  198. def _load_kernel_module(self, kernel_driver, kernel_module):
  199. sysfs_path = Path("/sys/bus/hid/drivers")
  200. if kernel_driver is not None:
  201. sysfs_path /= kernel_driver
  202. else:
  203. # special case for when testing all available modules:
  204. # we don't know beforehand the name of the module from modinfo
  205. sysfs_path = Path("/sys/module") / kernel_module.replace("-", "_")
  206. if not sysfs_path.exists():
  207. ret = subprocess.run(["/usr/sbin/modprobe", kernel_module])
  208. if ret.returncode != 0:
  209. pytest.skip(
  210. f"module {kernel_module} could not be loaded, skipping the test"
  211. )
  212. @pytest.fixture()
  213. def load_kernel_module(self):
  214. for kernel_driver, kernel_module in self.kernel_modules:
  215. self._load_kernel_module(kernel_driver, kernel_module)
  216. yield
  217. def load_hid_bpfs(self):
  218. script_dir = Path(os.path.dirname(os.path.realpath(__file__)))
  219. root_dir = (script_dir / "../../../../..").resolve()
  220. bpf_dir = root_dir / "drivers/hid/bpf/progs"
  221. udev_hid_bpf = shutil.which("udev-hid-bpf")
  222. if not udev_hid_bpf:
  223. pytest.skip("udev-hid-bpf not found in $PATH, skipping")
  224. wait = False
  225. for _, rdesc_fixup in self.hid_bpfs:
  226. if rdesc_fixup:
  227. wait = True
  228. for hid_bpf, _ in self.hid_bpfs:
  229. # We need to start `udev-hid-bpf` in the background
  230. # and dispatch uhid events in case the kernel needs
  231. # to fetch features on the device
  232. process = subprocess.Popen(
  233. [
  234. "udev-hid-bpf",
  235. "--verbose",
  236. "add",
  237. str(self.uhdev.sys_path),
  238. str(bpf_dir / hid_bpf),
  239. ],
  240. )
  241. while process.poll() is None:
  242. self.uhdev.dispatch(1)
  243. if process.poll() != 0:
  244. pytest.fail(
  245. f"Couldn't insert hid-bpf program '{hid_bpf}', marking the test as failed"
  246. )
  247. if wait:
  248. # the HID-BPF program exports a rdesc fixup, so it needs to be
  249. # unbound by the kernel and then rebound.
  250. # Ensure we get the bound event exactly 2 times (one for the normal
  251. # uhid loading, and then the reload from HID-BPF)
  252. now = time.time()
  253. while self.uhdev.kernel_ready_count < 2 and time.time() - now < 2:
  254. self.uhdev.dispatch(1)
  255. if self.uhdev.kernel_ready_count < 2:
  256. pytest.fail(
  257. f"Couldn't insert hid-bpf programs, marking the test as failed"
  258. )
  259. def unload_hid_bpfs(self):
  260. ret = subprocess.run(
  261. ["udev-hid-bpf", "--verbose", "remove", str(self.uhdev.sys_path)],
  262. )
  263. if ret.returncode != 0:
  264. pytest.fail(
  265. f"Couldn't unload hid-bpf programs, marking the test as failed"
  266. )
  267. @pytest.fixture()
  268. def new_uhdev(self, load_kernel_module):
  269. return self.create_device()
  270. def assertName(self, uhdev):
  271. evdev = uhdev.get_evdev()
  272. assert uhdev.name in evdev.name
  273. @pytest.fixture(autouse=True)
  274. def context(self, new_uhdev, request):
  275. try:
  276. with HIDTestUdevRule.instance():
  277. with new_uhdev as self.uhdev:
  278. for skip_cond in request.node.iter_markers("skip_if_uhdev"):
  279. test, message, *rest = skip_cond.args
  280. if test(self.uhdev):
  281. pytest.skip(message)
  282. self.uhdev.create_kernel_device()
  283. now = time.time()
  284. while not self.uhdev.is_ready() and time.time() - now < 5:
  285. self.uhdev.dispatch(1)
  286. if self.hid_bpfs:
  287. self.load_hid_bpfs()
  288. if self.uhdev.get_evdev() is None:
  289. logger.warning(
  290. f"available list of input nodes: (default application is '{self.uhdev.application}')"
  291. )
  292. logger.warning(self.uhdev.input_nodes)
  293. yield
  294. if self.hid_bpfs:
  295. self.unload_hid_bpfs()
  296. self.uhdev = None
  297. except PermissionError:
  298. pytest.skip("Insufficient permissions, run me as root")
  299. @pytest.fixture(autouse=True)
  300. def check_taint(self):
  301. # we are abusing SysfsFile here, it's in /proc, but meh
  302. taint_file = SysfsFile("/proc/sys/kernel/tainted")
  303. taint = taint_file.int_value
  304. yield
  305. assert taint_file.int_value == taint
  306. def test_creation(self):
  307. """Make sure the device gets processed by the kernel and creates
  308. the expected application input node.
  309. If this fail, there is something wrong in the device report
  310. descriptors."""
  311. uhdev = self.uhdev
  312. assert uhdev is not None
  313. assert uhdev.get_evdev() is not None
  314. self.assertName(uhdev)
  315. assert len(uhdev.next_sync_events()) == 0
  316. assert uhdev.get_evdev() is not None
  317. class HIDTestUdevRule(object):
  318. _instance = None
  319. """
  320. A context-manager compatible class that sets up our udev rules file and
  321. deletes it on context exit.
  322. This class is tailored to our test setup: it only sets up the udev rule
  323. on the **second** context and it cleans it up again on the last context
  324. removed. This matches the expected pytest setup: we enter a context for
  325. the session once, then once for each test (the first of which will
  326. trigger the udev rule) and once the last test exited and the session
  327. exited, we clean up after ourselves.
  328. """
  329. def __init__(self):
  330. self.refs = 0
  331. self.rulesfile = None
  332. def __enter__(self):
  333. self.refs += 1
  334. if self.refs == 2 and self.rulesfile is None:
  335. self.create_udev_rule()
  336. self.reload_udev_rules()
  337. def __exit__(self, exc_type, exc_value, traceback):
  338. self.refs -= 1
  339. if self.refs == 0 and self.rulesfile:
  340. os.remove(self.rulesfile.name)
  341. self.reload_udev_rules()
  342. def reload_udev_rules(self):
  343. subprocess.run("udevadm control --reload-rules".split())
  344. subprocess.run("systemd-hwdb update".split())
  345. def create_udev_rule(self):
  346. import tempfile
  347. os.makedirs("/run/udev/rules.d", exist_ok=True)
  348. with tempfile.NamedTemporaryFile(
  349. prefix="91-uhid-test-device-REMOVEME-",
  350. suffix=".rules",
  351. mode="w+",
  352. dir="/run/udev/rules.d",
  353. delete=False,
  354. ) as f:
  355. f.write(
  356. """
  357. KERNELS=="*input*", ATTRS{name}=="*uhid test *", ENV{LIBINPUT_IGNORE_DEVICE}="1"
  358. KERNELS=="*hid*", ENV{HID_NAME}=="*uhid test *", ENV{HID_BPF_IGNORE_DEVICE}="1"
  359. KERNELS=="*input*", ATTRS{name}=="*uhid test * System Multi Axis", ENV{ID_INPUT_TOUCHSCREEN}="", ENV{ID_INPUT_SYSTEM_MULTIAXIS}="1"
  360. """
  361. )
  362. self.rulesfile = f
  363. @classmethod
  364. def instance(cls):
  365. if not cls._instance:
  366. cls._instance = HIDTestUdevRule()
  367. return cls._instance