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 unix socket fallback
70 os.environ.pop('MPD_HOST', None)
71 os.environ.pop('MPD_PORT', None)
72 os.environ.pop('XDG_RUNTIME_DIR', None)
73 with mock.patch('os.path.exists', return_value=True):
74 client = musicpd.MPDClient()
75 self.assertEqual(client.host, '/run/mpd/socket')
76 os.environ['XDG_RUNTIME_DIR'] = '/run/user/1000'
77 client = musicpd.MPDClient()
78 self.assertEqual(client.host, '/run/user/1000/mpd/socket')
80 os.environ.pop('MPD_HOST', None)
81 os.environ.pop('MPD_PORT', None)
82 os.environ['XDG_RUNTIME_DIR'] = '/run/user/1000/'
83 with mock.patch('os.path.exists', return_value=True):
84 client = musicpd.MPDClient()
85 self.assertEqual(client.host, '/run/user/1000/mpd/socket')
88 os.environ.pop('MPD_TIMEOUT', None)
89 client = musicpd.MPDClient()
90 self.assertEqual(client.mpd_timeout, musicpd.CONNECTION_TIMEOUT)
91 os.environ['MPD_TIMEOUT'] = 'garbage'
92 client = musicpd.MPDClient()
93 self.assertEqual(client.mpd_timeout,
94 musicpd.CONNECTION_TIMEOUT,
95 'Garbage\'s not silently ignore to use default value')
96 os.environ['MPD_TIMEOUT'] = '42'
97 client = musicpd.MPDClient()
98 self.assertEqual(client.mpd_timeout, 42)
101 class TestMPDClient(unittest.TestCase):
104 # last sync: musicpd 0.4.2 unreleased / Mon Nov 17 21:45:22 CET 2014
107 'clearerror': 'nothing',
108 'currentsong': 'object',
113 # Playback Option Commands
114 'consume': 'nothing',
115 'crossfade': 'nothing',
116 'mixrampdb': 'nothing',
117 'mixrampdelay': 'nothing',
122 'replay_gain_mode': 'nothing',
123 'replay_gain_status': 'item',
125 # Playback Control Commands
130 'previous': 'nothing',
133 'seekcur': 'nothing',
140 'deleteid': 'nothing',
143 'playlist': 'playlist',
144 'playlistfind': 'songs',
145 'playlistid': 'songs',
146 'playlistinfo': 'songs',
147 'playlistsearch': 'songs',
148 'plchanges': 'songs',
149 'plchangesposid': 'changes',
152 'rangeid': 'nothing',
153 'shuffle': 'nothing',
156 'addtagid': 'nothing',
157 'cleartagid': 'nothing',
158 # Stored Playlist Commands
159 'listplaylist': 'list',
160 'listplaylistinfo': 'songs',
161 'listplaylists': 'playlists',
163 'playlistadd': 'nothing',
164 'playlistclear': 'nothing',
165 'playlistdelete': 'nothing',
166 'playlistmove': 'nothing',
173 'findadd': 'nothing',
175 'listall': 'database',
176 'listallinfo': 'database',
177 'lsinfo': 'database',
179 'searchadd': 'nothing',
180 'searchaddpl': 'nothing',
183 'readcomments': 'object',
184 # Mounts and neighbors
186 'unmount': 'nothing',
187 'listmounts': 'mounts',
188 'listneighbors': 'neighbors',
190 'sticker get': 'item',
191 'sticker set': 'nothing',
192 'sticker delete': 'nothing',
193 'sticker list': 'list',
194 'sticker find': 'songs',
195 # Connection Commands
198 'password': 'nothing',
201 'partition': 'nothing',
202 'listpartitions': 'list',
203 'newpartition': 'nothing',
204 # Audio Output Commands
205 'disableoutput': 'nothing',
206 'enableoutput': 'nothing',
207 'toggleoutput': 'nothing',
208 'outputs': 'outputs',
209 # Reflection Commands
212 'notcommands': 'list',
214 'urlhandlers': 'list',
215 'decoders': 'plugins',
217 'subscribe': 'nothing',
218 'unsubscribe': 'nothing',
220 'readmessages': 'messages',
221 'sendmessage': 'nothing',
225 self.socket_patch = mock.patch('musicpd.socket')
226 self.socket_mock = self.socket_patch.start()
227 self.socket_mock.getaddrinfo.return_value = [range(5)]
229 self.socket_mock.socket.side_effect = (
231 # Create a new socket.socket() mock with default attributes,
232 # each time we are calling it back (otherwise, it keeps set
233 # attributes across calls).
234 # That's probably what we want, since reconnecting is like
235 # reinitializing the entire connection, and so, the mock.
236 mock.MagicMock(name='socket.socket'))
238 self.client = musicpd.MPDClient()
239 self.client.connect(TEST_MPD_HOST, TEST_MPD_PORT)
240 self.client._sock.reset_mock()
241 self.MPDWillReturn('ACK don\'t forget to setup your mock\n')
244 self.socket_patch.stop()
246 def MPDWillReturn(self, *lines):
247 # Return what the caller wants first, then do as if the socket was
249 self.client._rfile.readline.side_effect = itertools.chain(
250 lines, itertools.repeat(''))
252 def MPDWillReturnBinary(self, lines):
253 data = bytearray(b''.join(lines))
261 val.append(data.pop(0))
266 while not val.endswith(b'\x0a'):
267 val.append(data.pop(0))
269 self.client._rbfile.readline.side_effect = readline
270 self.client._rbfile.read.side_effect = read
272 def assertMPDReceived(self, *lines):
273 self.client._wfile.write.assert_called_with(*lines)
275 def test_metaclass_commands(self):
276 """Controls client has at least commands as last synchronized in
277 TestMPDClient.commands"""
278 for cmd, ret in TestMPDClient.commands.items():
279 self.assertTrue(hasattr(self.client, cmd), msg='cmd "{}" not available!'.format(cmd))
281 self.assertTrue(hasattr(self.client, cmd.replace(' ', '_')))
283 def test_fetch_nothing(self):
284 self.MPDWillReturn('OK\n')
285 self.assertIsNone(self.client.ping())
286 self.assertMPDReceived('ping\n')
288 def test_fetch_list(self):
289 self.MPDWillReturn('OK\n')
290 self.assertIsInstance(self.client.list('album'), list)
291 self.assertMPDReceived('list "album"\n')
293 def test_fetch_item(self):
294 self.MPDWillReturn('updating_db: 42\n', 'OK\n')
295 self.assertIsNotNone(self.client.update())
297 def test_fetch_object(self):
298 # XXX: _read_objects() doesn't wait for the final OK
299 self.MPDWillReturn('volume: 63\n', 'OK\n')
300 status = self.client.status()
301 self.assertMPDReceived('status\n')
302 self.assertIsInstance(status, dict)
304 # XXX: _read_objects() doesn't wait for the final OK
305 self.MPDWillReturn('OK\n')
306 stats = self.client.stats()
307 self.assertMPDReceived('stats\n')
308 self.assertIsInstance(stats, dict)
310 def test_fetch_songs(self):
311 self.MPDWillReturn('file: my-song.ogg\n', 'Pos: 0\n', 'Id: 66\n', 'OK\n')
312 playlist = self.client.playlistinfo()
314 self.assertMPDReceived('playlistinfo\n')
315 self.assertIsInstance(playlist, list)
316 self.assertEqual(1, len(playlist))
318 self.assertIsInstance(e, dict)
319 self.assertEqual('my-song.ogg', e['file'])
320 self.assertEqual('0', e['pos'])
321 self.assertEqual('66', e['id'])
323 def test_send_and_fetch(self):
324 self.MPDWillReturn('volume: 50\n', 'OK\n')
325 result = self.client.send_status()
326 self.assertEqual(None, result)
327 self.assertMPDReceived('status\n')
329 status = self.client.fetch_status()
330 self.assertEqual(1, self.client._wfile.write.call_count)
331 self.assertEqual({'volume': '50'}, status)
333 def test_iterating(self):
334 self.MPDWillReturn('file: my-song.ogg\n', 'Pos: 0\n', 'Id: 66\n',
335 'file: my-song.ogg\n', 'Pos: 0\n', 'Id: 66\n', 'OK\n')
336 self.client.iterate = True
337 playlist = self.client.playlistinfo()
338 self.assertMPDReceived('playlistinfo\n')
339 self.assertIsInstance(playlist, types.GeneratorType)
340 self.assertTrue(self.client._iterating)
341 for song in playlist:
342 self.assertRaises(musicpd.IteratingError, self.client.status)
343 self.assertIsInstance(song, dict)
344 self.assertEqual('my-song.ogg', song['file'])
345 self.assertEqual('0', song['pos'])
346 self.assertEqual('66', song['id'])
347 self.assertFalse(self.client._iterating)
349 def test_noidle(self):
350 self.MPDWillReturn('OK\n') # nothing changed after idle-ing
351 self.client.send_idle()
352 self.MPDWillReturn('OK\n') # nothing changed after noidle
353 self.assertEqual(self.client.noidle(), [])
354 self.assertMPDReceived('noidle\n')
355 self.MPDWillReturn('volume: 50\n', 'OK\n')
357 self.assertMPDReceived('status\n')
359 def test_noidle_while_idle_started_sending(self):
360 self.MPDWillReturn('OK\n') # nothing changed after idle
361 self.client.send_idle()
362 self.MPDWillReturn('CHANGED: player\n', 'OK\n') # noidle response
363 self.assertEqual(self.client.noidle(), ['player'])
364 self.MPDWillReturn('volume: 50\n', 'OK\n')
365 status = self.client.status()
366 self.assertMPDReceived('status\n')
367 self.assertEqual({'volume': '50'}, status)
369 def test_throw_when_calling_noidle_withoutidling(self):
370 self.assertRaises(musicpd.CommandError, self.client.noidle)
371 self.client.send_status()
372 self.assertRaises(musicpd.CommandError, self.client.noidle)
374 def test_client_to_client(self):
375 # client to client is at this time in beta!
377 self.MPDWillReturn('OK\n')
378 self.assertIsNone(self.client.subscribe("monty"))
379 self.assertMPDReceived('subscribe "monty"\n')
381 self.MPDWillReturn('channel: monty\n', 'OK\n')
382 channels = self.client.channels()
383 self.assertMPDReceived('channels\n')
384 self.assertEqual(['monty'], channels)
386 self.MPDWillReturn('OK\n')
387 self.assertIsNone(self.client.sendmessage('monty', 'SPAM'))
388 self.assertMPDReceived('sendmessage "monty" "SPAM"\n')
390 self.MPDWillReturn('channel: monty\n', 'message: SPAM\n', 'OK\n')
391 msg = self.client.readmessages()
392 self.assertMPDReceived('readmessages\n')
393 self.assertEqual(msg, [{'channel': 'monty', 'message': 'SPAM'}])
395 self.MPDWillReturn('OK\n')
396 self.assertIsNone(self.client.unsubscribe('monty'))
397 self.assertMPDReceived('unsubscribe "monty"\n')
399 self.MPDWillReturn('OK\n')
400 channels = self.client.channels()
401 self.assertMPDReceived('channels\n')
402 self.assertEqual([], channels)
404 def test_ranges_in_command_args(self):
405 self.MPDWillReturn('OK\n')
406 self.client.playlistinfo((10,))
407 self.assertMPDReceived('playlistinfo 10:\n')
409 self.MPDWillReturn('OK\n')
410 self.client.playlistinfo(('10',))
411 self.assertMPDReceived('playlistinfo 10:\n')
413 self.MPDWillReturn('OK\n')
414 self.client.playlistinfo((10, 12))
415 self.assertMPDReceived('playlistinfo 10:12\n')
417 self.MPDWillReturn('OK\n')
418 self.client.rangeid(())
419 self.assertMPDReceived('rangeid :\n')
421 for arg in [(10, 't'), (10, 1, 1), (None,1)]:
422 self.MPDWillReturn('OK\n')
423 with self.assertRaises(musicpd.CommandError):
424 self.client.playlistinfo(arg)
426 def test_numbers_as_command_args(self):
427 self.MPDWillReturn('OK\n')
428 self.client.find('file', 1)
429 self.assertMPDReceived('find "file" "1"\n')
431 def test_commands_without_callbacks(self):
432 self.MPDWillReturn('\n')
434 self.assertMPDReceived('close\n')
436 # XXX: what are we testing here?
438 self.client.connect(TEST_MPD_HOST, TEST_MPD_PORT)
440 def test_connection_lost(self):
441 # Simulate a connection lost: the socket returns empty strings
442 self.MPDWillReturn('')
444 with self.assertRaises(musicpd.ConnectionError):
447 # consistent behaviour
448 # solves <https://github.com/Mic92/python-mpd2/issues/11> (also present
450 with self.assertRaises(musicpd.ConnectionError):
453 self.assertIs(self.client._sock, None)
455 def test_parse_sticker_get_no_sticker(self):
456 self.MPDWillReturn('ACK [50@0] {sticker} no such sticker\n')
457 self.assertRaises(musicpd.CommandError,
458 self.client.sticker_get, 'song', 'baz', 'foo')
460 def test_parse_sticker_list(self):
461 self.MPDWillReturn('sticker: foo=bar\n', 'sticker: lom=bok\n', 'OK\n')
462 res = self.client.sticker_list('song', 'baz')
463 self.assertEqual(['foo=bar', 'lom=bok'], res)
465 # Even with only one sticker, we get a dict
466 self.MPDWillReturn('sticker: foo=bar\n', 'OK\n')
467 res = self.client.sticker_list('song', 'baz')
468 self.assertEqual(['foo=bar'], res)
470 def test_albumart(self):
471 # here is a 34 bytes long data
472 data = bytes('\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01'
473 '\x00\x01\x00\x00\xff\xdb\x00C\x00\x05\x03\x04',
475 read_lines = [b'size: 42\nbinary: 34\n', data, b'\nOK\n']
476 self.MPDWillReturnBinary(read_lines)
477 # Reading albumart / offset 0 should return the data
478 res = self.client.albumart('muse/Raised Fist/2002-Dedication/', 0)
479 self.assertEqual(res.get('data'), data)
482 if __name__ == '__main__':