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