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