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 password extraction (no host)
65 os.environ['MPD_HOST'] = 'pa55w04d@'
66 with mock.patch('os.path.exists', return_value=False):
67 client = musicpd.MPDClient()
68 self.assertEqual(client.pwd, 'pa55w04d')
69 self.assertEqual(client.host, 'localhost')
71 # Test unix socket extraction
72 os.environ['MPD_HOST'] = 'pa55w04d@/unix/sock'
73 client = musicpd.MPDClient()
74 self.assertEqual(client.host, '/unix/sock')
76 # Test plain abstract socket extraction
77 os.environ['MPD_HOST'] = '@abstract'
78 client = musicpd.MPDClient()
79 self.assertEqual(client.host, '@abstract')
81 # Test password and abstract socket extraction
82 os.environ['MPD_HOST'] = 'pass@@abstract'
83 client = musicpd.MPDClient()
84 self.assertEqual(client.pwd, 'pass')
85 self.assertEqual(client.host, '@abstract')
87 # Test unix socket fallback
88 os.environ.pop('MPD_HOST', None)
89 os.environ.pop('MPD_PORT', None)
90 os.environ.pop('XDG_RUNTIME_DIR', None)
91 with mock.patch('os.path.exists', return_value=True):
92 client = musicpd.MPDClient()
93 self.assertEqual(client.host, '/run/mpd/socket')
94 os.environ['XDG_RUNTIME_DIR'] = '/run/user/1000'
95 client = musicpd.MPDClient()
96 self.assertEqual(client.host, '/run/user/1000/mpd/socket')
98 os.environ.pop('MPD_HOST', None)
99 os.environ.pop('MPD_PORT', None)
100 os.environ['XDG_RUNTIME_DIR'] = '/run/user/1000/'
101 with mock.patch('os.path.exists', return_value=True):
102 client = musicpd.MPDClient()
103 self.assertEqual(client.host, '/run/user/1000/mpd/socket')
106 os.environ.pop('MPD_TIMEOUT', None)
107 client = musicpd.MPDClient()
108 self.assertEqual(client.mpd_timeout, musicpd.CONNECTION_TIMEOUT)
109 os.environ['MPD_TIMEOUT'] = 'garbage'
110 client = musicpd.MPDClient()
111 self.assertEqual(client.mpd_timeout,
112 musicpd.CONNECTION_TIMEOUT,
113 'Garbage\'s not silently ignore to use default value')
114 os.environ['MPD_TIMEOUT'] = '42'
115 client = musicpd.MPDClient()
116 self.assertEqual(client.mpd_timeout, 42)
119 class TestMPDClient(unittest.TestCase):
122 # last sync: musicpd 0.4.2 unreleased / Mon Nov 17 21:45:22 CET 2014
125 'clearerror': 'nothing',
126 'currentsong': 'object',
131 # Playback Option Commands
132 'consume': 'nothing',
133 'crossfade': 'nothing',
134 'mixrampdb': 'nothing',
135 'mixrampdelay': 'nothing',
140 'replay_gain_mode': 'nothing',
141 'replay_gain_status': 'item',
143 # Playback Control Commands
148 'previous': 'nothing',
151 'seekcur': 'nothing',
158 'deleteid': 'nothing',
161 'playlist': 'playlist',
162 'playlistfind': 'songs',
163 'playlistid': 'songs',
164 'playlistinfo': 'songs',
165 'playlistsearch': 'songs',
166 'plchanges': 'songs',
167 'plchangesposid': 'changes',
170 'rangeid': 'nothing',
171 'shuffle': 'nothing',
174 'addtagid': 'nothing',
175 'cleartagid': 'nothing',
176 # Stored Playlist Commands
177 'listplaylist': 'list',
178 'listplaylistinfo': 'songs',
179 'listplaylists': 'playlists',
181 'playlistadd': 'nothing',
182 'playlistclear': 'nothing',
183 'playlistdelete': 'nothing',
184 'playlistmove': 'nothing',
191 'findadd': 'nothing',
193 'listall': 'database',
194 'listallinfo': 'database',
195 'lsinfo': 'database',
197 'searchadd': 'nothing',
198 'searchaddpl': 'nothing',
201 'readcomments': 'object',
202 # Mounts and neighbors
204 'unmount': 'nothing',
205 'listmounts': 'mounts',
206 'listneighbors': 'neighbors',
208 'sticker get': 'item',
209 'sticker set': 'nothing',
210 'sticker delete': 'nothing',
211 'sticker list': 'list',
212 'sticker find': 'songs',
213 # Connection Commands
216 'password': 'nothing',
219 'partition': 'nothing',
220 'listpartitions': 'list',
221 'newpartition': 'nothing',
222 # Audio Output Commands
223 'disableoutput': 'nothing',
224 'enableoutput': 'nothing',
225 'toggleoutput': 'nothing',
226 'outputs': 'outputs',
227 # Reflection Commands
230 'notcommands': 'list',
232 'urlhandlers': 'list',
233 'decoders': 'plugins',
235 'subscribe': 'nothing',
236 'unsubscribe': 'nothing',
238 'readmessages': 'messages',
239 'sendmessage': 'nothing',
243 self.socket_patch = mock.patch('musicpd.socket')
244 self.socket_mock = self.socket_patch.start()
245 self.socket_mock.getaddrinfo.return_value = [range(5)]
247 self.socket_mock.socket.side_effect = (
249 # Create a new socket.socket() mock with default attributes,
250 # each time we are calling it back (otherwise, it keeps set
251 # attributes across calls).
252 # That's probably what we want, since reconnecting is like
253 # reinitializing the entire connection, and so, the mock.
254 mock.MagicMock(name='socket.socket'))
256 self.client = musicpd.MPDClient()
257 self.client.connect(TEST_MPD_HOST, TEST_MPD_PORT)
258 self.client._sock.reset_mock()
259 self.MPDWillReturn('ACK don\'t forget to setup your mock\n')
262 self.socket_patch.stop()
264 def MPDWillReturn(self, *lines):
265 # Return what the caller wants first, then do as if the socket was
267 self.client._rfile.readline.side_effect = itertools.chain(
268 lines, itertools.repeat(''))
270 def MPDWillReturnBinary(self, lines):
271 data = bytearray(b''.join(lines))
279 val.append(data.pop(0))
284 while not val.endswith(b'\x0a'):
285 val.append(data.pop(0))
287 self.client._rbfile.readline.side_effect = readline
288 self.client._rbfile.read.side_effect = read
290 def assertMPDReceived(self, *lines):
291 self.client._wfile.write.assert_called_with(*lines)
293 def test_metaclass_commands(self):
294 """Controls client has at least commands as last synchronized in
295 TestMPDClient.commands"""
296 for cmd, ret in TestMPDClient.commands.items():
297 self.assertTrue(hasattr(self.client, cmd), msg='cmd "{}" not available!'.format(cmd))
299 self.assertTrue(hasattr(self.client, cmd.replace(' ', '_')))
301 def test_fetch_nothing(self):
302 self.MPDWillReturn('OK\n')
303 self.assertIsNone(self.client.ping())
304 self.assertMPDReceived('ping\n')
306 def test_fetch_list(self):
307 self.MPDWillReturn('OK\n')
308 self.assertIsInstance(self.client.list('album'), list)
309 self.assertMPDReceived('list "album"\n')
311 def test_fetch_item(self):
312 self.MPDWillReturn('updating_db: 42\n', 'OK\n')
313 self.assertIsNotNone(self.client.update())
315 def test_fetch_object(self):
316 # XXX: _read_objects() doesn't wait for the final OK
317 self.MPDWillReturn('volume: 63\n', 'OK\n')
318 status = self.client.status()
319 self.assertMPDReceived('status\n')
320 self.assertIsInstance(status, dict)
322 # XXX: _read_objects() doesn't wait for the final OK
323 self.MPDWillReturn('OK\n')
324 stats = self.client.stats()
325 self.assertMPDReceived('stats\n')
326 self.assertIsInstance(stats, dict)
328 def test_fetch_songs(self):
329 self.MPDWillReturn('file: my-song.ogg\n', 'Pos: 0\n', 'Id: 66\n', 'OK\n')
330 playlist = self.client.playlistinfo()
332 self.assertMPDReceived('playlistinfo\n')
333 self.assertIsInstance(playlist, list)
334 self.assertEqual(1, len(playlist))
336 self.assertIsInstance(e, dict)
337 self.assertEqual('my-song.ogg', e['file'])
338 self.assertEqual('0', e['pos'])
339 self.assertEqual('66', e['id'])
341 def test_send_and_fetch(self):
342 self.MPDWillReturn('volume: 50\n', 'OK\n')
343 result = self.client.send_status()
344 self.assertEqual(None, result)
345 self.assertMPDReceived('status\n')
347 status = self.client.fetch_status()
348 self.assertEqual(1, self.client._wfile.write.call_count)
349 self.assertEqual({'volume': '50'}, status)
351 def test_iterating(self):
352 self.MPDWillReturn('file: my-song.ogg\n', 'Pos: 0\n', 'Id: 66\n',
353 'file: my-song.ogg\n', 'Pos: 0\n', 'Id: 66\n', 'OK\n')
354 self.client.iterate = True
355 playlist = self.client.playlistinfo()
356 self.assertMPDReceived('playlistinfo\n')
357 self.assertIsInstance(playlist, types.GeneratorType)
358 self.assertTrue(self.client._iterating)
359 for song in playlist:
360 self.assertRaises(musicpd.IteratingError, self.client.status)
361 self.assertIsInstance(song, dict)
362 self.assertEqual('my-song.ogg', song['file'])
363 self.assertEqual('0', song['pos'])
364 self.assertEqual('66', song['id'])
365 self.assertFalse(self.client._iterating)
367 def test_noidle(self):
368 self.MPDWillReturn('OK\n') # nothing changed after idle-ing
369 self.client.send_idle()
370 self.MPDWillReturn('OK\n') # nothing changed after noidle
371 self.assertEqual(self.client.noidle(), [])
372 self.assertMPDReceived('noidle\n')
373 self.MPDWillReturn('volume: 50\n', 'OK\n')
375 self.assertMPDReceived('status\n')
377 def test_noidle_while_idle_started_sending(self):
378 self.MPDWillReturn('OK\n') # nothing changed after idle
379 self.client.send_idle()
380 self.MPDWillReturn('CHANGED: player\n', 'OK\n') # noidle response
381 self.assertEqual(self.client.noidle(), ['player'])
382 self.MPDWillReturn('volume: 50\n', 'OK\n')
383 status = self.client.status()
384 self.assertMPDReceived('status\n')
385 self.assertEqual({'volume': '50'}, status)
387 def test_throw_when_calling_noidle_withoutidling(self):
388 self.assertRaises(musicpd.CommandError, self.client.noidle)
389 self.client.send_status()
390 self.assertRaises(musicpd.CommandError, self.client.noidle)
392 def test_client_to_client(self):
393 # client to client is at this time in beta!
395 self.MPDWillReturn('OK\n')
396 self.assertIsNone(self.client.subscribe("monty"))
397 self.assertMPDReceived('subscribe "monty"\n')
399 self.MPDWillReturn('channel: monty\n', 'OK\n')
400 channels = self.client.channels()
401 self.assertMPDReceived('channels\n')
402 self.assertEqual(['monty'], channels)
404 self.MPDWillReturn('OK\n')
405 self.assertIsNone(self.client.sendmessage('monty', 'SPAM'))
406 self.assertMPDReceived('sendmessage "monty" "SPAM"\n')
408 self.MPDWillReturn('channel: monty\n', 'message: SPAM\n', 'OK\n')
409 msg = self.client.readmessages()
410 self.assertMPDReceived('readmessages\n')
411 self.assertEqual(msg, [{'channel': 'monty', 'message': 'SPAM'}])
413 self.MPDWillReturn('OK\n')
414 self.assertIsNone(self.client.unsubscribe('monty'))
415 self.assertMPDReceived('unsubscribe "monty"\n')
417 self.MPDWillReturn('OK\n')
418 channels = self.client.channels()
419 self.assertMPDReceived('channels\n')
420 self.assertEqual([], channels)
422 def test_ranges_in_command_args(self):
423 self.MPDWillReturn('OK\n')
424 self.client.playlistinfo((10,))
425 self.assertMPDReceived('playlistinfo 10:\n')
427 self.MPDWillReturn('OK\n')
428 self.client.playlistinfo(('10',))
429 self.assertMPDReceived('playlistinfo 10:\n')
431 self.MPDWillReturn('OK\n')
432 self.client.playlistinfo((10, 12))
433 self.assertMPDReceived('playlistinfo 10:12\n')
435 self.MPDWillReturn('OK\n')
436 self.client.rangeid(())
437 self.assertMPDReceived('rangeid :\n')
439 for arg in [(10, 't'), (10, 1, 1), (None,1)]:
440 self.MPDWillReturn('OK\n')
441 with self.assertRaises(musicpd.CommandError):
442 self.client.playlistinfo(arg)
444 def test_numbers_as_command_args(self):
445 self.MPDWillReturn('OK\n')
446 self.client.find('file', 1)
447 self.assertMPDReceived('find "file" "1"\n')
449 def test_commands_without_callbacks(self):
450 self.MPDWillReturn('\n')
452 self.assertMPDReceived('close\n')
454 # XXX: what are we testing here?
456 self.client.connect(TEST_MPD_HOST, TEST_MPD_PORT)
458 def test_connection_lost(self):
459 # Simulate a connection lost: the socket returns empty strings
460 self.MPDWillReturn('')
462 with self.assertRaises(musicpd.ConnectionError):
465 # consistent behaviour
466 # solves <https://github.com/Mic92/python-mpd2/issues/11> (also present
468 with self.assertRaises(musicpd.ConnectionError):
471 self.assertIs(self.client._sock, None)
473 def test_parse_sticker_get_no_sticker(self):
474 self.MPDWillReturn('ACK [50@0] {sticker} no such sticker\n')
475 self.assertRaises(musicpd.CommandError,
476 self.client.sticker_get, 'song', 'baz', 'foo')
478 def test_parse_sticker_list(self):
479 self.MPDWillReturn('sticker: foo=bar\n', 'sticker: lom=bok\n', 'OK\n')
480 res = self.client.sticker_list('song', 'baz')
481 self.assertEqual(['foo=bar', 'lom=bok'], res)
483 # Even with only one sticker, we get a dict
484 self.MPDWillReturn('sticker: foo=bar\n', 'OK\n')
485 res = self.client.sticker_list('song', 'baz')
486 self.assertEqual(['foo=bar'], res)
488 def test_albumart(self):
489 # here is a 34 bytes long data
490 data = bytes('\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01'
491 '\x00\x01\x00\x00\xff\xdb\x00C\x00\x05\x03\x04',
493 read_lines = [b'size: 42\nbinary: 34\n', data, b'\nOK\n']
494 self.MPDWillReturnBinary(read_lines)
495 # Reading albumart / offset 0 should return the data
496 res = self.client.albumart('muse/Raised Fist/2002-Dedication/', 0)
497 self.assertEqual(res.get('data'), data)
500 if __name__ == '__main__':