vendetta / tests / mpris_test.py
180 lines · 153 sloc · 6.88 KB · d81505db14fa82ca3fd312aab073a648c7b38fbc
Raw
1#!/usr/bin/env python3
2"""Run with: dbus-run-session -- python3 tests/mpris_test.py [path/to/v].
3
4Uses a private bus, the real MPRIS worker and libdbus, without a player window.
5"""
6
7import os
8from pathlib import Path
9import select
10import shutil
11import subprocess
12import sys
13import tempfile
14import time
15
16ROOT = Path(__file__).resolve().parents[1]
17DEST = "org.mpris.MediaPlayer2.vendetta"
18PATH = "/org/mpris/MediaPlayer2"
19PLAYER = "org.mpris.MediaPlayer2.Player"
20
21
22def call(method, *args, path=PATH):
23 return subprocess.run(
24 ["dbus-send", "--session", "--print-reply", "--reply-timeout=1000",
25 f"--dest={DEST}", path, method, *args],
26 capture_output=True, text=True, timeout=3,
27 )
28
29
30def get_all():
31 return call("org.freedesktop.DBus.Properties.GetAll", f"string:{PLAYER}")
32
33
34def eventually(predicate):
35 deadline = time.monotonic() + 8
36 while time.monotonic() < deadline:
37 if predicate():
38 return
39 time.sleep(0.05)
40 raise AssertionError("Timed out waiting for MPRIS state")
41
42
43def line(process):
44 assert select.select([process.stdout], [], [], 8)[0], "Host stopped responding"
45 result = process.stdout.readline().strip()
46 assert result, f"Host exited: {process.poll()}"
47 return result
48
49
50def control(process, command):
51 process.stdin.write(command + "\n")
52 process.stdin.flush()
53 assert line(process) == "done"
54
55
56def stop(process):
57 process.stdin.write("quit\n")
58 process.stdin.flush()
59 assert line(process) == "stopped"
60 assert process.wait(timeout=5) == 0
61
62
63def main():
64 assert os.environ.get("DBUS_SESSION_BUS_ADDRESS"), "Run inside dbus-run-session"
65 with tempfile.TemporaryDirectory(prefix="vendetta-mpris-") as directory:
66 directory = Path(directory)
67 shutil.copy(ROOT / "src/mpris_d_mpris.v", directory)
68 shutil.copy(ROOT / "tests/mpris_host.v", directory / "main.v")
69 executable = directory / "host"
70 subprocess.run(
71 [sys.argv[1] if len(sys.argv) > 1 else "v", "-d", "mpris",
72 "-d", "ui2_custom_rendering", "-path", f"{ROOT}|@vlib|@vmodules",
73 "-o", str(executable), str(directory)], check=True,
74 )
75 hosts = []
76 try:
77 def start():
78 host = subprocess.Popen([str(executable)], stdin=subprocess.PIPE,
79 stdout=subprocess.PIPE, text=True, bufsize=1)
80 hosts.append(host)
81 assert line(host) == "ready"
82 return host
83
84 first = start()
85 eventually(lambda: get_all().returncode == 0)
86 result = get_all()
87 assert 'string "Test track"' in result.stdout, result.stdout
88 assert 'string "None"' in result.stdout, result.stdout
89 result = call("org.freedesktop.DBus.Introspectable.Introspect")
90 assert result.returncode == 0 and PLAYER in result.stdout, result.stderr
91
92 # Signature checks must reject malformed calls without queuing them.
93 for method, args in [
94 (f"{PLAYER}.Seek", ["string:bad"]),
95 (f"{PLAYER}.SetPosition", ["string:bad", "int64:0"]),
96 (f"{PLAYER}.Pause", ["int64:0"]),
97 ("org.freedesktop.DBus.Properties.Get", [f"string:{PLAYER}"]),
98 ("org.freedesktop.DBus.Properties.Set", [f"string:{PLAYER}", "string:Rate", "variant:double:nan"]),
99 ("org.freedesktop.DBus.Properties.Set", [f"string:{PLAYER}", "string:Volume", "variant:double:inf"]),
100 ]:
101 result = call(method, *args)
102 assert "InvalidArgs" in result.stderr, result
103 result = call("org.freedesktop.DBus.Properties.GetAll", f"string:{PLAYER}", path="/wrong")
104 assert result.returncode != 0
105
106 # Fill the UI queue, then ensure the bus still answers reads and quit.
107 control(first, "fill")
108 result = call(f"{PLAYER}.Pause")
109 assert "LimitsExceeded" in result.stderr, result
110 assert get_all().returncode == 0
111
112 monitor = subprocess.Popen(
113 ["dbus-monitor", "--session", "type='signal',interface='org.mpris.MediaPlayer2.Player',member='Seeked'"],
114 stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
115 )
116 try:
117 time.sleep(0.2)
118 control(first, "seek")
119 time.sleep(0.2)
120 monitor.terminate()
121 output, _ = monitor.communicate(timeout=3)
122 assert "int64 1250000" in output and "variant" not in output, output
123 finally:
124 if monitor.poll() is None:
125 monitor.kill()
126 monitor.wait()
127
128 for _ in range(3):
129 control(first, "off")
130 eventually(lambda: get_all().returncode != 0)
131 control(first, "on")
132 eventually(lambda: get_all().returncode == 0)
133
134 # A second instance must recover when the first releases the name.
135 second = start()
136 control(first, "off")
137 eventually(lambda: get_all().returncode == 0)
138 stop(first)
139 assert get_all().returncode == 0
140 stop(second)
141 eventually(lambda: get_all().returncode != 0)
142
143 # Restart a bus at the same address while the worker remains alive.
144 address = f"unix:path={directory / 'bus'}"
145 original_address = os.environ["DBUS_SESSION_BUS_ADDRESS"]
146 os.environ["DBUS_SESSION_BUS_ADDRESS"] = address
147 daemon = None
148 try:
149 def start_bus():
150 return subprocess.Popen(
151 ["dbus-daemon", "--session", "--nofork", "--nopidfile", f"--address={address}"],
152 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
153 )
154
155 daemon = start_bus()
156 third = start()
157 eventually(lambda: get_all().returncode == 0)
158 daemon.terminate()
159 daemon.wait(timeout=5)
160 eventually(lambda: get_all().returncode != 0)
161 assert third.poll() is None, "Bus loss terminated the worker host"
162 daemon = start_bus()
163 eventually(lambda: get_all().returncode == 0)
164 assert 'string "Test track"' in get_all().stdout
165 stop(third)
166 finally:
167 if daemon is not None and daemon.poll() is None:
168 daemon.terminate()
169 daemon.wait(timeout=5)
170 os.environ["DBUS_SESSION_BUS_ADDRESS"] = original_address
171 print("MPRIS checks passed: properties, signatures, overload, Seeked, toggles, ownership, bus recovery, shutdown")
172 finally:
173 for host in hosts:
174 if host.poll() is None:
175 host.kill()
176 host.wait(timeout=5)
177
178
179if __name__ == "__main__":
180 main()
181