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')
64 # Test unix socket extraction
65 os.environ['MPD_HOST'] = 'pa55w04d@/unix/sock'
66 client = musicpd.MPDClient()
67 self.assertEqual(client.host, '/unix/sock')
69 # Test plain abstract socket extraction
70 os.environ['MPD_HOST'] = '@abstract'
71 client = musicpd.MPDClient()
72 self.assertEqual(client.host, '@abstract')
74 # Test password and abstract socket extraction
75 os.environ['MPD_HOST'] = 'pass@@abstract'
76 client = musicpd.MPDClient()
77 self.assertEqual(client.pwd, 'pass')
78 self.assertEqual(client.host, '@abstract')
80 # Test unix socket fallback
81 os.environ.pop('MPD_HOST', None)
82 os.environ.pop('MPD_PORT', None)
83 os.environ.pop('XDG_RUNTIME_DIR', None)
84 with mock.patch('os.path.exists', return_value=True):
85 client = musicpd.MPDClient()
86 self.assertEqual(client.host, '/run/mpd/socket')
87 os.environ['XDG_RUNTIME_DIR'] = '/run/user/1000'
88 client = musicpd.MPDClient()
89 self.assertEqual(client.host, '/run/user/1000/mpd/socket')
91 os.environ.pop('MPD_HOST', None)
92 os.environ.pop('MPD_PORT', None)
93 os.environ['XDG_RUNTIME_DIR'] = '/run/user/1000/'
94 with mock.patch('os.path.exists', return_value=True):
95 client = musicpd.MPDClient()
96 self.assertEqual(client.host, '/run/user/1000/mpd/socket')
99 os.environ.pop('MPD_TIMEOUT', None)
100 client = musicpd.MPDClient()
101 self.assertEqual(client.mpd_timeout, musicpd.CONNECTION_TIMEOUT)
102 os.environ['MPD_TIMEOUT'] = 'garbage'
103 client = musicpd.MPDClient()
104 self.assertEqual(client.mpd_timeout,
105 musicpd.CONNECTION_TIMEOUT,
106 'Garbage\'s not silently ignore to use default value')
107 os.environ['MPD_TIMEOUT'] = '42'
108 client = musicpd.MPDClient()
109 self.assertEqual(client.mpd_timeout, 42)
112 class TestMPDClient(unittest.TestCase):
115 # last sync: musicpd 0.4.2 unreleased / Mon Nov 17 21:45:22 CET 2014
118 'clearerror': 'nothing',
119 'currentsong': 'object',
124 # Playback Option Commands
125 'consume': 'nothing',
126 'crossfade': 'nothing',
127 'mixrampdb': 'nothing',
128 'mixrampdelay': 'nothing',
133 'replay_gain_mode': 'nothing',
134 'replay_gain_status': 'item',
136 # Playback Control Commands
141 'previous': 'nothing',
144 'seekcur': 'nothing',
151 'deleteid': 'nothing',
154 'playlist': 'playlist',
155 'playlistfind': 'songs',
156 'playlistid': 'songs',
157 'playlistinfo': 'songs',
158 'playlistsearch': 'songs',
159 'plchanges': 'songs',
160 'plchangesposid': 'changes',
163 'rangeid': 'nothing',
164 'shuffle': 'nothing',
167 'addtagid': 'nothing',
168 'cleartagid': 'nothing',
169 # Stored Playlist Commands
170 'listplaylist': 'list',
171 'listplaylistinfo': 'songs',
172 'listplaylists': 'playlists',
174 'playlistadd': 'nothing',
175 'playlistclear': 'nothing',
176 'playlistdelete': 'nothing',
177 'playlistmove': 'nothing',
184 'findadd': 'nothing',
186 'listall': 'database',
187 'listallinfo': 'database',
188 'lsinfo': 'database',
190 'searchadd': 'nothing',
191 'searchaddpl': 'nothing',
194 'readcomments': 'object',
195 # Mounts and neighbors
197 'unmount': 'nothing',
198 'listmounts': 'mounts',
199 'listneighbors': 'neighbors',
201 'sticker get': 'item',
202 'sticker set': 'nothing',
203 'sticker delete': 'nothing',
204 'sticker list': 'list',
205 'sticker find': 'songs',
206 # Connection Commands
209 'password': 'nothing',
212 'partition': 'nothing',
213 'listpartitions': 'list',
214 'newpartition': 'nothing',
215 # Audio Output Commands
216 'disableoutput': 'nothing',
217 'enableoutput': 'nothing',
218 'toggleoutput': 'nothing',
219 'outputs': 'outputs',
220 # Reflection Commands
223 'notcommands': 'list',
225 'urlhandlers': 'list',
226 'decoders': 'plugins',
228 'subscribe': 'nothing',
229 'unsubscribe': 'nothing',
231 'readmessages': 'messages',
232 'sendmessage': 'nothing',
236 self.socket_patch = mock.patch('musicpd.socket')
237 self.socket_mock = self.socket_patch.start()
238 self.socket_mock.getaddrinfo.return_value = [range(5)]
240 self.socket_mock.socket.side_effect = (
242 # Create a new socket.socket() mock with default attributes,
243 # each time we are calling it back (otherwise, it keeps set
244 # attributes across calls).
245 # That's probably what we want, since reconnecting is like
246 # reinitializing the entire connection, and so, the mock.
247 mock.MagicMock(name='socket.socket'))
249 self.client = musicpd.MPDClient()
250 self.client.connect(TEST_MPD_HOST, TEST_MPD_PORT)
251 self.client._sock.reset_mock()
252 self.MPDWillReturn('ACK don\'t forget to setup your mock\n')
255 self.socket_patch.stop()
257 def MPDWillReturn(self, *lines):
258 # Return what the caller wants first, then do as if the socket was
260 self.client._rfile.readline.side_effect = itertools.chain(
261 lines, itertools.repeat(''))
263 def MPDWillReturnBinary(self, lines):
264 data = bytearray(b''.join(lines))
272 val.append(data.pop(0))
277 while not val.endswith(b'\x0a'):
278 val.append(data.pop(0))
280 self.client._rbfile.readline.side_effect = readline
281 self.client._rbfile.read.side_effect = read
283 def assertMPDReceived(self, *lines):
284 self.client._wfile.write.assert_called_with(*lines)
286 def test_metaclass_commands(self):
287 """Controls client has at least commands as last synchronized in
288 TestMPDClient.commands"""
289 for cmd, ret in TestMPDClient.commands.items():
290 self.assertTrue(hasattr(self.client, cmd), msg='cmd "{}" not available!'.format(cmd))
292 self.assertTrue(hasattr(self.client, cmd.replace(' ', '_')))
294 def test_fetch_nothing(self):
295 self.MPDWillReturn('OK\n')
296 self.assertIsNone(self.client.ping())
297 self.assertMPDReceived('ping\n')
299 def test_fetch_list(self):
300 self.MPDWillReturn('OK\n')
301 self.assertIsInstance(self.client.list('album'), list)
302 self.assertMPDReceived('list "album"\n')
304 def test_fetch_item(self):
305 self.MPDWillReturn('updating_db: 42\n', 'OK\n')
306 self.assertIsNotNone(self.client.update())
308 def test_fetch_object(self):
309 # XXX: _read_objects() doesn't wait for the final OK
310 self.MPDWillReturn('volume: 63\n', 'OK\n')
311 status = self.client.status()
312 self.assertMPDReceived('status\n')
313 self.assertIsInstance(status, dict)
315 # XXX: _read_objects() doesn't wait for the final OK
316 self.MPDWillReturn('OK\n')
317 stats = self.client.stats()
318 self.assertMPDReceived('stats\n')
319 self.assertIsInstance(stats, dict)
321 def test_fetch_songs(self):
322 self.MPDWillReturn('file: my-song.ogg\n', 'Pos: 0\n', 'Id: 66\n', 'OK\n')
323 playlist = self.client.playlistinfo()
325 self.assertMPDReceived('playlistinfo\n')
326 self.assertIsInstance(playlist, list)
327 self.assertEqual(1, len(playlist))
329 self.assertIsInstance(e, dict)
330 self.assertEqual('my-song.ogg', e['file'])
331 self.assertEqual('0', e['pos'])
332 self.assertEqual('66', e['id'])
334 def test_send_and_fetch(self):
335 self.MPDWillReturn('volume: 50\n', 'OK\n')
336 result = self.client.send_status()
337 self.assertEqual(None, result)
338 self.assertMPDReceived('status\n')
340 status = self.client.fetch_status()
341 self.assertEqual(1, self.client._wfile.write.call_count)
342 self.assertEqual({'volume': '50'}, status)
344 def test_iterating(self):
345 self.MPDWillReturn('file: my-song.ogg\n', 'Pos: 0\n', 'Id: 66\n',
346 'file: my-song.ogg\n', 'Pos: 0\n', 'Id: 66\n', 'OK\n')
347 self.client.iterate = True
348 playlist = self.client.playlistinfo()
349 self.assertMPDReceived('playlistinfo\n')
350 self.assertIsInstance(playlist, types.GeneratorType)
351 self.assertTrue(self.client._iterating)
352 for song in playlist:
353 self.assertRaises(musicpd.IteratingError, self.client.status)
354 self.assertIsInstance(song, dict)
355 self.assertEqual('my-song.ogg', song['file'])
356 self.assertEqual('0', song['pos'])
357 self.assertEqual('66', song['id'])
358 self.assertFalse(self.client._iterating)
360 def test_noidle(self):
361 self.MPDWillReturn('OK\n') # nothing changed after idle-ing
362 self.client.send_idle()
363 self.MPDWillReturn('OK\n') # nothing changed after noidle
364 self.assertEqual(self.client.noidle(), [])
365 self.assertMPDReceived('noidle\n')
366 self.MPDWillReturn('volume: 50\n', 'OK\n')
368 self.assertMPDReceived('status\n')
370 def test_noidle_while_idle_started_sending(self):
371 self.MPDWillReturn('OK\n') # nothing changed after idle
372 self.client.send_idle()
373 self.MPDWillReturn('CHANGED: player\n', 'OK\n') # noidle response
374 self.assertEqual(self.client.noidle(), ['player'])
375 self.MPDWillReturn('volume: 50\n', 'OK\n')
376 status = self.client.status()
377 self.assertMPDReceived('status\n')
378 self.assertEqual({'volume': '50'}, status)
380 def test_throw_when_calling_noidle_withoutidling(self):
381 self.assertRaises(musicpd.CommandError, self.client.noidle)
382 self.client.send_status()
383 self.assertRaises(musicpd.CommandError, self.client.noidle)
385 def test_client_to_client(self):
386 # client to client is at this time in beta!
388 self.MPDWillReturn('OK\n')
389 self.assertIsNone(self.client.subscribe("monty"))
390 self.assertMPDReceived('subscribe "monty"\n')
392 self.MPDWillReturn('channel: monty\n', 'OK\n')
393 channels = self.client.channels()
394 self.assertMPDReceived('channels\n')
395 self.assertEqual(['monty'], channels)
397 self.MPDWillReturn('OK\n')
398 self.assertIsNone(self.client.sendmessage('monty', 'SPAM'))
399 self.assertMPDReceived('sendmessage "monty" "SPAM"\n')
401 self.MPDWillReturn('channel: monty\n', 'message: SPAM\n', 'OK\n')
402 msg = self.client.readmessages()
403 self.assertMPDReceived('readmessages\n')
404 self.assertEqual(msg, [{'channel': 'monty', 'message': 'SPAM'}])
406 self.MPDWillReturn('OK\n')
407 self.assertIsNone(self.client.unsubscribe('monty'))
408 self.assertMPDReceived('unsubscribe "monty"\n')
410 self.MPDWillReturn('OK\n')
411 channels = self.client.channels()
412 self.assertMPDReceived('channels\n')
413 self.assertEqual([], channels)
415 def test_ranges_in_command_args(self):
416 self.MPDWillReturn('OK\n')
417 self.client.playlistinfo((10,))
418 self.assertMPDReceived('playlistinfo 10:\n')
420 self.MPDWillReturn('OK\n')
421 self.client.playlistinfo(('10',))
422 self.assertMPDReceived('playlistinfo 10:\n')
424 self.MPDWillReturn('OK\n')
425 self.client.playlistinfo((10, 12))
426 self.assertMPDReceived('playlistinfo 10:12\n')
428 self.MPDWillReturn('OK\n')
429 self.client.rangeid(())
430 self.assertMPDReceived('rangeid :\n')
432 for arg in [(10, 't'), (10, 1, 1), (None,1)]:
433 self.MPDWillReturn('OK\n')
434 with self.assertRaises(musicpd.CommandError):
435 self.client.playlistinfo(arg)
437 def test_numbers_as_command_args(self):
438 self.MPDWillReturn('OK\n')
439 self.client.find('file', 1)
440 self.assertMPDReceived('find "file" "1"\n')
442 def test_commands_without_callbacks(self):
443 self.MPDWillReturn('\n')
445 self.assertMPDReceived('close\n')
447 # XXX: what are we testing here?
449 self.client.connect(TEST_MPD_HOST, TEST_MPD_PORT)
451 def test_connection_lost(self):
452 # Simulate a connection lost: the socket returns empty strings
453 self.MPDWillReturn('')
455 with self.assertRaises(musicpd.ConnectionError):
458 # consistent behaviour
459 # solves <https://github.com/Mic92/python-mpd2/issues/11> (also present
461 with self.assertRaises(musicpd.ConnectionError):
464 self.assertIs(self.client._sock, None)
466 def test_parse_sticker_get_no_sticker(self):
467 self.MPDWillReturn('ACK [50@0] {sticker} no such sticker\n')
468 self.assertRaises(musicpd.CommandError,
469 self.client.sticker_get, 'song', 'baz', 'foo')
471 def test_parse_sticker_list(self):
472 self.MPDWillReturn('sticker: foo=bar\n', 'sticker: lom=bok\n', 'OK\n')
473 res = self.client.sticker_list('song', 'baz')
474 self.assertEqual(['foo=bar', 'lom=bok'], res)
476 # Even with only one sticker, we get a dict
477 self.MPDWillReturn('sticker: foo=bar\n', 'OK\n')
478 res = self.client.sticker_list('song', 'baz')
479 self.assertEqual(['foo=bar'], res)
481 def test_albumart(self):
482 # here is a 34 bytes long data
483 data = bytes('\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01'
484 '\x00\x01\x00\x00\xff\xdb\x00C\x00\x05\x03\x04',
486 read_lines = [b'size: 42\nbinary: 34\n', data, b'\nOK\n']
487 self.MPDWillReturnBinary(read_lines)
488 # Reading albumart / offset 0 should return the data
489 res = self.client.albumart('muse/Raised Fist/2002-Dedication/', 0)
490 self.assertEqual(res.get('data'), data)
493 if __name__ == '__main__':