Write route_message(message, roles), where message is a dict with a 'recipient' key and roles maps role name -> handler. Return the handler for the recipient. Raise KeyError if no such role exists. Standard library only.
from unittest import TestCase
from exercise import route_message
class Evaluate(TestCase):
def test_routes_to_recipient(self):
self.assertEqual(route_message({'recipient': 'writer'}, {'writer': 'W'}), 'W')
def test_unknown_recipient_raises(self):
self.assertRaises(KeyError, route_message, {'recipient': 'ghost'}, {'writer': 'W'})
def test_picks_correct_among_many(self):
roles = {'a': 1, 'b': 2, 'c': 3}
self.assertEqual(route_message({'recipient': 'b'}, roles), 2)
def route_message(message, roles):
recipient = message['recipient']
if recipient not in roles:
raise KeyError("no agent for role '" + str(recipient) + "'")
return roles[recipient]