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