Debian Codegraph @

test/plugins/test_bpd.py

raw
1 """Tests for BPD's implementation of the MPD protocol."""
2
3 import asyncio
4 import multiprocessing as mp
5 import os
6 import socket
7 import tempfile
8 import threading
9 import time
10 import unittest
11 from contextlib import contextmanager
12 from typing import ClassVar
13 from unittest.mock import MagicMock, patch
14
15 import confuse
16 import pytest
17 import yaml
18
19 from beets.test.helper import PluginTestCase
20
21 bpd = pytest.importorskip("beetsplug.bpd", exc_type=ImportError)
22
23 if hasattr(mp, "set_start_method"):
24 try:
25 mp.set_start_method("fork", force=True)
26 except RuntimeError:
27 # Already set, which is fine
28 pass
29
30
31 class CommandParseTest(unittest.TestCase):
32 def test_no_args(self):
33 s = r"command"
34 c = bpd.Command(s)
35 assert c.name == "command"
36 assert c.args == []
37
38 def test_one_unquoted_arg(self):
39 s = r"command hello"
40 c = bpd.Command(s)
41 assert c.name == "command"
42 assert c.args == ["hello"]
43
44 def test_two_unquoted_args(self):
45 s = r"command hello there"
46 c = bpd.Command(s)
47 assert c.name == "command"
48 assert c.args == ["hello", "there"]
49
50 def test_one_quoted_arg(self):
51 s = r'command "hello there"'
52 c = bpd.Command(s)
53 assert c.name == "command"
54 assert c.args == ["hello there"]
55
56 def test_heterogenous_args(self):
57 s = r'command "hello there" sir'
58 c = bpd.Command(s)
59 assert c.name == "command"
60 assert c.args == ["hello there", "sir"]
61
62 def test_quote_in_arg(self):
63 s = r'command "hello \" there"'
64 c = bpd.Command(s)
65 assert c.args == ['hello " there']
66
67 def test_backslash_in_arg(self):
68 s = r'command "hello \\ there"'
69 c = bpd.Command(s)
70 assert c.args == ["hello \\ there"]
71
72
73 class MPCResponse:
74 def __init__(self, raw_response):
75 body = b"\n".join(raw_response.split(b"\n")[:-2]).decode("utf-8")
76 self.data = self._parse_body(body)
77 status = raw_response.split(b"\n")[-2].decode("utf-8")
78 self.ok, self.err_data = self._parse_status(status)
79
80 def _parse_status(self, status):
81 """Parses the first response line, which contains the status."""
82 if status.startswith(("OK", "list_OK")):
83 return True, None
84 if status.startswith("ACK"):
85 code, rest = status[5:].split("@", 1)
86 pos, rest = rest.split("]", 1)
87 cmd, rest = rest[2:].split("}")
88 return False, (int(code), int(pos), cmd, rest[1:])
89 raise RuntimeError(f"Unexpected status: {status!r}")
90
91 def _parse_body(self, body):
92 """Messages are generally in the format "header: content".
93 Convert them into a dict, storing the values for repeated headers as
94 lists of strings, and non-repeated ones as string.
95 """
96 data = {}
97 repeated_headers = set()
98 for line in body.split("\n"):
99 if not line:
100 continue
101 if ":" not in line:
102 raise RuntimeError(f"Unexpected line: {line!r}")
103 header, content = line.split(":", 1)
104 content = content.lstrip()
105 if header in repeated_headers:
106 data[header].append(content)
107 elif header in data:
108 data[header] = [data[header], content]
109 repeated_headers.add(header)
110 else:
111 data[header] = content
112 return data
113
114
115 class MPCClient:
116 def __init__(self, sock, do_hello=True):
117 self.sock = sock
118 self.buf = b""
119 if do_hello:
120 hello = self.get_response()
121 if not hello.ok:
122 raise RuntimeError("Bad hello")
123
124 def get_response(self, force_multi=None):
125 """Wait for a full server response and wrap it in a helper class.
126 If the request was a batch request then this will return a list of
127 `MPCResponse`s, one for each processed subcommand.
128 """
129
130 response = b""
131 responses = []
132 while True:
133 line = self.readline()
134 response += line
135 if line.startswith((b"OK", b"ACK")):
136 if force_multi or any(responses):
137 if line.startswith(b"ACK"):
138 responses.append(MPCResponse(response))
139 n_remaining = force_multi - len(responses)
140 responses.extend([None] * n_remaining)
141 return responses
142 return MPCResponse(response)
143 if line.startswith(b"list_OK"):
144 responses.append(MPCResponse(response))
145 response = b""
146 elif not line:
147 raise RuntimeError(f"Unexpected response: {line!r}")
148
149 def serialise_command(self, command, *args):
150 cmd = [command.encode("utf-8")]
151 for arg in [a.encode("utf-8") for a in args]:
152 if b" " in arg:
153 cmd.append(b'"' + arg + b'"')
154 else:
155 cmd.append(arg)
156 return b" ".join(cmd) + b"\n"
157
158 def send_command(self, command, *args):
159 request = self.serialise_command(command, *args)
160 self.sock.sendall(request)
161 return self.get_response()
162
163 def send_commands(self, *commands):
164 """Use MPD command batching to send multiple commands at once.
165 Each item of commands is a tuple containing a command followed by
166 any arguments.
167 """
168
169 requests = []
170 for command_and_args in commands:
171 command = command_and_args[0]
172 args = command_and_args[1:]
173 requests.append(self.serialise_command(command, *args))
174 requests.insert(0, b"command_list_ok_begin\n")
175 requests.append(b"command_list_end\n")
176 request = b"".join(requests)
177 self.sock.sendall(request)
178 return self.get_response(force_multi=len(commands))
179
180 def readline(self, terminator=b"\n", bufsize=1024):
181 """Reads a line of data from the socket."""
182
183 while True:
184 if terminator in self.buf:
185 line, self.buf = self.buf.split(terminator, 1)
186 line += terminator
187 return line
188 self.sock.settimeout(1)
189 data = self.sock.recv(bufsize)
190 if data:
191 self.buf += data
192 else:
193 line = self.buf
194 self.buf = b""
195 return line
196
197
198 def implements(commands, fail=False):
199 def _test(self):
200 with self.run_bpd() as client:
201 response = client.send_command("commands")
202 self._assert_ok(response)
203 implemented = response.data["command"]
204 assert commands.intersection(implemented) == commands
205
206 return unittest.expectedFailure(_test) if fail else _test
207
208
209 class MemoryStreamWriter:
210 """Capture writes and optionally hold them at the drain boundary."""
211
212 def __init__(self, block_drain=False):
213 self.data = bytearray()
214 self.drain_started = asyncio.Event()
215 self.can_drain = asyncio.Event()
216 if not block_drain:
217 self.can_drain.set()
218
219 def get_extra_info(self, name):
220 return ("localhost", 6600) if name == "peername" else None
221
222 def write(self, data):
223 self.data.extend(data)
224
225 async def drain(self):
226 self.drain_started.set()
227 await self.can_drain.wait()
228
229
230 class AsyncServerTest(unittest.TestCase):
231 def test_dispatch_events_sends_one_notification_at_a_time(self):
232 async def exercise():
233 server = bpd.BaseServer("localhost", 0, None, 0, MagicMock())
234 writer = MemoryStreamWriter(block_drain=True)
235 conn = bpd.MPDConnection(server, asyncio.StreamReader(), writer)
236 conn.notifications.add("player")
237 conn.idle_subscriptions.add("player")
238 server.connect(conn)
239
240 server.dispatch_events()
241 await writer.drain_started.wait()
242 server.dispatch_events()
243 await asyncio.sleep(0)
244 tasks = tuple(server._notification_tasks.values())
245
246 writer.can_drain.set()
247 await asyncio.gather(*tasks)
248
249 assert bytes(writer.data) == b"changed: player\nOK\n"
250
251 asyncio.run(exercise())
252
253 def test_dispatch_events_sends_event_queued_while_task_finishes(self):
254 async def exercise():
255 server = bpd.BaseServer("localhost", 0, None, 0, MagicMock())
256 writer = MemoryStreamWriter()
257 conn = bpd.MPDConnection(server, asyncio.StreamReader(), writer)
258 conn.idle_subscriptions.add("player")
259 server.connect(conn)
260
261 server.dispatch_events()
262 await asyncio.sleep(0)
263 conn.notify("player")
264 server.dispatch_events()
265 await asyncio.sleep(0)
266 await asyncio.gather(*server._notification_tasks.values())
267
268 assert bytes(writer.data) == b"changed: player\nOK\n"
269
270 asyncio.run(exercise())
271
272 def test_idle_error_disconnects_client(self):
273 async def exercise():
274 server = bpd.BaseServer("localhost", 0, None, 0, MagicMock())
275 reader = asyncio.StreamReader()
276 reader.feed_data(b"idle\nnotacommand\n")
277 reader.feed_eof()
278 conn = bpd.MPDConnection(server, reader, MemoryStreamWriter())
279
280 await conn.run()
281
282 assert conn not in server.connections
283
284 asyncio.run(exercise())
285
286
287 asyncio_start_server = asyncio.start_server
288
289
290 @patch("beetsplug.bpd.asyncio.start_server")
291 def start_server(args, assigned_port, start_server_patch):
292 """Start the bpd server, writing the port to `assigned_port`."""
293
294 async def start_server_wrap(callback, host, port, **kwargs):
295 """Start an asyncio server and report its assigned port."""
296 # `asyncio.start_server` has previously been saved because this
297 # function replaces it at its original location.
298 server = await asyncio_start_server(callback, host, port, **kwargs)
299 # Read the port assigned by the OS.
300 assigned_port.put_nowait(server.sockets[0].getsockname()[1])
301 return server
302
303 start_server_patch.side_effect = start_server_wrap
304
305 import beets.ui
306
307 beets.ui.main(args)
308
309
310 class BPDTestHelper(PluginTestCase):
311 db_on_disk = True
312 plugin = "bpd"
313
314 def setUp(self):
315 super().setUp()
316 self.item1 = self.add_item(
317 title="Track One Title",
318 track=1,
319 album="Album Title",
320 artist="Artist Name",
321 )
322 self.item2 = self.add_item(
323 title="Track Two Title",
324 track=2,
325 album="Album Title",
326 artist="Artist Name",
327 )
328 self.lib.add_album([self.item1, self.item2])
329
330 @contextmanager
331 def run_bpd(
332 self,
333 host="localhost",
334 password=None,
335 do_hello=True,
336 second_client=False,
337 ):
338 """Runs BPD in another process, configured with the same library
339 database as we created in the setUp method. Exposes a client that is
340 connected to the server, and kills the server at the end.
341 """
342 # Create a config file:
343 config = {
344 "pluginpath": [str(self.temp_path)],
345 "plugins": "bpd",
346 # use port 0 to let the OS choose a free port
347 "bpd": {"host": host, "port": 0, "control_port": 0},
348 }
349 if password:
350 config["bpd"]["password"] = password
351 config_file = tempfile.NamedTemporaryFile(
352 mode="wb", dir=str(self.temp_path), suffix=".yaml", delete=False
353 )
354 config_file.write(
355 yaml.dump(config, Dumper=confuse.Dumper, encoding="utf-8")
356 )
357 config_file.close()
358
359 # Fork and launch BPD in the new process:
360 assigned_port = mp.Queue(2) # 2 slots, `control_port` and `port`
361 server = mp.Process(
362 target=start_server,
363 args=(
364 [
365 "--library",
366 self.config["library"].as_filename(),
367 "--directory",
368 str(self.lib_path),
369 "--config",
370 os.fsdecode(config_file.name),
371 "bpd",
372 ],
373 assigned_port,
374 ),
375 )
376 server.start()
377
378 try:
379 assigned_port.get(timeout=1) # skip control_port
380 port = assigned_port.get(timeout=0.5) # read port
381
382 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
383 try:
384 sock.connect((host, port))
385
386 if second_client:
387 sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
388 try:
389 sock2.connect((host, port))
390 yield (
391 MPCClient(sock, do_hello),
392 MPCClient(sock2, do_hello),
393 )
394 finally:
395 sock2.close()
396
397 else:
398 yield MPCClient(sock, do_hello)
399 finally:
400 sock.close()
401 finally:
402 server.terminate()
403 server.join(timeout=2) # give coverage time to write data
404 if server.is_alive():
405 server.kill() # force kill if still stuck (SIGKILL on POSIX)
406 server.join(timeout=2)
407
408 def _assert_ok(self, *responses):
409 for response in responses:
410 assert response is not None
411 assert response.ok, f"Response failed: {response.err_data}"
412
413 def _assert_failed(self, response, code, pos=None):
414 """Check that a command failed with a specific error code. If this
415 is a list of responses, first check all preceding commands were OK.
416 """
417 if pos is not None:
418 previous_commands = response[0:pos]
419 self._assert_ok(*previous_commands)
420 response = response[pos]
421 assert not response.ok
422 if pos is not None:
423 assert pos == response.err_data[1]
424 if code is not None:
425 assert code == response.err_data[0]
426
427 def _bpd_add(self, client, *items, **kwargs):
428 """Add the given item to the BPD playlist or queue."""
429 paths = [
430 os.fsdecode(item.destination(relative_to_libdir=True))
431 for item in items
432 ]
433 playlist = kwargs.get("playlist")
434 if playlist:
435 commands = [("playlistadd", playlist, path) for path in paths]
436 else:
437 commands = [("add", path) for path in paths]
438 responses = client.send_commands(*commands)
439 self._assert_ok(*responses)
440
441
442 class BPDTest(BPDTestHelper):
443 def test_server_hello(self):
444 with self.run_bpd(do_hello=False) as client:
445 assert client.readline() == b"OK MPD 0.16.0\n"
446
447 def test_unknown_cmd(self):
448 with self.run_bpd() as client:
449 response = client.send_command("notacommand")
450 self._assert_failed(response, bpd.ERROR_UNKNOWN)
451
452 def test_unexpected_argument(self):
453 with self.run_bpd() as client:
454 response = client.send_command("ping", "extra argument")
455 self._assert_failed(response, bpd.ERROR_ARG)
456
457 def test_missing_argument(self):
458 with self.run_bpd() as client:
459 response = client.send_command("add")
460 self._assert_failed(response, bpd.ERROR_ARG)
461
462 def test_system_error(self):
463 with self.run_bpd() as client:
464 response = client.send_command("crash")
465 self._assert_failed(response, bpd.ERROR_SYSTEM)
466
467 def test_empty_request(self):
468 with self.run_bpd() as client:
469 response = client.send_command("")
470 self._assert_failed(response, bpd.ERROR_UNKNOWN)
471
472
473 class BPDQueryTest(BPDTestHelper):
474 test_implements_query = implements({"clearerror"})
475
476 def test_cmd_currentsong(self):
477 with self.run_bpd() as client:
478 self._bpd_add(client, self.item1)
479 responses = client.send_commands(
480 ("play",), ("currentsong",), ("stop",), ("currentsong",)
481 )
482 self._assert_ok(*responses)
483 assert "1" == responses[1].data["Id"]
484 assert "Id" not in responses[3].data
485
486 def test_cmd_currentsong_tagtypes(self):
487 with self.run_bpd() as client:
488 self._bpd_add(client, self.item1)
489 responses = client.send_commands(("play",), ("currentsong",))
490 self._assert_ok(*responses)
491 assert BPDConnectionTest.TAGTYPES.union(BPDQueueTest.METADATA) == set(
492 responses[1].data.keys()
493 )
494
495 def test_cmd_status(self):
496 with self.run_bpd() as client:
497 self._bpd_add(client, self.item1, self.item2)
498 responses = client.send_commands(
499 ("status",), ("play",), ("status",)
500 )
501 self._assert_ok(*responses)
502 fields_not_playing = {
503 "repeat",
504 "random",
505 "single",
506 "consume",
507 "playlist",
508 "playlistlength",
509 "mixrampdb",
510 "state",
511 "volume",
512 }
513 assert fields_not_playing == set(responses[0].data.keys())
514 fields_playing = fields_not_playing | {
515 "song",
516 "songid",
517 "time",
518 "elapsed",
519 "bitrate",
520 "duration",
521 "audio",
522 "nextsong",
523 "nextsongid",
524 }
525 assert fields_playing == set(responses[2].data.keys())
526
527 def test_cmd_stats(self):
528 with self.run_bpd() as client:
529 response = client.send_command("stats")
530 self._assert_ok(response)
531 details = {
532 "artists",
533 "albums",
534 "songs",
535 "uptime",
536 "db_playtime",
537 "db_update",
538 "playtime",
539 }
540 assert details == set(response.data.keys())
541
542 def test_cmd_idle(self):
543 def _toggle(c):
544 for _ in range(3):
545 rs = c.send_commands(("play",), ("pause",))
546 # time.sleep(0.05) # uncomment if test is flaky
547 if any(not r.ok for r in rs):
548 raise RuntimeError("Toggler failed")
549
550 with self.run_bpd(second_client=True) as (client, client2):
551 self._bpd_add(client, self.item1, self.item2)
552 toggler = threading.Thread(target=_toggle, args=(client2,))
553 toggler.start()
554 # Idling will hang until the toggler thread changes the play state.
555 # Since the client sockets have a 1s timeout set at worst this will
556 # raise a socket.timeout and fail the test if the toggler thread
557 # manages to finish before the idle command is sent here.
558 response = client.send_command("idle", "player")
559 toggler.join()
560 self._assert_ok(response)
561
562 def test_cmd_idle_with_pending(self):
563 with self.run_bpd(second_client=True) as (client, client2):
564 response1 = client.send_command("random", "1")
565 response2 = client2.send_command("idle")
566 self._assert_ok(response1, response2)
567 assert "options" == response2.data["changed"]
568
569 def test_cmd_noidle(self):
570 with self.run_bpd() as client:
571 # Manually send a command without reading a response.
572 request = client.serialise_command("idle")
573 client.sock.sendall(request)
574 time.sleep(0.01)
575 response = client.send_command("noidle")
576 self._assert_ok(response)
577
578 def test_cmd_noidle_when_not_idle(self):
579 with self.run_bpd() as client:
580 # Manually send a command without reading a response.
581 request = client.serialise_command("noidle")
582 client.sock.sendall(request)
583 response = client.send_command("notacommand")
584 self._assert_failed(response, bpd.ERROR_UNKNOWN)
585
586
587 class BPDPlaybackTest(BPDTestHelper):
588 test_implements_playback = implements({"random"})
589
590 def test_cmd_consume(self):
591 with self.run_bpd() as client:
592 self._bpd_add(client, self.item1, self.item2)
593 responses = client.send_commands(
594 ("consume", "0"),
595 ("playlistinfo",),
596 ("next",),
597 ("playlistinfo",),
598 ("consume", "1"),
599 ("playlistinfo",),
600 ("play", "0"),
601 ("next",),
602 ("playlistinfo",),
603 ("status",),
604 )
605 self._assert_ok(*responses)
606 assert responses[1].data["Id"] == responses[3].data["Id"]
607 assert ["1", "2"] == responses[5].data["Id"]
608 assert "2" == responses[8].data["Id"]
609 assert "1" == responses[9].data["consume"]
610 assert "play" == responses[9].data["state"]
611
612 def test_cmd_consume_in_reverse(self):
613 with self.run_bpd() as client:
614 self._bpd_add(client, self.item1, self.item2)
615 responses = client.send_commands(
616 ("consume", "1"),
617 ("play", "1"),
618 ("playlistinfo",),
619 ("previous",),
620 ("playlistinfo",),
621 ("status",),
622 )
623 self._assert_ok(*responses)
624 assert ["1", "2"] == responses[2].data["Id"]
625 assert "1" == responses[4].data["Id"]
626 assert "play" == responses[5].data["state"]
627
628 def test_cmd_single(self):
629 with self.run_bpd() as client:
630 self._bpd_add(client, self.item1, self.item2)
631 responses = client.send_commands(
632 ("status",),
633 ("single", "1"),
634 ("play",),
635 ("status",),
636 ("next",),
637 ("status",),
638 )
639 self._assert_ok(*responses)
640 assert "0" == responses[0].data["single"]
641 assert "1" == responses[3].data["single"]
642 assert "play" == responses[3].data["state"]
643 assert "stop" == responses[5].data["state"]
644
645 def test_cmd_repeat(self):
646 with self.run_bpd() as client:
647 self._bpd_add(client, self.item1, self.item2)
648 responses = client.send_commands(
649 ("repeat", "1"),
650 ("play",),
651 ("currentsong",),
652 ("next",),
653 ("currentsong",),
654 ("next",),
655 ("currentsong",),
656 )
657 self._assert_ok(*responses)
658 assert "1" == responses[2].data["Id"]
659 assert "2" == responses[4].data["Id"]
660 assert "1" == responses[6].data["Id"]
661
662 def test_cmd_repeat_with_single(self):
663 with self.run_bpd() as client:
664 self._bpd_add(client, self.item1, self.item2)
665 responses = client.send_commands(
666 ("repeat", "1"),
667 ("single", "1"),
668 ("play",),
669 ("currentsong",),
670 ("next",),
671 ("status",),
672 ("currentsong",),
673 )
674 self._assert_ok(*responses)
675 assert "1" == responses[3].data["Id"]
676 assert "play" == responses[5].data["state"]
677 assert "1" == responses[6].data["Id"]
678
679 def test_cmd_repeat_in_reverse(self):
680 with self.run_bpd() as client:
681 self._bpd_add(client, self.item1, self.item2)
682 responses = client.send_commands(
683 ("repeat", "1"),
684 ("play",),
685 ("currentsong",),
686 ("previous",),
687 ("currentsong",),
688 )
689 self._assert_ok(*responses)
690 assert "1" == responses[2].data["Id"]
691 assert "2" == responses[4].data["Id"]
692
693 def test_cmd_repeat_with_single_in_reverse(self):
694 with self.run_bpd() as client:
695 self._bpd_add(client, self.item1, self.item2)
696 responses = client.send_commands(
697 ("repeat", "1"),
698 ("single", "1"),
699 ("play",),
700 ("currentsong",),
701 ("previous",),
702 ("status",),
703 ("currentsong",),
704 )
705 self._assert_ok(*responses)
706 assert "1" == responses[3].data["Id"]
707 assert "play" == responses[5].data["state"]
708 assert "1" == responses[6].data["Id"]
709
710 def test_cmd_crossfade(self):
711 with self.run_bpd() as client:
712 responses = client.send_commands(
713 ("status",),
714 ("crossfade", "123"),
715 ("status",),
716 ("crossfade", "-2"),
717 )
718 response = client.send_command("crossfade", "0.5")
719 self._assert_failed(responses, bpd.ERROR_ARG, pos=3)
720 self._assert_failed(response, bpd.ERROR_ARG)
721 assert "xfade" not in responses[0].data
722 assert 123 == pytest.approx(int(responses[2].data["xfade"]))
723
724 def test_cmd_mixrampdb(self):
725 with self.run_bpd() as client:
726 responses = client.send_commands(("mixrampdb", "-17"), ("status",))
727 self._assert_ok(*responses)
728 assert -17 == pytest.approx(float(responses[1].data["mixrampdb"]))
729
730 def test_cmd_mixrampdelay(self):
731 with self.run_bpd() as client:
732 responses = client.send_commands(
733 ("mixrampdelay", "2"),
734 ("status",),
735 ("mixrampdelay", "nan"),
736 ("status",),
737 ("mixrampdelay", "-2"),
738 )
739 self._assert_failed(responses, bpd.ERROR_ARG, pos=4)
740 assert 2 == pytest.approx(float(responses[1].data["mixrampdelay"]))
741 assert "mixrampdelay" not in responses[3].data
742
743 def test_cmd_setvol(self):
744 with self.run_bpd() as client:
745 responses = client.send_commands(
746 ("setvol", "67"),
747 ("status",),
748 ("setvol", "32"),
749 ("status",),
750 ("setvol", "101"),
751 )
752 self._assert_failed(responses, bpd.ERROR_ARG, pos=4)
753 assert "67" == responses[1].data["volume"]
754 assert "32" == responses[3].data["volume"]
755
756 def test_cmd_volume(self):
757 with self.run_bpd() as client:
758 responses = client.send_commands(
759 ("setvol", "10"), ("volume", "5"), ("volume", "-2"), ("status",)
760 )
761 self._assert_ok(*responses)
762 assert "13" == responses[3].data["volume"]
763
764 def test_cmd_replay_gain(self):
765 with self.run_bpd() as client:
766 responses = client.send_commands(
767 ("replay_gain_mode", "track"),
768 ("replay_gain_status",),
769 ("replay_gain_mode", "notanoption"),
770 )
771 self._assert_failed(responses, bpd.ERROR_ARG, pos=2)
772 assert "track" == responses[1].data["replay_gain_mode"]
773
774
775 class BPDControlTest(BPDTestHelper):
776 test_implements_control = implements(
777 {"seek", "seekid", "seekcur"}, fail=True
778 )
779
780 def test_cmd_play(self):
781 with self.run_bpd() as client:
782 self._bpd_add(client, self.item1, self.item2)
783 responses = client.send_commands(
784 ("status",),
785 ("play",),
786 ("status",),
787 ("play", "1"),
788 ("currentsong",),
789 )
790 self._assert_ok(*responses)
791 assert "stop" == responses[0].data["state"]
792 assert "play" == responses[2].data["state"]
793 assert "2" == responses[4].data["Id"]
794
795 def test_cmd_playid(self):
796 with self.run_bpd() as client:
797 self._bpd_add(client, self.item1, self.item2)
798 responses = client.send_commands(
799 ("playid", "2"), ("currentsong",), ("clear",)
800 )
801 self._bpd_add(client, self.item2, self.item1)
802 responses.extend(
803 client.send_commands(("playid", "2"), ("currentsong",))
804 )
805 self._assert_ok(*responses)
806 assert "2" == responses[1].data["Id"]
807 assert "2" == responses[4].data["Id"]
808
809 def test_cmd_pause(self):
810 with self.run_bpd() as client:
811 self._bpd_add(client, self.item1)
812 responses = client.send_commands(
813 ("play",), ("pause",), ("status",), ("currentsong",)
814 )
815 self._assert_ok(*responses)
816 assert "pause" == responses[2].data["state"]
817 assert "1" == responses[3].data["Id"]
818
819 def test_cmd_stop(self):
820 with self.run_bpd() as client:
821 self._bpd_add(client, self.item1)
822 responses = client.send_commands(
823 ("play",), ("stop",), ("status",), ("currentsong",)
824 )
825 self._assert_ok(*responses)
826 assert "stop" == responses[2].data["state"]
827 assert "Id" not in responses[3].data
828
829 def test_cmd_next(self):
830 with self.run_bpd() as client:
831 self._bpd_add(client, self.item1, self.item2)
832 responses = client.send_commands(
833 ("play",),
834 ("currentsong",),
835 ("next",),
836 ("currentsong",),
837 ("next",),
838 ("status",),
839 )
840 self._assert_ok(*responses)
841 assert "1" == responses[1].data["Id"]
842 assert "2" == responses[3].data["Id"]
843 assert "stop" == responses[5].data["state"]
844
845 def test_cmd_previous(self):
846 with self.run_bpd() as client:
847 self._bpd_add(client, self.item1, self.item2)
848 responses = client.send_commands(
849 ("play", "1"),
850 ("currentsong",),
851 ("previous",),
852 ("currentsong",),
853 ("previous",),
854 ("status",),
855 ("currentsong",),
856 )
857 self._assert_ok(*responses)
858 assert "2" == responses[1].data["Id"]
859 assert "1" == responses[3].data["Id"]
860 assert "play" == responses[5].data["state"]
861 assert "1" == responses[6].data["Id"]
862
863
864 class BPDQueueTest(BPDTestHelper):
865 test_implements_queue = implements(
866 {
867 "addid",
868 "clear",
869 "delete",
870 "deleteid",
871 "move",
872 "moveid",
873 "playlist",
874 "playlistfind",
875 "playlistsearch",
876 "plchanges",
877 "plchangesposid",
878 "prio",
879 "prioid",
880 "rangeid",
881 "shuffle",
882 "swap",
883 "swapid",
884 "addtagid",
885 "cleartagid",
886 },
887 fail=True,
888 )
889
890 METADATA: ClassVar[set[str]] = {"Pos", "Time", "Id", "file", "duration"}
891
892 def test_cmd_add(self):
893 with self.run_bpd() as client:
894 self._bpd_add(client, self.item1)
895
896 def test_cmd_playlistinfo(self):
897 with self.run_bpd() as client:
898 self._bpd_add(client, self.item1, self.item2)
899 responses = client.send_commands(
900 ("playlistinfo",),
901 ("playlistinfo", "0"),
902 ("playlistinfo", "0:2"),
903 ("playlistinfo", "200"),
904 )
905 self._assert_failed(responses, bpd.ERROR_ARG, pos=3)
906 assert "1" == responses[1].data["Id"]
907 assert ["1", "2"] == responses[2].data["Id"]
908
909 def test_cmd_playlistinfo_tagtypes(self):
910 with self.run_bpd() as client:
911 self._bpd_add(client, self.item1)
912 response = client.send_command("playlistinfo", "0")
913 self._assert_ok(response)
914 assert BPDConnectionTest.TAGTYPES.union(BPDQueueTest.METADATA) == set(
915 response.data.keys()
916 )
917
918 def test_cmd_playlistid(self):
919 with self.run_bpd() as client:
920 self._bpd_add(client, self.item1, self.item2)
921 responses = client.send_commands(
922 ("playlistid", "2"), ("playlistid",)
923 )
924 self._assert_ok(*responses)
925 assert "Track Two Title" == responses[0].data["Title"]
926 assert ["1", "2"] == responses[1].data["Track"]
927
928
929 class BPDPlaylistsTest(BPDTestHelper):
930 test_implements_playlists = implements({"playlistadd"})
931
932 def test_cmd_listplaylist(self):
933 with self.run_bpd() as client:
934 response = client.send_command("listplaylist", "anything")
935 self._assert_failed(response, bpd.ERROR_NO_EXIST)
936
937 def test_cmd_listplaylistinfo(self):
938 with self.run_bpd() as client:
939 response = client.send_command("listplaylistinfo", "anything")
940 self._assert_failed(response, bpd.ERROR_NO_EXIST)
941
942 def test_cmd_listplaylists(self):
943 with self.run_bpd() as client:
944 response = client.send_command("listplaylists")
945 self._assert_failed(response, bpd.ERROR_UNKNOWN)
946
947 def test_cmd_load(self):
948 with self.run_bpd() as client:
949 response = client.send_command("load", "anything")
950 self._assert_failed(response, bpd.ERROR_NO_EXIST)
951
952 @unittest.expectedFailure
953 def test_cmd_playlistadd(self):
954 with self.run_bpd() as client:
955 self._bpd_add(client, self.item1, playlist="anything")
956
957 def test_cmd_playlistclear(self):
958 with self.run_bpd() as client:
959 response = client.send_command("playlistclear", "anything")
960 self._assert_failed(response, bpd.ERROR_UNKNOWN)
961
962 def test_cmd_playlistdelete(self):
963 with self.run_bpd() as client:
964 response = client.send_command("playlistdelete", "anything", "0")
965 self._assert_failed(response, bpd.ERROR_UNKNOWN)
966
967 def test_cmd_playlistmove(self):
968 with self.run_bpd() as client:
969 response = client.send_command("playlistmove", "anything", "0", "1")
970 self._assert_failed(response, bpd.ERROR_UNKNOWN)
971
972 def test_cmd_rename(self):
973 with self.run_bpd() as client:
974 response = client.send_command("rename", "anything", "newname")
975 self._assert_failed(response, bpd.ERROR_UNKNOWN)
976
977 def test_cmd_rm(self):
978 with self.run_bpd() as client:
979 response = client.send_command("rm", "anything")
980 self._assert_failed(response, bpd.ERROR_UNKNOWN)
981
982 def test_cmd_save(self):
983 with self.run_bpd() as client:
984 self._bpd_add(client, self.item1)
985 response = client.send_command("save", "newplaylist")
986 self._assert_failed(response, bpd.ERROR_UNKNOWN)
987
988
989 class BPDDatabaseTest(BPDTestHelper):
990 test_implements_database = implements(
991 {
992 "albumart",
993 "find",
994 "findadd",
995 "listall",
996 "listallinfo",
997 "listfiles",
998 "readcomments",
999 "searchadd",
1000 "searchaddpl",
1001 "update",
1002 "rescan",
1003 },
1004 fail=True,
1005 )
1006
1007 def test_cmd_search(self):
1008 with self.run_bpd() as client:
1009 response = client.send_command("search", "track", "1")
1010 self._assert_ok(response)
1011 assert self.item1.title == response.data["Title"]
1012
1013 def test_cmd_search_any(self):
1014 with self.run_bpd() as client:
1015 response = client.send_command("search", "any", "1")
1016 self._assert_ok(response)
1017 assert self.item1.title == response.data["Title"]
1018
1019 def test_cmd_list(self):
1020 with self.run_bpd() as client:
1021 responses = client.send_commands(
1022 ("list", "album"),
1023 ("list", "track"),
1024 ("list", "album", "artist", "Artist Name", "track"),
1025 )
1026 self._assert_failed(responses, bpd.ERROR_ARG, pos=2)
1027 assert "Album Title" == responses[0].data["Album"]
1028 assert ["1", "2"] == responses[1].data["Track"]
1029
1030 def test_cmd_list_three_arg_form(self):
1031 with self.run_bpd() as client:
1032 responses = client.send_commands(
1033 ("list", "album", "artist", "Artist Name"),
1034 ("list", "album", "Artist Name"),
1035 ("list", "track", "Artist Name"),
1036 )
1037 self._assert_failed(responses, bpd.ERROR_ARG, pos=2)
1038 assert responses[0].data == responses[1].data
1039
1040 def test_cmd_lsinfo(self):
1041 with self.run_bpd() as client:
1042 response1 = client.send_command("lsinfo")
1043 self._assert_ok(response1)
1044 response2 = client.send_command(
1045 "lsinfo", response1.data["directory"]
1046 )
1047 self._assert_ok(response2)
1048 response3 = client.send_command(
1049 "lsinfo", response2.data["directory"]
1050 )
1051 self._assert_ok(response3)
1052 assert self.item1.title in response3.data["Title"]
1053
1054 def test_cmd_count(self):
1055 with self.run_bpd() as client:
1056 response = client.send_command("count", "track", "1")
1057 self._assert_ok(response)
1058 assert "1" == response.data["songs"]
1059 assert "0" == response.data["playtime"]
1060
1061
1062 class BPDMountsTest(BPDTestHelper):
1063 test_implements_mounts = implements(
1064 {"mount", "unmount", "listmounts", "listneighbors"}, fail=True
1065 )
1066
1067
1068 class BPDStickerTest(BPDTestHelper):
1069 test_implements_stickers = implements({"sticker"}, fail=True)
1070
1071
1072 class BPDConnectionTest(BPDTestHelper):
1073 test_implements_connection = implements({"close", "kill"})
1074
1075 ALL_MPD_TAGTYPES: ClassVar[set[str]] = {
1076 "Artist",
1077 "ArtistSort",
1078 "Album",
1079 "AlbumSort",
1080 "AlbumArtist",
1081 "AlbumArtistSort",
1082 "Title",
1083 "Track",
1084 "Name",
1085 "Genre",
1086 "Date",
1087 "Composer",
1088 "Performer",
1089 "Comment",
1090 "Disc",
1091 "Label",
1092 "OriginalDate",
1093 "MUSICBRAINZ_ARTISTID",
1094 "MUSICBRAINZ_ALBUMID",
1095 "MUSICBRAINZ_ALBUMARTISTID",
1096 "MUSICBRAINZ_TRACKID",
1097 "MUSICBRAINZ_RELEASETRACKID",
1098 "MUSICBRAINZ_WORKID",
1099 }
1100 UNSUPPORTED_TAGTYPES: ClassVar[set[str]] = {
1101 "MUSICBRAINZ_WORKID", # not tracked by beets
1102 "Performer", # not tracked by beets
1103 "AlbumSort", # not tracked by beets
1104 "Name", # junk field for internet radio
1105 }
1106 TAGTYPES = ALL_MPD_TAGTYPES.difference(UNSUPPORTED_TAGTYPES)
1107
1108 def test_cmd_password(self):
1109 with self.run_bpd(password="abc123") as client:
1110 response = client.send_command("status")
1111 self._assert_failed(response, bpd.ERROR_PERMISSION)
1112
1113 response = client.send_command("password", "wrong")
1114 self._assert_failed(response, bpd.ERROR_PASSWORD)
1115
1116 responses = client.send_commands(
1117 ("password", "abc123"), ("status",)
1118 )
1119 self._assert_ok(*responses)
1120
1121 def test_cmd_ping(self):
1122 with self.run_bpd() as client:
1123 response = client.send_command("ping")
1124 self._assert_ok(response)
1125
1126 def test_cmd_tagtypes(self):
1127 with self.run_bpd() as client:
1128 response = client.send_command("tagtypes")
1129 self._assert_ok(response)
1130 assert self.TAGTYPES == set(response.data["tagtype"])
1131
1132 @unittest.expectedFailure
1133 def test_tagtypes_mask(self):
1134 with self.run_bpd() as client:
1135 response = client.send_command("tagtypes", "clear")
1136 self._assert_ok(response)
1137
1138
1139 class BPDPartitionTest(BPDTestHelper):
1140 test_implements_partitions = implements(
1141 {"partition", "listpartitions", "newpartition"}, fail=True
1142 )
1143
1144
1145 class BPDDeviceTest(BPDTestHelper):
1146 test_implements_devices = implements(
1147 {"disableoutput", "enableoutput", "toggleoutput", "outputs"}, fail=True
1148 )
1149
1150
1151 class BPDReflectionTest(BPDTestHelper):
1152 test_implements_reflection = implements(
1153 {"config", "commands", "notcommands", "urlhandlers"}, fail=True
1154 )
1155
1156 @patch(
1157 "beetsplug.bpd.gstplayer.GstPlayer.get_decoders",
1158 MagicMock(return_value={"default": ({"audio/mpeg"}, {"mp3"})}),
1159 )
1160 def test_cmd_decoders(self):
1161 with self.run_bpd() as client:
1162 response = client.send_command("decoders")
1163 self._assert_ok(response)
1164 assert "default" == response.data["plugin"]
1165 assert "mp3" == response.data["suffix"]
1166 assert "audio/mpeg" == response.data["mime_type"]
1167
1168
1169 class BPDPeersTest(BPDTestHelper):
1170 test_implements_peers = implements(
1171 {"subscribe", "unsubscribe", "channels", "readmessages", "sendmessage"},
1172 fail=True,
1173 )