1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
|
import asyncio
import multiprocessing
import os
import shutil
import signal
import subprocess
import time
from enum import Enum
import pytest
from dbus_fast.aio import MessageBus
from dbus_fast.constants import BusType, PropertyAccess
from dbus_fast.service import ServiceInterface, dbus_property, method
from libqtile.bar import Bar
from libqtile.config import Screen
from libqtile.widget.bluetooth import BLUEZ_ADAPTER, BLUEZ_BATTERY, BLUEZ_DEVICE, Bluetooth
from test.conftest import BareConfig
from test.helpers import Retry
ADAPTER_PATH = "/org/bluez/hci0"
ADAPTER_NAME = "qtile_bluez"
BLUEZ_SERVICE = "test.qtile.bluez"
class DeviceState(Enum):
UNPAIRED = 1
PAIRED = 2
CONNECTED = 3
class ForceSessionBusType:
SESSION = BusType.SESSION
SYSTEM = BusType.SESSION
class Device(ServiceInterface):
def __init__(self, *args, alias, state, adapter, address, **kwargs):
ServiceInterface.__init__(self, *args, **kwargs)
self._state = state
self._name = alias
self._adapter = adapter
self._address = ":".join([address] * 8)
@method()
def Pair(self): # noqa: F821, N802
self._state = DeviceState.PAIRED
self.emit_properties_changed({"Paired": True, "Connected": False})
@method()
def Connect(self): # noqa: F821, N802
self._state = DeviceState.CONNECTED
self.emit_properties_changed({"Paired": True, "Connected": True})
@method()
def Disconnect(self): # noqa: F821, N802
self._state = DeviceState.PAIRED
self.emit_properties_changed({"Paired": True, "Connected": False})
@dbus_property(access=PropertyAccess.READ)
def Name(self) -> "s": # noqa: F821, N802
return self._name
@dbus_property(access=PropertyAccess.READ)
def Address(self) -> "s": # noqa: F821, N802
return self._address
@dbus_property(access=PropertyAccess.READ)
def Adapter(self) -> "s": # noqa: F821, N802
return self._adapter
@dbus_property(access=PropertyAccess.READ)
def Connected(self) -> "b": # noqa: F821, N802
return self._state == DeviceState.CONNECTED
@dbus_property(access=PropertyAccess.READ)
def Paired(self) -> "b": # noqa: F821, N802
return self._state != DeviceState.UNPAIRED
class Adapter(ServiceInterface):
def __init__(self, *args, **kwargs):
ServiceInterface.__init__(self, *args, **kwargs)
self._name = ADAPTER_NAME
self._powered = True
self._discovering = False
@dbus_property(access=PropertyAccess.READ)
def Name(self) -> "s": # noqa: F821, N802
return self._name
@dbus_property()
def Powered(self) -> "b": # noqa: F821, N802
return self._powered
@Powered.setter
def Powered_setter(self, state: "b"): # noqa: F821, N802
self._powered = state
self.emit_properties_changed({"Powered": state})
@dbus_property(access=PropertyAccess.READ)
def Discovering(self) -> "b": # noqa: F821, N802
return self._discovering
@method()
def StartDiscovery(self): # noqa: F821, N802
self._discovering = True
self.emit_properties_changed({"Discovering": self._discovering})
@method()
def StopDiscovery(self): # noqa: F821, N802
self._discovering = False
self.emit_properties_changed({"Discovering": self._discovering})
class Battery(ServiceInterface):
@dbus_property(PropertyAccess.READ)
def Percentage(self) -> "d": # noqa: F821, N802
return 75
class QtileRoot(ServiceInterface):
def __init__(self):
super().__init__("org.qtile.root")
class Bluez:
"""Class that runs fake UPower interface."""
async def start_server(self):
"""Connects to the bus and publishes 3 interfaces."""
bus = await MessageBus().connect()
root = QtileRoot()
bus.export("/", root)
unpaired_device = Device(
BLUEZ_DEVICE,
alias="Earbuds",
state=DeviceState.UNPAIRED,
address="11",
adapter=ADAPTER_PATH,
)
paired_device = Device(
BLUEZ_DEVICE,
alias="Headphones",
state=DeviceState.PAIRED,
address="22",
adapter=ADAPTER_PATH,
)
connected_device = Device(
BLUEZ_DEVICE,
alias="Speaker",
state=DeviceState.CONNECTED,
address="33",
adapter=ADAPTER_PATH,
)
battery = Battery(BLUEZ_BATTERY)
for d in [unpaired_device, paired_device, connected_device]:
path = f"{ADAPTER_PATH}/dev_{d._address.replace(':', '_')}"
bus.export(path, d)
if d is connected_device:
bus.export(path, battery)
adapter = Adapter(BLUEZ_ADAPTER)
bus.export(ADAPTER_PATH, adapter)
# Request the service name
await bus.request_name(BLUEZ_SERVICE)
await asyncio.get_event_loop().create_future()
def run(self):
loop = asyncio.new_event_loop()
loop.run_until_complete(self.start_server())
@pytest.fixture()
def fake_dbus_daemon(monkeypatch):
"""Start a thread which publishes a fake bluez interface on dbus."""
# for Github CI/Ubuntu, dbus-launch is provided by "dbus-x11" package
launcher = shutil.which("dbus-launch")
# If dbus-launch can't be found then tests will fail so we
# need to skip
if launcher is None:
pytest.skip("dbus-launch must be installed")
# dbus-launch prints two lines which should be set as
# environmental variables
result = subprocess.run(launcher, capture_output=True)
pid = None
for line in result.stdout.decode().splitlines():
# dbus server addresses can have multiple "=" so
# we use partition to split by the first one onle
var, _, val = line.partition("=")
# Use monkeypatch to set these variables so they are
# removed at end of test.
monkeypatch.setitem(os.environ, var, val)
# We want the pid so we can kill the process when the
# test is finished
if var == "DBUS_SESSION_BUS_PID":
try:
pid = int(val)
except ValueError:
pass
p = multiprocessing.Process(target=Bluez().run)
p.start()
# Pause for the dbus interface to come up
time.sleep(1)
yield
# Stop the bus
if pid:
os.kill(pid, signal.SIGTERM)
p.kill()
@pytest.fixture
def widget(monkeypatch):
"""Patch the widget to use the fake dbus service."""
monkeypatch.setattr("libqtile.widget.bluetooth.BLUEZ_SERVICE", BLUEZ_SERVICE)
# Make dbus_fast always return the session bus address even if system bus is requested
monkeypatch.setattr("libqtile.widget.bluetooth.BusType", ForceSessionBusType)
yield Bluetooth
@pytest.fixture
def bluetooth_manager(request, widget, fake_dbus_daemon, manager_nospawn):
class BluetoothConfig(BareConfig):
screens = [Screen(top=Bar([widget(**getattr(request, "param", dict()))], 20))]
manager_nospawn.start(BluetoothConfig)
yield manager_nospawn
@Retry(ignore_exceptions=(AssertionError,))
def wait_for_text(widget, text):
assert widget.info()["text"] == text
def test_defaults(bluetooth_manager):
widget = bluetooth_manager.c.widget["bluetooth"]
def text():
return widget.info()["text"]
def click():
bluetooth_manager.c.bar["top"].fake_button_press(0, 0, 1)
# Show prefix plus list of connected devices (1 connected at startup)
wait_for_text(widget, "BT Speaker")
widget.scroll_up()
assert text() == f"Adapter: {ADAPTER_NAME} [*]"
widget.scroll_up()
assert text() == "Device: Earbuds [?]"
widget.scroll_up()
assert text() == "Device: Headphones [-]"
widget.scroll_up()
assert text() == "Device: Speaker (75.0%) [*]"
widget.scroll_up()
assert text() == "BT Speaker"
widget.scroll_down()
widget.scroll_down()
assert text() == "Device: Headphones [-]"
def test_device_actions(bluetooth_manager):
widget = bluetooth_manager.c.widget["bluetooth"]
def text():
return widget.info()["text"]
def click():
bluetooth_manager.c.bar["top"].fake_button_press(0, 0, 1)
wait_for_text(widget, "BT Speaker")
widget.scroll_down()
widget.scroll_down()
wait_for_text(widget, "Device: Headphones [-]")
# Clicking a paired device connects it
click()
wait_for_text(widget, "Device: Headphones [*]")
# Clicking a connected device disconnects it
click()
wait_for_text(widget, "Device: Headphones [-]")
# We want it connected for the last check
click()
# Clicking an unpaired device pairs and connects it
widget.scroll_down()
click()
wait_for_text(widget, "Device: Earbuds [*]")
# Clicking this now disconnects it but it remains paired
click()
wait_for_text(widget, "Device: Earbuds [-]")
widget.scroll_down()
widget.scroll_down()
# 2 devices are now connected
assert text() == "BT Headphones, Speaker"
def test_adapter_actions(bluetooth_manager):
widget = bluetooth_manager.c.widget["bluetooth"]
def text():
return widget.info()["text"]
def click():
bluetooth_manager.c.bar["top"].fake_button_press(0, 0, 1)
wait_for_text(widget, "BT Speaker")
widget.scroll_up()
assert text() == f"Adapter: {ADAPTER_NAME} [*]"
click()
wait_for_text(widget, "Turn power off")
click()
wait_for_text(widget, "Turn power on")
widget.scroll_up()
assert text() == "Turn discovery on"
click()
wait_for_text(widget, "Turn discovery off")
click()
wait_for_text(widget, "Turn discovery on")
widget.scroll_up()
assert text() == "Exit"
click()
# Adapter power is now off
wait_for_text(widget, f"Adapter: {ADAPTER_NAME} [-]")
@pytest.mark.parametrize(
"bluetooth_manager",
[
{
"symbol_connected": "C",
"symbol_paired": "P",
"symbol_unknown": "U",
"symbol_powered": ("ON", "OFF"),
}
],
indirect=True,
)
def test_custom_symbols(bluetooth_manager):
widget = bluetooth_manager.c.widget["bluetooth"]
def text():
return widget.info()["text"]
def click():
bluetooth_manager.c.bar["top"].fake_button_press(0, 0, 1)
wait_for_text(widget, "BT Speaker")
widget.scroll_up()
assert text() == f"Adapter: {ADAPTER_NAME} [ON]"
click()
wait_for_text(widget, "Turn power off")
click()
widget.scroll_up()
widget.scroll_up()
click()
wait_for_text(widget, f"Adapter: {ADAPTER_NAME} [OFF]")
widget.scroll_up()
assert text() == "Device: Earbuds [U]"
widget.scroll_up()
assert text() == "Device: Headphones [P]"
widget.scroll_up()
assert text() == "Device: Speaker (75.0%) [C]"
@pytest.mark.parametrize("bluetooth_manager", [{"default_show_battery": True}], indirect=True)
def test_default_show_battery(bluetooth_manager):
widget = bluetooth_manager.c.widget["bluetooth"]
wait_for_text(widget, "BT Speaker (75.0%)")
@pytest.mark.parametrize(
"bluetooth_manager", [{"adapter_paths": ["/org/bluez/hci1"]}], indirect=True
)
def test_missing_adapter(bluetooth_manager):
widget = bluetooth_manager.c.widget["bluetooth"]
def text():
return widget.info()["text"]
wait_for_text(widget, "BT ")
# No adapter or devices should be listed
widget.scroll_up()
assert text() == "BT "
@pytest.mark.parametrize(
"bluetooth_manager",
[
{
"default_text": "BT {connected_devices} {num_connected_devices} {adapters} {num_adapters}"
}
],
indirect=True,
)
def test_default_text(bluetooth_manager):
widget = bluetooth_manager.c.widget["bluetooth"]
wait_for_text(widget, "BT Speaker 1 qtile_bluez 1")
@pytest.mark.parametrize(
"bluetooth_manager",
[
{"device": "/dev_22_22_22_22_22_22_22_22"},
],
indirect=True,
)
def test_default_device(bluetooth_manager):
widget = bluetooth_manager.c.widget["bluetooth"]
wait_for_text(widget, "Device: Headphones [-]")
|