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