37/39
Part 7 of 7 · Follow-upsLearn

What tests would you write?

A walk with a limit, as at the top of this lesson, and a node that counts how often anyone follows next, so the code under test can't loop forever either. The practice problem's tests use the same idea on their hops:

class Budget:
    left = 0


class CountingNode:
    __slots__ = ("val", "_next")

    def __init__(self, val, next=None):
        self.val, self._next = val, next

    @property
    def next(self):
        Budget.left -= 1
        if Budget.left < 0:
            raise AssertionError("followed .next too many times: a walk that never ends")
        return self._next

    @next.setter
    def next(self, node):
        self._next = node

@property turns next into a method that runs whenever code reads node.next, and @next.setter runs whenever code assigns it. So every step along the list costs one unit of the budget, and the class needs no other change. Set Budget.left to a few times what a correct walk needs before each call. Then write the cases:

  • the empty list, one node and two nodes
  • a cycle back to the head, and a node pointing at itself
  • two lists with equal values on different nodes