2 # -*- coding: utf-8 -*-
4 Test suite highly borrowed^Wsteal from python-mpd2 [0] project.
6 [0] https://github.com/Mic92/python-mpd2
20 import unittest.mock as mock
25 print("Please install mock from PyPI to run tests!")
28 # show deprecation warnings
29 warnings.simplefilter('default')
32 TEST_MPD_HOST, TEST_MPD_PORT = ('example.com', 10000)
35 class testEnvVar(unittest.TestCase):
37 def test_envvar(self):
38 os.environ.pop('MPD_HOST', None)
39 os.environ.pop('MPD_PORT', None)
40 client = musicpd.MPDClient()
41 self.assertEqual(client.host, 'localhost')
42 self.assertEqual(client.port, '6600')
44 os.environ['MPD_HOST'] = 'pa55w04d@example.org'
45 client = musicpd.MPDClient()
46 self.assertEqual(client.pwd, 'pa55w04d')
47 self.assertEqual(client.host, 'example.org')
48 self.assertEqual(client.port, '6600')
50 os.environ.pop('MPD_HOST', None)
51 os.environ['MPD_PORT'] = '6666'
52 client = musicpd.MPDClient()
53 self.assertEqual(client.pwd, None)
54 self.assertEqual(client.host, 'localhost')
55 self.assertEqual(client.port, '6666')
57 # Test unix socket fallback
58 os.environ.pop('MPD_HOST', None)
59 os.environ.pop('MPD_PORT', None)
60 os.environ.pop('XDG_RUNTIME_DIR', None)
61 with mock.patch('os.path.exists', return_value=True):
62 client = musicpd.MPDClient()
63 self.assertEqual(client.host, '/run/mpd/socket')
65 os.environ.pop('MPD_HOST', None)
66 os.environ.pop('MPD_PORT', None)
67 os.environ['XDG_RUNTIME_DIR'] = '/run/user/1000/'
68 with mock.patch('os.path.exists', return_value=True):
69 client = musicpd.MPDClient()
70 self.assertEqual(client.host, '/run/user/1000/mpd/socket')
72 class TestMPDClient(unittest.TestCase):
75 # last sync: musicpd 0.4.2 unreleased / Mon Nov 17 21:45:22 CET 2014
78 'clearerror': 'nothing',
79 'currentsong': 'object',
84 # Playback Option Commands
86 'crossfade': 'nothing',
87 'mixrampdb': 'nothing',
88 'mixrampdelay': 'nothing',
93 'replay_gain_mode': 'nothing',
94 'replay_gain_status': 'item',
96 # Playback Control Commands
101 'previous': 'nothing',
104 'seekcur': 'nothing',
111 'deleteid': 'nothing',
114 'playlist': 'playlist',
115 'playlistfind': 'songs',
116 'playlistid': 'songs',
117 'playlistinfo': 'songs',
118 'playlistsearch': 'songs',
119 'plchanges': 'songs',
120 'plchangesposid': 'changes',
123 'rangeid': 'nothing',
124 'shuffle': 'nothing',
127 'addtagid': 'nothing',
128 'cleartagid': 'nothing',
129 # Stored Playlist Commands
130 'listplaylist': 'list',
131 'listplaylistinfo': 'songs',
132 'listplaylists': 'playlists',
134 'playlistadd': 'nothing',
135 'playlistclear': 'nothing',
136 'playlistdelete': 'nothing',
137 'playlistmove': 'nothing',
144 'findadd': 'nothing',
146 'listall': 'database',
147 'listallinfo': 'database',
148 'lsinfo': 'database',
150 'searchadd': 'nothing',
151 'searchaddpl': 'nothing',
154 'readcomments': 'object',
155 # Mounts and neighbors
157 'unmount': 'nothing',
158 'listmounts': 'mounts',
159 'listneighbors': 'neighbors',
161 'sticker get': 'item',
162 'sticker set': 'nothing',
163 'sticker delete': 'nothing',
164 'sticker list': 'list',
165 'sticker find': 'songs',
166 # Connection Commands
169 'password': 'nothing',
171 # Audio Output Commands
172 'disableoutput': 'nothing',
173 'enableoutput': 'nothing',
174 'toggleoutput': 'nothing',
175 'outputs': 'outputs',
176 # Reflection Commands
179 'notcommands': 'list',
181 'urlhandlers': 'list',
182 'decoders': 'plugins',
184 'subscribe': 'nothing',
185 'unsubscribe': 'nothing',
187 'readmessages': 'messages',
188 'sendmessage': 'nothing',
192 self.socket_patch = mock.patch('musicpd.socket')
193 self.socket_mock = self.socket_patch.start()
194 self.socket_mock.getaddrinfo.return_value = [range(5)]
196 self.socket_mock.socket.side_effect = (
198 # Create a new socket.socket() mock with default attributes,
199 # each time we are calling it back (otherwise, it keeps set
200 # attributes across calls).
201 # That's probably what we want, since reconnecting is like
202 # reinitializing the entire connection, and so, the mock.
203 mock.MagicMock(name='socket.socket'))
205 self.client = musicpd.MPDClient()
206 self.client.connect(TEST_MPD_HOST, TEST_MPD_PORT)
207 self.client._sock.reset_mock()
208 self.MPDWillReturn('ACK don\'t forget to setup your mock\n')
211 self.socket_patch.stop()
213 def MPDWillReturn(self, *lines):
214 # Return what the caller wants first, then do as if the socket was
216 self.client._rfile.readline.side_effect = itertools.chain(
217 lines, itertools.repeat(''))
219 def assertMPDReceived(self, *lines):
220 self.client._wfile.write.assert_called_with(*lines)
222 def test_metaclass_commands(self):
223 """Controls client has at least commands as last synchronized in
224 TestMPDClient.commands"""
225 for cmd, ret in TestMPDClient.commands.items():
226 self.assertTrue(hasattr(self.client, cmd), msg='cmd "{}" not available!'.format(cmd))
228 self.assertTrue(hasattr(self.client, cmd.replace(' ', '_')))
230 def test_fetch_nothing(self):
231 self.MPDWillReturn('OK\n')
232 self.assertIsNone(self.client.ping())
233 self.assertMPDReceived('ping\n')
235 def test_fetch_list(self):
236 self.MPDWillReturn('OK\n')
237 self.assertIsInstance(self.client.list('album'), list)
238 self.assertMPDReceived('list "album"\n')
240 def test_fetch_item(self):
241 self.MPDWillReturn('updating_db: 42\n', 'OK\n')
242 self.assertIsNotNone(self.client.update())
244 def test_fetch_object(self):
245 # XXX: _read_objects() doesn't wait for the final OK
246 self.MPDWillReturn('volume: 63\n', 'OK\n')
247 status = self.client.status()
248 self.assertMPDReceived('status\n')
249 self.assertIsInstance(status, dict)
251 # XXX: _read_objects() doesn't wait for the final OK
252 self.MPDWillReturn('OK\n')
253 stats = self.client.stats()
254 self.assertMPDReceived('stats\n')
255 self.assertIsInstance(stats, dict)
257 def test_fetch_songs(self):
258 self.MPDWillReturn('file: my-song.ogg\n', 'Pos: 0\n', 'Id: 66\n', 'OK\n')
259 playlist = self.client.playlistinfo()
261 self.assertMPDReceived('playlistinfo\n')
262 self.assertIsInstance(playlist, list)
263 self.assertEqual(1, len(playlist))
265 self.assertIsInstance(e, dict)
266 self.assertEqual('my-song.ogg', e['file'])
267 self.assertEqual('0', e['pos'])
268 self.assertEqual('66', e['id'])
270 def test_send_and_fetch(self):
271 self.MPDWillReturn('volume: 50\n', 'OK\n')
272 result = self.client.send_status()
273 self.assertEqual(None, result)
274 self.assertMPDReceived('status\n')
276 status = self.client.fetch_status()
277 self.assertEqual(1, self.client._wfile.write.call_count)
278 self.assertEqual({'volume': '50'}, status)
280 def test_iterating(self):
281 self.MPDWillReturn('file: my-song.ogg\n', 'Pos: 0\n', 'Id: 66\n',
282 'file: my-song.ogg\n', 'Pos: 0\n', 'Id: 66\n', 'OK\n')
283 self.client.iterate = True
284 playlist = self.client.playlistinfo()
285 self.assertMPDReceived('playlistinfo\n')
286 self.assertIsInstance(playlist, types.GeneratorType)
287 self.assertTrue(self.client._iterating)
288 for song in playlist:
289 self.assertRaises(musicpd.IteratingError, self.client.status)
290 self.assertIsInstance(song, dict)
291 self.assertEqual('my-song.ogg', song['file'])
292 self.assertEqual('0', song['pos'])
293 self.assertEqual('66', song['id'])
294 self.assertFalse(self.client._iterating)
296 def test_noidle(self):
297 self.MPDWillReturn('OK\n') # nothing changed after idle-ing
298 self.client.send_idle()
299 self.MPDWillReturn('OK\n') # nothing changed after noidle
300 self.assertEqual(self.client.noidle(), [])
301 self.assertMPDReceived('noidle\n')
302 self.MPDWillReturn('volume: 50\n', 'OK\n')
304 self.assertMPDReceived('status\n')
306 def test_noidle_while_idle_started_sending(self):
307 self.MPDWillReturn('OK\n') # nothing changed after idle
308 self.client.send_idle()
309 self.MPDWillReturn('CHANGED: player\n', 'OK\n') # noidle response
310 self.assertEqual(self.client.noidle(), ['player'])
311 self.MPDWillReturn('volume: 50\n', 'OK\n')
312 status = self.client.status()
313 self.assertMPDReceived('status\n')
314 self.assertEqual({'volume': '50'}, status)
316 def test_throw_when_calling_noidle_withoutidling(self):
317 self.assertRaises(musicpd.CommandError, self.client.noidle)
318 self.client.send_status()
319 self.assertRaises(musicpd.CommandError, self.client.noidle)
321 def test_client_to_client(self):
322 # client to client is at this time in beta!
324 self.MPDWillReturn('OK\n')
325 self.assertIsNone(self.client.subscribe("monty"))
326 self.assertMPDReceived('subscribe "monty"\n')
328 self.MPDWillReturn('channel: monty\n', 'OK\n')
329 channels = self.client.channels()
330 self.assertMPDReceived('channels\n')
331 self.assertEqual(['monty'], channels)
333 self.MPDWillReturn('OK\n')
334 self.assertIsNone(self.client.sendmessage('monty', 'SPAM'))
335 self.assertMPDReceived('sendmessage "monty" "SPAM"\n')
337 self.MPDWillReturn('channel: monty\n', 'message: SPAM\n', 'OK\n')
338 msg = self.client.readmessages()
339 self.assertMPDReceived('readmessages\n')
340 self.assertEqual(msg, [{'channel': 'monty', 'message': 'SPAM'}])
342 self.MPDWillReturn('OK\n')
343 self.assertIsNone(self.client.unsubscribe('monty'))
344 self.assertMPDReceived('unsubscribe "monty"\n')
346 self.MPDWillReturn('OK\n')
347 channels = self.client.channels()
348 self.assertMPDReceived('channels\n')
349 self.assertEqual([], channels)
351 def test_ranges_in_command_args(self):
352 self.MPDWillReturn('OK\n')
353 self.client.playlistinfo((10,))
354 self.assertMPDReceived('playlistinfo 10:\n')
356 self.MPDWillReturn('OK\n')
357 self.client.playlistinfo(('10',))
358 self.assertMPDReceived('playlistinfo 10:\n')
360 self.MPDWillReturn('OK\n')
361 self.client.playlistinfo((10, 12))
362 self.assertMPDReceived('playlistinfo 10:12\n')
364 self.MPDWillReturn('OK\n')
365 self.client.rangeid(())
366 self.assertMPDReceived('rangeid :\n')
368 for arg in [(10, 't'), (10, 1, 1), (None,1)]:
369 self.MPDWillReturn('OK\n')
370 with self.assertRaises(musicpd.CommandError):
371 self.client.playlistinfo(arg)
373 def test_numbers_as_command_args(self):
374 self.MPDWillReturn('OK\n')
375 self.client.find('file', 1)
376 self.assertMPDReceived('find "file" "1"\n')
378 def test_commands_without_callbacks(self):
379 self.MPDWillReturn('\n')
381 self.assertMPDReceived('close\n')
383 # XXX: what are we testing here?
385 self.client.connect(TEST_MPD_HOST, TEST_MPD_PORT)
387 def test_connection_lost(self):
388 # Simulate a connection lost: the socket returns empty strings
389 self.MPDWillReturn('')
391 with self.assertRaises(musicpd.ConnectionError):
394 # consistent behaviour
395 # solves <https://github.com/Mic92/python-mpd2/issues/11> (also present
397 with self.assertRaises(musicpd.ConnectionError):
400 self.assertIs(self.client._sock, None)
402 def test_parse_sticker_get_no_sticker(self):
403 self.MPDWillReturn('ACK [50@0] {sticker} no such sticker\n')
404 self.assertRaises(musicpd.CommandError,
405 self.client.sticker_get, 'song', 'baz', 'foo')
407 def test_parse_sticker_list(self):
408 self.MPDWillReturn('sticker: foo=bar\n', 'sticker: lom=bok\n', 'OK\n')
409 res = self.client.sticker_list('song', 'baz')
410 self.assertEqual(['foo=bar', 'lom=bok'], res)
412 # Even with only one sticker, we get a dict
413 self.MPDWillReturn('sticker: foo=bar\n', 'OK\n')
414 res = self.client.sticker_list('song', 'baz')
415 self.assertEqual(['foo=bar'], res)
418 if __name__ == '__main__':