]> kaliko git repositories - python-musicpd.git/blob - test.py
Fixed tests
[python-musicpd.git] / test.py
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 """
4 Test suite highly borrowed^Wsteal from python-mpd2 [0] project.
5
6 [0] https://github.com/Mic92/python-mpd2
7 """
8
9
10 import itertools
11 import os
12 import sys
13 import types
14 import unittest
15 import warnings
16
17 import musicpd
18
19 try:
20     import unittest.mock as mock
21 except ImportError:
22     try:
23         import mock
24     except ImportError:
25         print("Please install mock from PyPI to run tests!")
26         sys.exit(1)
27
28 # show deprecation warnings
29 warnings.simplefilter('default')
30
31
32 TEST_MPD_HOST, TEST_MPD_PORT = ('example.com', 10000)
33
34
35 class testEnvVar(unittest.TestCase):
36
37     def test_envvar(self):
38         os.environ.pop('MPD_HOST', None)
39         os.environ.pop('MPD_PORT', None)
40         client = musicpd.MPDClient()
41         self.assertEqual(client.host, 'localhost')
42         self.assertEqual(client.port, '6600')
43
44         os.environ['MPD_HOST'] = 'pa55w04d@example.org'
45         client = musicpd.MPDClient()
46         self.assertEqual(client.pwd, 'pa55w04d')
47         self.assertEqual(client.host, 'example.org')
48         self.assertEqual(client.port, '6600')
49
50         os.environ.pop('MPD_HOST', None)
51         os.environ['MPD_PORT'] = '6666'
52         client = musicpd.MPDClient()
53         self.assertEqual(client.pwd, None)
54         self.assertEqual(client.host, 'localhost')
55         self.assertEqual(client.port, '6666')
56
57         # Test unix socket fallback
58         os.environ.pop('MPD_HOST', None)
59         os.environ.pop('MPD_PORT', None)
60         os.environ.pop('XDG_RUNTIME_DIR', None)
61         with mock.patch('os.path.exists', return_value=True):
62             client = musicpd.MPDClient()
63             self.assertEqual(client.host, '/run/mpd/socket')
64
65         os.environ.pop('MPD_HOST', None)
66         os.environ.pop('MPD_PORT', None)
67         os.environ['XDG_RUNTIME_DIR'] = '/run/user/1000/'
68         with mock.patch('os.path.exists', return_value=True):
69             client = musicpd.MPDClient()
70             self.assertEqual(client.host, '/run/user/1000/mpd/socket')
71
72 class TestMPDClient(unittest.TestCase):
73
74     longMessage = True
75     # last sync: musicpd 0.4.2 unreleased / Mon Nov 17 21:45:22 CET 2014
76     commands = {
77             # Status Commands
78             'clearerror':         'nothing',
79             'currentsong':        'object',
80             'idle':               'list',
81             'noidle':             None,
82             'status':             'object',
83             'stats':              'object',
84             # Playback Option Commands
85             'consume':            'nothing',
86             'crossfade':          'nothing',
87             'mixrampdb':          'nothing',
88             'mixrampdelay':       'nothing',
89             'random':             'nothing',
90             'repeat':             'nothing',
91             'setvol':             'nothing',
92             'single':             'nothing',
93             'replay_gain_mode':   'nothing',
94             'replay_gain_status': 'item',
95             'volume':             'nothing',
96             # Playback Control Commands
97             'next':               'nothing',
98             'pause':              'nothing',
99             'play':               'nothing',
100             'playid':             'nothing',
101             'previous':           'nothing',
102             'seek':               'nothing',
103             'seekid':             'nothing',
104             'seekcur':            'nothing',
105             'stop':               'nothing',
106             # Playlist Commands
107             'add':                'nothing',
108             'addid':              'item',
109             'clear':              'nothing',
110             'delete':             'nothing',
111             'deleteid':           'nothing',
112             'move':               'nothing',
113             'moveid':             'nothing',
114             'playlist':           'playlist',
115             'playlistfind':       'songs',
116             'playlistid':         'songs',
117             'playlistinfo':       'songs',
118             'playlistsearch':     'songs',
119             'plchanges':          'songs',
120             'plchangesposid':     'changes',
121             'prio':               'nothing',
122             'prioid':             'nothing',
123             'rangeid':            'nothing',
124             'shuffle':            'nothing',
125             'swap':               'nothing',
126             'swapid':             'nothing',
127             'addtagid':           'nothing',
128             'cleartagid':         'nothing',
129             # Stored Playlist Commands
130             'listplaylist':       'list',
131             'listplaylistinfo':   'songs',
132             'listplaylists':      'playlists',
133             'load':               'nothing',
134             'playlistadd':        'nothing',
135             'playlistclear':      'nothing',
136             'playlistdelete':     'nothing',
137             'playlistmove':       'nothing',
138             'rename':             'nothing',
139             'rm':                 'nothing',
140             'save':               'nothing',
141             # Database Commands
142             'count':              'object',
143             'find':               'songs',
144             'findadd':            'nothing',
145             'list':               'list',
146             'listall':            'database',
147             'listallinfo':        'database',
148             'lsinfo':             'database',
149             'search':             'songs',
150             'searchadd':          'nothing',
151             'searchaddpl':        'nothing',
152             'update':             'item',
153             'rescan':             'item',
154             'readcomments':       'object',
155             # Mounts and neighbors
156             'mount':              'nothing',
157             'unmount':            'nothing',
158             'listmounts':         'mounts',
159             'listneighbors':      'neighbors',
160             # Sticker Commands
161             'sticker get':        'item',
162             'sticker set':        'nothing',
163             'sticker delete':     'nothing',
164             'sticker list':       'list',
165             'sticker find':       'songs',
166             # Connection Commands
167             'close':              None,
168             'kill':               None,
169             'password':           'nothing',
170             'ping':               'nothing',
171             # Audio Output Commands
172             'disableoutput':      'nothing',
173             'enableoutput':       'nothing',
174             'toggleoutput':       'nothing',
175             'outputs':            'outputs',
176             # Reflection Commands
177             'config':             'object',
178             'commands':           'list',
179             'notcommands':        'list',
180             'tagtypes':           'list',
181             'urlhandlers':        'list',
182             'decoders':           'plugins',
183             # Client to Client
184             'subscribe':          'nothing',
185             'unsubscribe':        'nothing',
186             'channels':           'list',
187             'readmessages':       'messages',
188             'sendmessage':        'nothing',
189         }
190
191     def setUp(self):
192         self.socket_patch = mock.patch('musicpd.socket')
193         self.socket_mock = self.socket_patch.start()
194         self.socket_mock.getaddrinfo.return_value = [range(5)]
195
196         self.socket_mock.socket.side_effect = (
197             lambda *a, **kw:
198             # Create a new socket.socket() mock with default attributes,
199             # each time we are calling it back (otherwise, it keeps set
200             # attributes across calls).
201             # That's probably what we want, since reconnecting is like
202             # reinitializing the entire connection, and so, the mock.
203             mock.MagicMock(name='socket.socket'))
204
205         self.client = musicpd.MPDClient()
206         self.client.connect(TEST_MPD_HOST, TEST_MPD_PORT)
207         self.client._sock.reset_mock()
208         self.MPDWillReturn('ACK don\'t forget to setup your mock\n')
209
210     def tearDown(self):
211         self.socket_patch.stop()
212
213     def MPDWillReturn(self, *lines):
214         # Return what the caller wants first, then do as if the socket was
215         # disconnected.
216         self.client._rfile.readline.side_effect = itertools.chain(
217             lines, itertools.repeat(''))
218
219     def assertMPDReceived(self, *lines):
220         self.client._wfile.write.assert_called_with(*lines)
221
222     def test_metaclass_commands(self):
223         """Controls client has at least commands as last synchronized in
224         TestMPDClient.commands"""
225         for cmd, ret in TestMPDClient.commands.items():
226             self.assertTrue(hasattr(self.client, cmd), msg='cmd "{}" not available!'.format(cmd))
227             if ' ' in cmd:
228                 self.assertTrue(hasattr(self.client, cmd.replace(' ', '_')))
229
230     def test_fetch_nothing(self):
231         self.MPDWillReturn('OK\n')
232         self.assertIsNone(self.client.ping())
233         self.assertMPDReceived('ping\n')
234
235     def test_fetch_list(self):
236         self.MPDWillReturn('OK\n')
237         self.assertIsInstance(self.client.list('album'), list)
238         self.assertMPDReceived('list "album"\n')
239
240     def test_fetch_item(self):
241         self.MPDWillReturn('updating_db: 42\n', 'OK\n')
242         self.assertIsNotNone(self.client.update())
243
244     def test_fetch_object(self):
245         # XXX: _read_objects() doesn't wait for the final OK
246         self.MPDWillReturn('volume: 63\n', 'OK\n')
247         status = self.client.status()
248         self.assertMPDReceived('status\n')
249         self.assertIsInstance(status, dict)
250
251         # XXX: _read_objects() doesn't wait for the final OK
252         self.MPDWillReturn('OK\n')
253         stats = self.client.stats()
254         self.assertMPDReceived('stats\n')
255         self.assertIsInstance(stats, dict)
256
257     def test_fetch_songs(self):
258         self.MPDWillReturn('file: my-song.ogg\n', 'Pos: 0\n', 'Id: 66\n', 'OK\n')
259         playlist = self.client.playlistinfo()
260
261         self.assertMPDReceived('playlistinfo\n')
262         self.assertIsInstance(playlist, list)
263         self.assertEqual(1, len(playlist))
264         e = playlist[0]
265         self.assertIsInstance(e, dict)
266         self.assertEqual('my-song.ogg', e['file'])
267         self.assertEqual('0', e['pos'])
268         self.assertEqual('66', e['id'])
269
270     def test_send_and_fetch(self):
271         self.MPDWillReturn('volume: 50\n', 'OK\n')
272         result = self.client.send_status()
273         self.assertEqual(None, result)
274         self.assertMPDReceived('status\n')
275
276         status = self.client.fetch_status()
277         self.assertEqual(1, self.client._wfile.write.call_count)
278         self.assertEqual({'volume': '50'}, status)
279
280     def test_iterating(self):
281         self.MPDWillReturn('file: my-song.ogg\n', 'Pos: 0\n', 'Id: 66\n',
282                            'file: my-song.ogg\n', 'Pos: 0\n', 'Id: 66\n', 'OK\n')
283         self.client.iterate = True
284         playlist = self.client.playlistinfo()
285         self.assertMPDReceived('playlistinfo\n')
286         self.assertIsInstance(playlist, types.GeneratorType)
287         self.assertTrue(self.client._iterating)
288         for song in playlist:
289             self.assertRaises(musicpd.IteratingError, self.client.status)
290             self.assertIsInstance(song, dict)
291             self.assertEqual('my-song.ogg', song['file'])
292             self.assertEqual('0', song['pos'])
293             self.assertEqual('66', song['id'])
294         self.assertFalse(self.client._iterating)
295
296     def test_noidle(self):
297         self.MPDWillReturn('OK\n') # nothing changed after idle-ing
298         self.client.send_idle()
299         self.MPDWillReturn('OK\n') # nothing changed after noidle
300         self.assertEqual(self.client.noidle(), [])
301         self.assertMPDReceived('noidle\n')
302         self.MPDWillReturn('volume: 50\n', 'OK\n')
303         self.client.status()
304         self.assertMPDReceived('status\n')
305
306     def test_noidle_while_idle_started_sending(self):
307         self.MPDWillReturn('OK\n') # nothing changed after idle
308         self.client.send_idle()
309         self.MPDWillReturn('CHANGED: player\n', 'OK\n')  # noidle response
310         self.assertEqual(self.client.noidle(), ['player'])
311         self.MPDWillReturn('volume: 50\n', 'OK\n')
312         status = self.client.status()
313         self.assertMPDReceived('status\n')
314         self.assertEqual({'volume': '50'}, status)
315
316     def test_throw_when_calling_noidle_withoutidling(self):
317         self.assertRaises(musicpd.CommandError, self.client.noidle)
318         self.client.send_status()
319         self.assertRaises(musicpd.CommandError, self.client.noidle)
320
321     def test_client_to_client(self):
322         # client to client is at this time in beta!
323
324         self.MPDWillReturn('OK\n')
325         self.assertIsNone(self.client.subscribe("monty"))
326         self.assertMPDReceived('subscribe "monty"\n')
327
328         self.MPDWillReturn('channel: monty\n', 'OK\n')
329         channels = self.client.channels()
330         self.assertMPDReceived('channels\n')
331         self.assertEqual(['monty'], channels)
332
333         self.MPDWillReturn('OK\n')
334         self.assertIsNone(self.client.sendmessage('monty', 'SPAM'))
335         self.assertMPDReceived('sendmessage "monty" "SPAM"\n')
336
337         self.MPDWillReturn('channel: monty\n', 'message: SPAM\n', 'OK\n')
338         msg = self.client.readmessages()
339         self.assertMPDReceived('readmessages\n')
340         self.assertEqual(msg, [{'channel': 'monty', 'message': 'SPAM'}])
341
342         self.MPDWillReturn('OK\n')
343         self.assertIsNone(self.client.unsubscribe('monty'))
344         self.assertMPDReceived('unsubscribe "monty"\n')
345
346         self.MPDWillReturn('OK\n')
347         channels = self.client.channels()
348         self.assertMPDReceived('channels\n')
349         self.assertEqual([], channels)
350
351     def test_ranges_in_command_args(self):
352         self.MPDWillReturn('OK\n')
353         self.client.playlistinfo((10,))
354         self.assertMPDReceived('playlistinfo 10:\n')
355
356         self.MPDWillReturn('OK\n')
357         self.client.playlistinfo(('10',))
358         self.assertMPDReceived('playlistinfo 10:\n')
359
360         self.MPDWillReturn('OK\n')
361         self.client.playlistinfo((10, 12))
362         self.assertMPDReceived('playlistinfo 10:12\n')
363
364         self.MPDWillReturn('OK\n')
365         self.client.rangeid(())
366         self.assertMPDReceived('rangeid :\n')
367
368         for arg in [(10, 't'), (10, 1, 1), (None,1)]:
369             self.MPDWillReturn('OK\n')
370             with self.assertRaises(musicpd.CommandError):
371                 self.client.playlistinfo(arg)
372
373     def test_numbers_as_command_args(self):
374         self.MPDWillReturn('OK\n')
375         self.client.find('file', 1)
376         self.assertMPDReceived('find "file" "1"\n')
377
378     def test_commands_without_callbacks(self):
379         self.MPDWillReturn('\n')
380         self.client.close()
381         self.assertMPDReceived('close\n')
382
383         # XXX: what are we testing here?
384         self.client._reset()
385         self.client.connect(TEST_MPD_HOST, TEST_MPD_PORT)
386
387     def test_connection_lost(self):
388         # Simulate a connection lost: the socket returns empty strings
389         self.MPDWillReturn('')
390
391         with self.assertRaises(musicpd.ConnectionError):
392             self.client.status()
393
394         # consistent behaviour
395         # solves <https://github.com/Mic92/python-mpd2/issues/11> (also present
396         # in python-mpd)
397         with self.assertRaises(musicpd.ConnectionError):
398             self.client.status()
399
400         self.assertIs(self.client._sock, None)
401
402     def test_parse_sticker_get_no_sticker(self):
403         self.MPDWillReturn('ACK [50@0] {sticker} no such sticker\n')
404         self.assertRaises(musicpd.CommandError,
405                           self.client.sticker_get, 'song', 'baz', 'foo')
406
407     def test_parse_sticker_list(self):
408         self.MPDWillReturn('sticker: foo=bar\n', 'sticker: lom=bok\n', 'OK\n')
409         res = self.client.sticker_list('song', 'baz')
410         self.assertEqual(['foo=bar', 'lom=bok'], res)
411
412         # Even with only one sticker, we get a dict
413         self.MPDWillReturn('sticker: foo=bar\n', 'OK\n')
414         res = self.client.sticker_list('song', 'baz')
415         self.assertEqual(['foo=bar'], res)
416
417
418 if __name__ == '__main__':
419     unittest.main()