]> kaliko git repositories - python-musicpd.git/blob - test.py
Fixed albumart command
[python-musicpd.git] / test.py
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 # pylint: disable=missing-docstring
4 """
5 Test suite highly borrowed^Wsteal from python-mpd2 [0] project.
6
7 [0] https://github.com/Mic92/python-mpd2
8 """
9
10
11 import itertools
12 import os
13 import sys
14 import types
15 import unittest
16 import warnings
17
18 import musicpd
19
20 try:
21     import unittest.mock as mock
22 except ImportError:
23     try:
24         import mock
25     except ImportError:
26         print("Please install mock from PyPI to run tests!")
27         sys.exit(1)
28
29 # show deprecation warnings
30 warnings.simplefilter('default')
31
32
33 TEST_MPD_HOST, TEST_MPD_PORT = ('example.com', 10000)
34
35
36 class testEnvVar(unittest.TestCase):
37
38     def test_envvar(self):
39         os.environ.pop('MPD_HOST', None)
40         os.environ.pop('MPD_PORT', None)
41         client = musicpd.MPDClient()
42         self.assertEqual(client.host, 'localhost')
43         self.assertEqual(client.port, '6600')
44
45         os.environ['MPD_HOST'] = 'pa55w04d@example.org'
46         client = musicpd.MPDClient()
47         self.assertEqual(client.pwd, 'pa55w04d')
48         self.assertEqual(client.host, 'example.org')
49         self.assertEqual(client.port, '6600')
50
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')
57
58         # Test unix socket fallback
59         os.environ.pop('MPD_HOST', None)
60         os.environ.pop('MPD_PORT', None)
61         os.environ.pop('XDG_RUNTIME_DIR', None)
62         with mock.patch('os.path.exists', return_value=True):
63             client = musicpd.MPDClient()
64             self.assertEqual(client.host, '/run/mpd/socket')
65
66         os.environ.pop('MPD_HOST', None)
67         os.environ.pop('MPD_PORT', None)
68         os.environ['XDG_RUNTIME_DIR'] = '/run/user/1000/'
69         with mock.patch('os.path.exists', return_value=True):
70             client = musicpd.MPDClient()
71             self.assertEqual(client.host, '/run/user/1000/mpd/socket')
72
73 class TestMPDClient(unittest.TestCase):
74
75     longMessage = True
76     # last sync: musicpd 0.4.2 unreleased / Mon Nov 17 21:45:22 CET 2014
77     commands = {
78             # Status Commands
79             'clearerror':         'nothing',
80             'currentsong':        'object',
81             'idle':               'list',
82             'noidle':             None,
83             'status':             'object',
84             'stats':              'object',
85             # Playback Option Commands
86             'consume':            'nothing',
87             'crossfade':          'nothing',
88             'mixrampdb':          'nothing',
89             'mixrampdelay':       'nothing',
90             'random':             'nothing',
91             'repeat':             'nothing',
92             'setvol':             'nothing',
93             'single':             'nothing',
94             'replay_gain_mode':   'nothing',
95             'replay_gain_status': 'item',
96             'volume':             'nothing',
97             # Playback Control Commands
98             'next':               'nothing',
99             'pause':              'nothing',
100             'play':               'nothing',
101             'playid':             'nothing',
102             'previous':           'nothing',
103             'seek':               'nothing',
104             'seekid':             'nothing',
105             'seekcur':            'nothing',
106             'stop':               'nothing',
107             # Playlist Commands
108             'add':                'nothing',
109             'addid':              'item',
110             'clear':              'nothing',
111             'delete':             'nothing',
112             'deleteid':           'nothing',
113             'move':               'nothing',
114             'moveid':             'nothing',
115             'playlist':           'playlist',
116             'playlistfind':       'songs',
117             'playlistid':         'songs',
118             'playlistinfo':       'songs',
119             'playlistsearch':     'songs',
120             'plchanges':          'songs',
121             'plchangesposid':     'changes',
122             'prio':               'nothing',
123             'prioid':             'nothing',
124             'rangeid':            'nothing',
125             'shuffle':            'nothing',
126             'swap':               'nothing',
127             'swapid':             'nothing',
128             'addtagid':           'nothing',
129             'cleartagid':         'nothing',
130             # Stored Playlist Commands
131             'listplaylist':       'list',
132             'listplaylistinfo':   'songs',
133             'listplaylists':      'playlists',
134             'load':               'nothing',
135             'playlistadd':        'nothing',
136             'playlistclear':      'nothing',
137             'playlistdelete':     'nothing',
138             'playlistmove':       'nothing',
139             'rename':             'nothing',
140             'rm':                 'nothing',
141             'save':               'nothing',
142             # Database Commands
143             'count':              'object',
144             'find':               'songs',
145             'findadd':            'nothing',
146             'list':               'list',
147             'listall':            'database',
148             'listallinfo':        'database',
149             'lsinfo':             'database',
150             'search':             'songs',
151             'searchadd':          'nothing',
152             'searchaddpl':        'nothing',
153             'update':             'item',
154             'rescan':             'item',
155             'readcomments':       'object',
156             # Mounts and neighbors
157             'mount':              'nothing',
158             'unmount':            'nothing',
159             'listmounts':         'mounts',
160             'listneighbors':      'neighbors',
161             # Sticker Commands
162             'sticker get':        'item',
163             'sticker set':        'nothing',
164             'sticker delete':     'nothing',
165             'sticker list':       'list',
166             'sticker find':       'songs',
167             # Connection Commands
168             'close':              None,
169             'kill':               None,
170             'password':           'nothing',
171             'ping':               'nothing',
172             # Partition Commands
173             'partition':          'nothing',
174             'listpartitions':     'list',
175             'newpartition':       'nothing',
176             # Audio Output Commands
177             'disableoutput':      'nothing',
178             'enableoutput':       'nothing',
179             'toggleoutput':       'nothing',
180             'outputs':            'outputs',
181             # Reflection Commands
182             'config':             'object',
183             'commands':           'list',
184             'notcommands':        'list',
185             'tagtypes':           'list',
186             'urlhandlers':        'list',
187             'decoders':           'plugins',
188             # Client to Client
189             'subscribe':          'nothing',
190             'unsubscribe':        'nothing',
191             'channels':           'list',
192             'readmessages':       'messages',
193             'sendmessage':        'nothing',
194         }
195
196     def setUp(self):
197         self.socket_patch = mock.patch('musicpd.socket')
198         self.socket_mock = self.socket_patch.start()
199         self.socket_mock.getaddrinfo.return_value = [range(5)]
200
201         self.socket_mock.socket.side_effect = (
202             lambda *a, **kw:
203             # Create a new socket.socket() mock with default attributes,
204             # each time we are calling it back (otherwise, it keeps set
205             # attributes across calls).
206             # That's probably what we want, since reconnecting is like
207             # reinitializing the entire connection, and so, the mock.
208             mock.MagicMock(name='socket.socket'))
209
210         self.client = musicpd.MPDClient()
211         self.client.connect(TEST_MPD_HOST, TEST_MPD_PORT)
212         self.client._sock.reset_mock()
213         self.MPDWillReturn('ACK don\'t forget to setup your mock\n')
214
215     def tearDown(self):
216         self.socket_patch.stop()
217
218     def MPDWillReturn(self, *lines):
219         # Return what the caller wants first, then do as if the socket was
220         # disconnected.
221         self.client._rfile.readline.side_effect = itertools.chain(
222             lines, itertools.repeat(''))
223
224     def MPDWillReturnBinary(self, lines):
225         data = bytearray(b''.join(lines))
226         print(data)
227
228         def recv(amount):
229             val = bytearray()
230             while amount > 0:
231                 amount -= 1
232                 _ = data.pop(0)
233                 print(hex(_))
234                 val.append(_)
235             return val
236
237         def readline():
238             val = bytearray()
239             while not val.endswith(b'\x0a'):
240                 val.append(data.pop(0))
241             return val
242         self.client._rbfile.readline.side_effect = readline
243         self.client._rbfile.recv.side_effect = recv
244
245     def assertMPDReceived(self, *lines):
246         self.client._wfile.write.assert_called_with(*lines)
247
248     def test_metaclass_commands(self):
249         """Controls client has at least commands as last synchronized in
250         TestMPDClient.commands"""
251         for cmd, ret in TestMPDClient.commands.items():
252             self.assertTrue(hasattr(self.client, cmd), msg='cmd "{}" not available!'.format(cmd))
253             if ' ' in cmd:
254                 self.assertTrue(hasattr(self.client, cmd.replace(' ', '_')))
255
256     def test_fetch_nothing(self):
257         self.MPDWillReturn('OK\n')
258         self.assertIsNone(self.client.ping())
259         self.assertMPDReceived('ping\n')
260
261     def test_fetch_list(self):
262         self.MPDWillReturn('OK\n')
263         self.assertIsInstance(self.client.list('album'), list)
264         self.assertMPDReceived('list "album"\n')
265
266     def test_fetch_item(self):
267         self.MPDWillReturn('updating_db: 42\n', 'OK\n')
268         self.assertIsNotNone(self.client.update())
269
270     def test_fetch_object(self):
271         # XXX: _read_objects() doesn't wait for the final OK
272         self.MPDWillReturn('volume: 63\n', 'OK\n')
273         status = self.client.status()
274         self.assertMPDReceived('status\n')
275         self.assertIsInstance(status, dict)
276
277         # XXX: _read_objects() doesn't wait for the final OK
278         self.MPDWillReturn('OK\n')
279         stats = self.client.stats()
280         self.assertMPDReceived('stats\n')
281         self.assertIsInstance(stats, dict)
282
283     def test_fetch_songs(self):
284         self.MPDWillReturn('file: my-song.ogg\n', 'Pos: 0\n', 'Id: 66\n', 'OK\n')
285         playlist = self.client.playlistinfo()
286
287         self.assertMPDReceived('playlistinfo\n')
288         self.assertIsInstance(playlist, list)
289         self.assertEqual(1, len(playlist))
290         e = playlist[0]
291         self.assertIsInstance(e, dict)
292         self.assertEqual('my-song.ogg', e['file'])
293         self.assertEqual('0', e['pos'])
294         self.assertEqual('66', e['id'])
295
296     def test_send_and_fetch(self):
297         self.MPDWillReturn('volume: 50\n', 'OK\n')
298         result = self.client.send_status()
299         self.assertEqual(None, result)
300         self.assertMPDReceived('status\n')
301
302         status = self.client.fetch_status()
303         self.assertEqual(1, self.client._wfile.write.call_count)
304         self.assertEqual({'volume': '50'}, status)
305
306     def test_iterating(self):
307         self.MPDWillReturn('file: my-song.ogg\n', 'Pos: 0\n', 'Id: 66\n',
308                            'file: my-song.ogg\n', 'Pos: 0\n', 'Id: 66\n', 'OK\n')
309         self.client.iterate = True
310         playlist = self.client.playlistinfo()
311         self.assertMPDReceived('playlistinfo\n')
312         self.assertIsInstance(playlist, types.GeneratorType)
313         self.assertTrue(self.client._iterating)
314         for song in playlist:
315             self.assertRaises(musicpd.IteratingError, self.client.status)
316             self.assertIsInstance(song, dict)
317             self.assertEqual('my-song.ogg', song['file'])
318             self.assertEqual('0', song['pos'])
319             self.assertEqual('66', song['id'])
320         self.assertFalse(self.client._iterating)
321
322     def test_noidle(self):
323         self.MPDWillReturn('OK\n') # nothing changed after idle-ing
324         self.client.send_idle()
325         self.MPDWillReturn('OK\n') # nothing changed after noidle
326         self.assertEqual(self.client.noidle(), [])
327         self.assertMPDReceived('noidle\n')
328         self.MPDWillReturn('volume: 50\n', 'OK\n')
329         self.client.status()
330         self.assertMPDReceived('status\n')
331
332     def test_noidle_while_idle_started_sending(self):
333         self.MPDWillReturn('OK\n') # nothing changed after idle
334         self.client.send_idle()
335         self.MPDWillReturn('CHANGED: player\n', 'OK\n')  # noidle response
336         self.assertEqual(self.client.noidle(), ['player'])
337         self.MPDWillReturn('volume: 50\n', 'OK\n')
338         status = self.client.status()
339         self.assertMPDReceived('status\n')
340         self.assertEqual({'volume': '50'}, status)
341
342     def test_throw_when_calling_noidle_withoutidling(self):
343         self.assertRaises(musicpd.CommandError, self.client.noidle)
344         self.client.send_status()
345         self.assertRaises(musicpd.CommandError, self.client.noidle)
346
347     def test_client_to_client(self):
348         # client to client is at this time in beta!
349
350         self.MPDWillReturn('OK\n')
351         self.assertIsNone(self.client.subscribe("monty"))
352         self.assertMPDReceived('subscribe "monty"\n')
353
354         self.MPDWillReturn('channel: monty\n', 'OK\n')
355         channels = self.client.channels()
356         self.assertMPDReceived('channels\n')
357         self.assertEqual(['monty'], channels)
358
359         self.MPDWillReturn('OK\n')
360         self.assertIsNone(self.client.sendmessage('monty', 'SPAM'))
361         self.assertMPDReceived('sendmessage "monty" "SPAM"\n')
362
363         self.MPDWillReturn('channel: monty\n', 'message: SPAM\n', 'OK\n')
364         msg = self.client.readmessages()
365         self.assertMPDReceived('readmessages\n')
366         self.assertEqual(msg, [{'channel': 'monty', 'message': 'SPAM'}])
367
368         self.MPDWillReturn('OK\n')
369         self.assertIsNone(self.client.unsubscribe('monty'))
370         self.assertMPDReceived('unsubscribe "monty"\n')
371
372         self.MPDWillReturn('OK\n')
373         channels = self.client.channels()
374         self.assertMPDReceived('channels\n')
375         self.assertEqual([], channels)
376
377     def test_ranges_in_command_args(self):
378         self.MPDWillReturn('OK\n')
379         self.client.playlistinfo((10,))
380         self.assertMPDReceived('playlistinfo 10:\n')
381
382         self.MPDWillReturn('OK\n')
383         self.client.playlistinfo(('10',))
384         self.assertMPDReceived('playlistinfo 10:\n')
385
386         self.MPDWillReturn('OK\n')
387         self.client.playlistinfo((10, 12))
388         self.assertMPDReceived('playlistinfo 10:12\n')
389
390         self.MPDWillReturn('OK\n')
391         self.client.rangeid(())
392         self.assertMPDReceived('rangeid :\n')
393
394         for arg in [(10, 't'), (10, 1, 1), (None,1)]:
395             self.MPDWillReturn('OK\n')
396             with self.assertRaises(musicpd.CommandError):
397                 self.client.playlistinfo(arg)
398
399     def test_numbers_as_command_args(self):
400         self.MPDWillReturn('OK\n')
401         self.client.find('file', 1)
402         self.assertMPDReceived('find "file" "1"\n')
403
404     def test_commands_without_callbacks(self):
405         self.MPDWillReturn('\n')
406         self.client.close()
407         self.assertMPDReceived('close\n')
408
409         # XXX: what are we testing here?
410         self.client._reset()
411         self.client.connect(TEST_MPD_HOST, TEST_MPD_PORT)
412
413     def test_connection_lost(self):
414         # Simulate a connection lost: the socket returns empty strings
415         self.MPDWillReturn('')
416
417         with self.assertRaises(musicpd.ConnectionError):
418             self.client.status()
419
420         # consistent behaviour
421         # solves <https://github.com/Mic92/python-mpd2/issues/11> (also present
422         # in python-mpd)
423         with self.assertRaises(musicpd.ConnectionError):
424             self.client.status()
425
426         self.assertIs(self.client._sock, None)
427
428     def test_parse_sticker_get_no_sticker(self):
429         self.MPDWillReturn('ACK [50@0] {sticker} no such sticker\n')
430         self.assertRaises(musicpd.CommandError,
431                           self.client.sticker_get, 'song', 'baz', 'foo')
432
433     def test_parse_sticker_list(self):
434         self.MPDWillReturn('sticker: foo=bar\n', 'sticker: lom=bok\n', 'OK\n')
435         res = self.client.sticker_list('song', 'baz')
436         self.assertEqual(['foo=bar', 'lom=bok'], res)
437
438         # Even with only one sticker, we get a dict
439         self.MPDWillReturn('sticker: foo=bar\n', 'OK\n')
440         res = self.client.sticker_list('song', 'baz')
441         self.assertEqual(['foo=bar'], res)
442
443     def test_albumart(self):
444         # here is a 34 bytes long data
445         data = bytes('\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01'
446                      '\x00\x01\x00\x00\xff\xdb\x00C\x00\x05\x03\x04',
447                      encoding='utf8')
448         read_lines = [b'size: 42\nbinary: 34\n', data, b'\nOK\n']
449         self.MPDWillReturnBinary(read_lines)
450         # Reading albumart / offset 0 should return the data
451         res = self.client.albumart('muse/Raised Fist/2002-Dedication/', 0)
452         self.assertEqual(res.get('data'), data)
453
454
455 if __name__ == '__main__':
456     unittest.main()