๐Ÿ’ป Exercise: Exercise: Route a message

๐Ÿ“ Instructions

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.

๐Ÿงช Initial Code / Tests

๐Ÿ“„ evaluate.py
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)

โœ… Solutions

๐Ÿ“„ exercise.py
def route_message(message, roles):
    recipient = message['recipient']
    if recipient not in roles:
        raise KeyError("no agent for role '" + str(recipient) + "'")
    return roles[recipient]