Refactor MpdDispatcher.handle_request

This commit is contained in:
Stein Magnus Jodal 2011-06-04 00:33:57 +02:00
parent bf175a3dce
commit 1db84dccca
3 changed files with 22 additions and 16 deletions

View File

@ -32,27 +32,33 @@ class MpdDispatcher(object):
self.command_list_ok = False
self.context = MpdContext(self, session=session)
def handle_request(self, request, command_list_index=None):
def handle_request(self, request, current_command_list_index=None):
"""Dispatch incoming requests to the correct handler."""
if self.command_list is not False and request != u'command_list_end':
if self._is_receiving_command_list(request):
self.command_list.append(request)
return None
try:
result = self._call_handler(request)
try:
result = self._call_handler(request)
except ActorDeadError as e:
logger.warning(u'Tried to communicate with dead actor.')
raise MpdSystemError(e.message)
except MpdAckError as e:
if command_list_index is not None:
e.index = command_list_index
if current_command_list_index is not None:
e.index = current_command_list_index
return self._format_response(e.get_mpd_ack(), add_ok=False)
except ActorDeadError as e:
logger.warning(u'Tried to communicate with dead actor.')
mpd_error = MpdSystemError(e.message)
return self._format_response(mpd_error.get_mpd_ack(), add_ok=False)
if request in (u'command_list_begin', u'command_list_ok_begin'):
return None
if command_list_index is not None:
if (request in (u'command_list_begin', u'command_list_ok_begin')
or current_command_list_index is not None):
return self._format_response(result, add_ok=False)
return self._format_response(result)
def _is_receiving_command_list(self, request):
return (self.command_list is not False
and request != u'command_list_end')
def _call_handler(self, request):
(handler, kwargs) = self._find_handler(request)
return handler(self.context, **kwargs)

View File

@ -32,9 +32,9 @@ def command_list_end(context):
(command_list_ok, context.dispatcher.command_list_ok) = (
context.dispatcher.command_list_ok, False)
result = []
for i, command in enumerate(command_list):
for index, command in enumerate(command_list):
response = context.dispatcher.handle_request(
command, command_list_index=i)
command, current_command_list_index=index)
if response is not None:
result.append(response)
if response and response[-1].startswith(u'ACK'):

View File

@ -16,7 +16,7 @@ class CommandListsTest(unittest.TestCase):
def test_command_list_begin(self):
result = self.dispatcher.handle_request(u'command_list_begin')
self.assert_(result is None)
self.assertEquals(result, [])
def test_command_list_end(self):
self.dispatcher.handle_request(u'command_list_begin')
@ -47,7 +47,7 @@ class CommandListsTest(unittest.TestCase):
def test_command_list_ok_begin(self):
result = self.dispatcher.handle_request(u'command_list_ok_begin')
self.assert_(result is None)
self.assertEquals(result, [])
def test_command_list_ok_with_ping(self):
self.dispatcher.handle_request(u'command_list_ok_begin')