Debian Codegraph @

test/test_udev_rules.py

raw
1 #!/usr/bin/env python3
2 #
3 # This test will only work where /dev/uinput is available.
4 # This test will reload the hwdb and udev rules
5 #
6 # Execute via pytest, it will:
7 # - load all data files and extract the matches
8 # - create a uinput device for each match
9 # - check if that device has the udev properties set we expect
10
11 import configparser
12 import os
13 from pathlib import Path
14 import pytest
15 import logging
16 import sys
17 import subprocess
18 import shutil
19
20
21 @pytest.fixture(scope="session", autouse=True)
22 def systemd_reload():
23 """Make sure our hwdb and udev rules are up-to-date"""
24
25 try:
26 hwdb = os.environ.get("LIBWACOM_HWDB_FILE")
27 target = Path("/etc/udev/hwdb.d/99-libwacom-pytest.hwdb")
28 target.parent.mkdir(exist_ok=True, parents=True)
29 if hwdb:
30 shutil.copyfile(hwdb, target)
31 else:
32 import warnings
33
34 warnings.warn("LIBWACOM_HWDB_FILE is not set, using already installed hwdb")
35
36 subprocess.run(["systemd-hwdb", "update"], check=True)
37
38 yield
39
40 if hwdb:
41 os.unlink(target)
42
43 subprocess.run(["systemd-hwdb", "update"], check=True)
44
45 except (IOError, FileNotFoundError, subprocess.CalledProcessError) as e:
46 # If any of the commands above are not found (most likely the system
47 # simply does not use systemd), just skip.
48 logging.critical(f"{e}")
49 pytest.skip(f"Skipping test: {e}")
50 except Exception as e:
51 logging.critical(f"{e}")
52 pytest.fail(f"Aborting test: {e}")
53
54
55 def pytest_generate_tests(metafunc):
56 # for any function that takes a "tablet" argument return a Tablet object
57 # filled with exactly one DeviceMatch from the list of all .tablet files
58 # in the data dir. Where the tablet also has touch/buttons generate an
59 # extra Finger or Pad device
60 if "tablet" in metafunc.fixturenames:
61 datadir = Path(os.getenv("MESON_SOURCE_ROOT") or ".") / "data"
62 tablets = []
63 for f in datadir.glob("*.tablet"):
64 config = configparser.ConfigParser()
65 config.read(f)
66 name = config["Device"]["Name"]
67 want_pad = config["Device"].get("Buttons", 0)
68 want_finger = config["Features"].get("Touch") == "true"
69 integrated_in = config["Device"].get("IntegratedIn", "").split(";")
70 is_touchscreen = set(integrated_in) & set(["Display", "System"])
71
72 for match in config["Device"]["DeviceMatch"].split(";"):
73 if not match or match == "generic":
74 continue
75
76 bus, vid, pid = match.split("|")[:3] # skip the name part of the match
77 if bus not in ["usb", "bluetooth"]:
78 continue
79
80 try:
81 vid = int(vid, 16)
82 pid = int(pid, 16)
83 except ValueError as e:
84 print(f"Invalid vid/pid in {match} in {f}", file=sys.stderr)
85 raise e
86
87 if bus == "usb":
88 bus = 0x3
89 elif bus == "bluetooth":
90 bus = 0x5
91
92 class Tablet(object):
93 def __init__(self, name, bus, vid, pid, is_touchscreen=False):
94 self.name = name
95 self.bus = bus
96 self.vid = vid
97 self.pid = pid
98 self.is_touchscreen = is_touchscreen
99
100 tablets.append(Tablet(name, bus, vid, pid))
101
102 if want_pad:
103 tablets.append(Tablet(name + " Pad", bus, vid, pid))
104
105 if want_finger:
106 tablets.append(
107 Tablet(name + " Finger", bus, vid, pid, is_touchscreen)
108 )
109
110 # our tablets list now becomes the list of arguments passed to the
111 # test functions taking a 'tablet' argument - one-by-one. So where
112 # tablets contains 10 entries, our test function will be called 10
113 # times.
114 metafunc.parametrize("tablet", tablets, ids=[t.name for t in tablets])
115
116
117 @pytest.mark.skipif(sys.platform != "linux", reason="This test requires udev")
118 def test_hwdb_files(tablet):
119 # Note: the actual name doesn't really matter, all our hwdb files use either "*"
120 # or "* Finger", etc. It does matter for that "Finger" suffix though.
121 query = f"libwacom:name:{tablet.name}:input:b{tablet.bus:04X}v{tablet.vid:04X}p{tablet.pid:04X}"
122 logging.debug(query)
123
124 r = subprocess.run(
125 ["systemd-hwdb", "query", query], check=True, capture_output=True
126 )
127 stdout = r.stdout.decode("utf-8").strip()
128 assert stdout, f"No output recorded for query {query}"
129 logging.debug(stdout)
130 props = {}
131 for line in filter(lambda line: len(line) > 1, stdout.split("\n")):
132 print(line)
133 k, v = line.split("=")
134 props[k] = v
135
136 assert "ID_INPUT" in props
137 assert props["ID_INPUT"] == "1"
138
139 assert "ID_INPUT_TABLET" in props
140 assert props["ID_INPUT_TABLET"] == "1"
141
142 if "ID_INPUT_JOYSTICK" not in props:
143 assert props["ID_INPUT_JOYSTICK"] == "0"
144
145 if "Finger" in tablet.name:
146 if tablet.is_touchscreen:
147 assert "ID_INPUT_TOUCHSCREEN" in props
148 else:
149 assert "ID_INPUT_TOUCHPAD" in props
150
151 # For the Wacom Bamboo Pad we check for "Pad Pad" in the device name
152 if "Pad" in tablet.name:
153 if "Wacom Bamboo Pad" not in tablet.name or "Pad Pad" in tablet.name:
154 assert "ID_INPUT_TABLET_PAD" in props