2 # -*- coding: utf-8 -*-
3 # pylint: disable=missing-docstring
5 Test suite highly borrowed^Wsteal from python-mpd2 [0] project.
7 [0] https://github.com/Mic92/python-mpd2
21 import unittest.mock as mock
26 print("Please install mock from PyPI to run tests!")
29 # show deprecation warnings
30 warnings.simplefilter('default')
33 TEST_MPD_HOST, TEST_MPD_PORT = ('example.com', 10000)
36 class testEnvVar(unittest.TestCase):
38 def test_envvar(self):
39 # mock "os.path.exists" here to ensure there are no socket in
40 # XDG_RUNTIME_DIR/mpd or /run/mpd since with test defaults fallbacks
42 # * neither MPD_HOST nor XDG_RUNTIME_DIR are not set
43 # * /run/mpd does not expose a socket
44 with mock.patch('os.path.exists', return_value=False):
45 os.environ.pop('MPD_HOST', None)
46 os.environ.pop('MPD_PORT', None)
47 client = musicpd.MPDClient()
48 self.assertEqual(client.host, 'localhost')
49 self.assertEqual(client.port, '6600')
51 os.environ.pop('MPD_HOST', None)
52 os.environ['MPD_PORT'] = '6666'
53 client = musicpd.MPDClient()
54 self.assertEqual(client.pwd, None)
55 self.assertEqual(client.host, 'localhost')
56 self.assertEqual(client.port, '6666')
58 # Test password extraction
59 os.environ['MPD_HOST'] = 'pa55w04d@example.org'
60 client = musicpd.MPDClient()
61 self.assertEqual(client.pwd, 'pa55w04d')
62 self.assertEqual(client.host, 'example.org')
65 os.environ['MPD_HOST'] = 'example.org'
66 client = musicpd.MPDClient()
67 self.assertFalse(client.pwd)
68 self.assertEqual(client.host, 'example.org')
70 # Test password extraction (no host)
71 os.environ['MPD_HOST'] = 'pa55w04d@'
72 with mock.patch('os.path.exists', return_value=False):
73 client = musicpd.MPDClient()
74 self.assertEqual(client.pwd, 'pa55w04d')
75 self.assertEqual(client.host, 'localhost')
77 # Test badly formatted MPD_HOST
78 os.environ['MPD_HOST'] = '@'
79 with mock.patch('os.path.exists', return_value=False):
80 client = musicpd.MPDClient()
81 self.assertEqual(client.pwd, None)
82 self.assertEqual(client.host, 'localhost')
84 # Test unix socket extraction
85 os.environ['MPD_HOST'] = 'pa55w04d@/unix/sock'
86 client = musicpd.MPDClient()
87 self.assertEqual(client.host, '/unix/sock')
89 # Test plain abstract socket extraction
90 os.environ['MPD_HOST'] = '@abstract'
91 client = musicpd.MPDClient()
92 self.assertEqual(client.host, '@abstract')
94 # Test password and abstract socket extraction
95 os.environ['MPD_HOST'] = 'pass@@abstract'
96 client = musicpd.MPDClient()
97 self.assertEqual(client.pwd, 'pass')
98 self.assertEqual(client.host, '@abstract')
100 # Test unix socket fallback
101 os.environ.pop('MPD_HOST', None)
102 os.environ.pop('MPD_PORT', None)
103 os.environ.pop('XDG_RUNTIME_DIR', None)
104 with mock.patch('os.path.exists', return_value=True):
105 client = musicpd.MPDClient()
106 self.assertEqual(client.host, '/run/mpd/socket')
107 os.environ['XDG_RUNTIME_DIR'] = '/run/user/1000'
108 client = musicpd.MPDClient()
109 self.assertEqual(client.host, '/run/user/1000/mpd/socket')
111 os.environ.pop('MPD_HOST', None)
112 os.environ.pop('MPD_PORT', None)
113 os.environ['XDG_RUNTIME_DIR'] = '/run/user/1000/'
114 with mock.patch('os.path.exists', return_value=True):
115 client = musicpd.MPDClient()
116 self.assertEqual(client.host, '/run/user/1000/mpd/socket')
119 os.environ.pop('MPD_TIMEOUT', None)
120 client = musicpd.MPDClient()
121 self.assertEqual(client.mpd_timeout, musicpd.CONNECTION_TIMEOUT)
122 os.environ['MPD_TIMEOUT'] = 'garbage'
123 client = musicpd.MPDClient()
124 self.assertEqual(client.mpd_timeout,
125 musicpd.CONNECTION_TIMEOUT,
126 'Garbage\'s not silently ignore to use default value')
127 os.environ['MPD_TIMEOUT'] = '42'
128 client = musicpd.MPDClient()
129 self.assertEqual(client.mpd_timeout, 42)
132 class TestMPDClient(unittest.TestCase):
135 # last sync: musicpd 0.4.2 unreleased / Mon Nov 17 21:45:22 CET 2014
138 'clearerror': 'nothing',
139 'currentsong': 'object',
144 # Playback Option Commands
145 'consume': 'nothing',
146 'crossfade': 'nothing',
147 'mixrampdb': 'nothing',
148 'mixrampdelay': 'nothing',
153 'replay_gain_mode': 'nothing',
154 'replay_gain_status': 'item',
156 # Playback Control Commands
161 'previous': 'nothing',
164 'seekcur': 'nothing',
171 'deleteid': 'nothing',
174 'playlist': 'playlist',
175 'playlistfind': 'songs',
176 'playlistid': 'songs',
177 'playlistinfo': 'songs',
178 'playlistsearch': 'songs',
179 'plchanges': 'songs',
180 'plchangesposid': 'changes',
183 'rangeid': 'nothing',
184 'shuffle': 'nothing',
187 'addtagid': 'nothing',
188 'cleartagid': 'nothing',
189 # Stored Playlist Commands
190 'listplaylist': 'list',
191 'listplaylistinfo': 'songs',
192 'listplaylists': 'playlists',
194 'playlistadd': 'nothing',
195 'playlistclear': 'nothing',
196 'playlistdelete': 'nothing',
197 'playlistmove': 'nothing',
204 'findadd': 'nothing',
206 'listall': 'database',
207 'listallinfo': 'database',
208 'lsinfo': 'database',
210 'searchadd': 'nothing',
211 'searchaddpl': 'nothing',
214 'readcomments': 'object',
215 # Mounts and neighbors
217 'unmount': 'nothing',
218 'listmounts': 'mounts',
219 'listneighbors': 'neighbors',
221 'sticker get': 'item',
222 'sticker set': 'nothing',
223 'sticker delete': 'nothing',
224 'sticker list': 'list',
225 'sticker find': 'songs',
226 # Connection Commands
229 'password': 'nothing',
232 'partition': 'nothing',
233 'listpartitions': 'list',
234 'newpartition': 'nothing',
235 # Audio Output Commands
236 'disableoutput': 'nothing',
237 'enableoutput': 'nothing',
238 'toggleoutput': 'nothing',
239 'outputs': 'outputs',
240 # Reflection Commands
243 'notcommands': 'list',
245 'urlhandlers': 'list',
246 'decoders': 'plugins',
248 'subscribe': 'nothing',
249 'unsubscribe': 'nothing',
251 'readmessages': 'messages',
252 'sendmessage': 'nothing',
256 self.socket_patch = mock.patch('musicpd.socket')
257 self.socket_mock = self.socket_patch.start()
258 self.socket_mock.getaddrinfo.return_value = [range(5)]
260 self.socket_mock.socket.side_effect = (
262 # Create a new socket.socket() mock with default attributes,
263 # each time we are calling it back (otherwise, it keeps set
264 # attributes across calls).
265 # That's probably what we want, since reconnecting is like
266 # reinitializing the entire connection, and so, the mock.
267 mock.MagicMock(name='socket.socket'))
269 self.client = musicpd.MPDClient()
270 self.client.connect(TEST_MPD_HOST, TEST_MPD_PORT)
271 self.client._sock.reset_mock()
272 self.MPDWillReturn('ACK don\'t forget to setup your mock\n')
275 self.socket_patch.stop()
277 def MPDWillReturn(self, *lines):
278 # Return what the caller wants first, then do as if the socket was
280 self.client._rfile.readline.side_effect = itertools.chain(
281 lines, itertools.repeat(''))
283 def MPDWillReturnBinary(self, lines):
284 data = bytearray(b''.join(lines))
292 val.append(data.pop(0))
297 while not val.endswith(b'\x0a'):
298 val.append(data.pop(0))
300 self.client._rbfile.readline.side_effect = readline
301 self.client._rbfile.read.side_effect = read
303 def assertMPDReceived(self, *lines):
304 self.client._wfile.write.assert_called_with(*lines)
306 def test_metaclass_commands(self):
307 """Controls client has at least commands as last synchronized in
308 TestMPDClient.commands"""
309 for cmd, ret in TestMPDClient.commands.items():
310 self.assertTrue(hasattr(self.client, cmd), msg='cmd "{}" not available!'.format(cmd))
312 self.assertTrue(hasattr(self.client, cmd.replace(' ', '_')))
314 def test_fetch_nothing(self):
315 self.MPDWillReturn('OK\n')
316 self.assertIsNone(self.client.ping())
317 self.assertMPDReceived('ping\n')
319 def test_fetch_list(self):
320 self.MPDWillReturn('OK\n')
321 self.assertIsInstance(self.client.list('album'), list)
322 self.assertMPDReceived('list "album"\n')
324 def test_fetch_item(self):
325 self.MPDWillReturn('updating_db: 42\n', 'OK\n')
326 self.assertIsNotNone(self.client.update())
328 def test_fetch_object(self):
329 # XXX: _read_objects() doesn't wait for the final OK
330 self.MPDWillReturn('volume: 63\n', 'OK\n')
331 status = self.client.status()
332 self.assertMPDReceived('status\n')
333 self.assertIsInstance(status, dict)
335 # XXX: _read_objects() doesn't wait for the final OK
336 self.MPDWillReturn('OK\n')
337 stats = self.client.stats()
338 self.assertMPDReceived('stats\n')
339 self.assertIsInstance(stats, dict)
341 def test_fetch_songs(self):
342 self.MPDWillReturn('file: my-song.ogg\n', 'Pos: 0\n', 'Id: 66\n', 'OK\n')
343 playlist = self.client.playlistinfo()
345 self.assertMPDReceived('playlistinfo\n')
346 self.assertIsInstance(playlist, list)
347 self.assertEqual(1, len(playlist))
349 self.assertIsInstance(e, dict)
350 self.assertEqual('my-song.ogg', e['file'])
351 self.assertEqual('0', e['pos'])
352 self.assertEqual('66', e['id'])
354 def test_send_and_fetch(self):
355 self.MPDWillReturn('volume: 50\n', 'OK\n')
356 result = self.client.send_status()
357 self.assertEqual(None, result)
358 self.assertMPDReceived('status\n')
360 status = self.client.fetch_status()
361 self.assertEqual(1, self.client._wfile.write.call_count)
362 self.assertEqual({'volume': '50'}, status)
364 def test_iterating(self):
365 self.MPDWillReturn('file: my-song.ogg\n', 'Pos: 0\n', 'Id: 66\n',
366 'file: my-song.ogg\n', 'Pos: 0\n', 'Id: 66\n', 'OK\n')
367 self.client.iterate = True
368 playlist = self.client.playlistinfo()
369 self.assertMPDReceived('playlistinfo\n')
370 self.assertIsInstance(playlist, types.GeneratorType)
371 self.assertTrue(self.client._iterating)
372 for song in playlist:
373 self.assertRaises(musicpd.IteratingError, self.client.status)
374 self.assertIsInstance(song, dict)
375 self.assertEqual('my-song.ogg', song['file'])
376 self.assertEqual('0', song['pos'])
377 self.assertEqual('66', song['id'])
378 self.assertFalse(self.client._iterating)
380 def test_noidle(self):
381 self.MPDWillReturn('OK\n') # nothing changed after idle-ing
382 self.client.send_idle()
383 self.MPDWillReturn('OK\n') # nothing changed after noidle
384 self.assertEqual(self.client.noidle(), [])
385 self.assertMPDReceived('noidle\n')
386 self.MPDWillReturn('volume: 50\n', 'OK\n')
388 self.assertMPDReceived('status\n')
390 def test_noidle_while_idle_started_sending(self):
391 self.MPDWillReturn('OK\n') # nothing changed after idle
392 self.client.send_idle()
393 self.MPDWillReturn('CHANGED: player\n', 'OK\n') # noidle response
394 self.assertEqual(self.client.noidle(), ['player'])
395 self.MPDWillReturn('volume: 50\n', 'OK\n')
396 status = self.client.status()
397 self.assertMPDReceived('status\n')
398 self.assertEqual({'volume': '50'}, status)
400 def test_throw_when_calling_noidle_withoutidling(self):
401 self.assertRaises(musicpd.CommandError, self.client.noidle)
402 self.client.send_status()
403 self.assertRaises(musicpd.CommandError, self.client.noidle)
405 def test_client_to_client(self):
406 # client to client is at this time in beta!
408 self.MPDWillReturn('OK\n')
409 self.assertIsNone(self.client.subscribe("monty"))
410 self.assertMPDReceived('subscribe "monty"\n')
412 self.MPDWillReturn('channel: monty\n', 'OK\n')
413 channels = self.client.channels()
414 self.assertMPDReceived('channels\n')
415 self.assertEqual(['monty'], channels)
417 self.MPDWillReturn('OK\n')
418 self.assertIsNone(self.client.sendmessage('monty', 'SPAM'))
419 self.assertMPDReceived('sendmessage "monty" "SPAM"\n')
421 self.MPDWillReturn('channel: monty\n', 'message: SPAM\n', 'OK\n')
422 msg = self.client.readmessages()
423 self.assertMPDReceived('readmessages\n')
424 self.assertEqual(msg, [{'channel': 'monty', 'message': 'SPAM'}])
426 self.MPDWillReturn('OK\n')
427 self.assertIsNone(self.client.unsubscribe('monty'))
428 self.assertMPDReceived('unsubscribe "monty"\n')
430 self.MPDWillReturn('OK\n')
431 channels = self.client.channels()
432 self.assertMPDReceived('channels\n')
433 self.assertEqual([], channels)
435 def test_ranges_in_command_args(self):
436 self.MPDWillReturn('OK\n')
437 self.client.playlistinfo((10,))
438 self.assertMPDReceived('playlistinfo 10:\n')
440 self.MPDWillReturn('OK\n')
441 self.client.playlistinfo(('10',))
442 self.assertMPDReceived('playlistinfo 10:\n')
444 self.MPDWillReturn('OK\n')
445 self.client.playlistinfo((10, 12))
446 self.assertMPDReceived('playlistinfo 10:12\n')
448 self.MPDWillReturn('OK\n')
449 self.client.rangeid(())
450 self.assertMPDReceived('rangeid :\n')
452 for arg in [(10, 't'), (10, 1, 1), (None,1)]:
453 self.MPDWillReturn('OK\n')
454 with self.assertRaises(musicpd.CommandError):
455 self.client.playlistinfo(arg)
457 def test_numbers_as_command_args(self):
458 self.MPDWillReturn('OK\n')
459 self.client.find('file', 1)
460 self.assertMPDReceived('find "file" "1"\n')
462 def test_commands_without_callbacks(self):
463 self.MPDWillReturn('\n')
465 self.assertMPDReceived('close\n')
467 # XXX: what are we testing here?
469 self.client.connect(TEST_MPD_HOST, TEST_MPD_PORT)
471 def test_connection_lost(self):
472 # Simulate a connection lost: the socket returns empty strings
473 self.MPDWillReturn('')
475 with self.assertRaises(musicpd.ConnectionError):
478 # consistent behaviour
479 # solves <https://github.com/Mic92/python-mpd2/issues/11> (also present
481 with self.assertRaises(musicpd.ConnectionError):
484 self.assertIs(self.client._sock, None)
486 def test_parse_sticker_get_no_sticker(self):
487 self.MPDWillReturn('ACK [50@0] {sticker} no such sticker\n')
488 self.assertRaises(musicpd.CommandError,
489 self.client.sticker_get, 'song', 'baz', 'foo')
491 def test_parse_sticker_list(self):
492 self.MPDWillReturn('sticker: foo=bar\n', 'sticker: lom=bok\n', 'OK\n')
493 res = self.client.sticker_list('song', 'baz')
494 self.assertEqual(['foo=bar', 'lom=bok'], res)
496 # Even with only one sticker, we get a dict
497 self.MPDWillReturn('sticker: foo=bar\n', 'OK\n')
498 res = self.client.sticker_list('song', 'baz')
499 self.assertEqual(['foo=bar'], res)
501 def test_albumart(self):
502 # here is a 34 bytes long data
503 data = bytes('\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01'
504 '\x00\x01\x00\x00\xff\xdb\x00C\x00\x05\x03\x04',
506 read_lines = [b'size: 42\nbinary: 34\n', data, b'\nOK\n']
507 self.MPDWillReturnBinary(read_lines)
508 # Reading albumart / offset 0 should return the data
509 res = self.client.albumart('muse/Raised Fist/2002-Dedication/', 0)
510 self.assertEqual(res.get('data'), data)
512 def test_command_list(self):
513 self.MPDWillReturn('updating_db: 42\n',
520 self.client.command_list_ok_begin()
523 self.client.repeat(1)
524 self.client.command_list_end()
525 self.assertMPDReceived('command_list_end\n')
528 if __name__ == '__main__':