๐Ÿ’ป Exercise: Exercise: Cap delegation depth

๐Ÿ“ Instructions

Implement DelegationError(RuntimeError) and a DelegationCap class constructed with max_depth (and optional depth=0). enter() returns a NEW DelegationCap one level deeper, but raises DelegationError if the current depth is already at max_depth. allows() returns whether another level is permitted. Standard library only.

๐Ÿงช Initial Code / Tests

๐Ÿ“„ evaluate.py
from unittest import TestCase
from exercise import DelegationCap, DelegationError


class Evaluate(TestCase):
    def test_enter_increments_depth(self):
        self.assertEqual(DelegationCap(3).enter().depth, 1)

    def test_enter_raises_past_cap(self):
        cap = DelegationCap(2).enter().enter()
        self.assertRaises(DelegationError, cap.enter)

    def test_allows_true_below_cap(self):
        self.assertTrue(DelegationCap(1).allows())

    def test_allows_false_at_cap(self):
        self.assertFalse(DelegationCap(2, 2).allows())

โœ… Solutions

๐Ÿ“„ exercise.py
class DelegationError(RuntimeError):
    pass


class DelegationCap:
    def __init__(self, max_depth, depth=0):
        self.max_depth = max_depth
        self.depth = depth

    def enter(self):
        if self.depth >= self.max_depth:
            raise DelegationError('delegation depth cap exceeded')
        return DelegationCap(self.max_depth, self.depth + 1)

    def allows(self):
        return self.depth < self.max_depth