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