Sub topic 12
Cost of Each Operation and How to Test It
This chapter assumes you know Python classes, the stack data structure (push and pop), and the History class built earlier in this tutorial. It covers what each operation costs and how to test the history manager so you can trust it.
What each operation costs
Every operation touches only the end of a list or deque. That keeps the cost small and independent of how much history exists.
| Operation | Time | Notes |
|---|---|---|
| `do(command)` | O(1) plus the cost of `command.apply()` | `clear()` on the redo list costs O(r), where r is the number of redo entries, but each entry is cleared only once. |
| `undo()` | O(1) plus the cost of `command.revert()` | One pop and one append. |
| `redo()` | O(1) plus the cost of `command.apply()` | One pop and one append. |
The history bookkeeping is cheap. The expensive part is usually the command itself. In the text editor example, Insert.apply() builds a new string by slicing, which takes O(n) time for a document of n characters. So the real cost of an edit depends on the document, not on the stacks.
Space is a different matter. Each command stays in memory until it is dropped. With a command that stores only a position and a short string, the cost per entry is small. A snapshot approach stores a full copy of the state per entry, so its memory grows with document size times history length. This is why BoundedHistory caps the undo stack with a deque(maxlen=limit).
What to test
A history manager has a small set of behaviors. Each one should have a test:
do()applies the command.undo()reverts the most recent command and returnsTrue.redo()re-applies the command that was undone and returnsTrue.- Undo and redo run in last-in, first-out order across several commands.
- A new
do()after an undo clears the redo stack. undo()andredo()returnFalseon empty stacks and change nothing.- A bounded history forgets the oldest command once the limit is reached.
Writing the tests
A small fake command makes tests independent of the text editor. It records what happened to it, so you can check order and counts.
The code below defines History and BoundedHistory again so the file runs on its own. Save it as test_history.py and run it with python -m unittest test_history.py.
import unittest
from collections import deque
class History:
def __init__(self):
self._undo = []
self._redo = []
def do(self, command):
command.apply()
self._undo.append(command)
self._redo.clear()
def undo(self):
if not self._undo:
return False
command = self._undo.pop()
command.revert()
self._redo.append(command)
return True
def redo(self):
if not self._redo:
return False
command = self._redo.pop()
command.apply()
self._undo.append(command)
return True
class BoundedHistory(History):
def __init__(self, limit):
super().__init__()
self._undo = deque(maxlen=limit)
class Recorder:
"""A fake command that logs every apply and revert call."""
def __init__(self, name, log):
self.name = name
self.log = log
def apply(self):
self.log.append(("apply", self.name))
def revert(self):
self.log.append(("revert", self.name))
class HistoryTests(unittest.TestCase):
def setUp(self):
self.log = []
self.history = History()
def test_undo_and_redo_follow_lifo_order(self):
self.history.do(Recorder("a", self.log))
self.history.do(Recorder("b", self.log))
self.history.undo()
self.history.undo()
self.history.redo()
self.assertEqual(
self.log,
[("apply", "a"), ("apply", "b"),
("revert", "b"), ("revert", "a"),
("apply", "a")],
)
def test_new_action_clears_redo(self):
self.history.do(Recorder("a", self.log))
self.history.undo()
self.history.do(Recorder("b", self.log))
self.assertFalse(self.history.redo())
def test_empty_stacks_return_false_and_do_nothing(self):
self.assertFalse(self.history.undo())
self.assertFalse(self.history.redo())
self.assertEqual(self.log, [])
def test_bounded_history_forgets_oldest(self):
history = BoundedHistory(limit=2)
for name in ["a", "b", "c"]:
history.do(Recorder(name, self.log))
self.assertTrue(history.undo())
self.assertTrue(history.undo())
self.assertFalse(history.undo())
self.assertEqual(self.log[-2:], [("revert", "c"), ("revert", "b")])
if __name__ == "__main__":
unittest.main()The first test pins down the ordering rule. The second guards the most common bug, which is forgetting self._redo.clear() in do(). The third checks that empty stacks are safe. The fourth shows that command "a" was dropped: after two undos, the third undo() returns False.
Common testing mistakes
- Testing only the happy path. Bugs in a history manager usually show up in sequences such as undo, do, redo. Test those sequences.
- Checking only return values. A
Trueresult does not prove the right command was reverted. Check the log or the document state too. - Skipping the round trip. For real commands, apply then revert should restore the original state exactly. Test this for each command class, including edge positions such as 0 and the end of the text.
Exercise
A history holds 1,000 commands in its undo stack, and each command's revert takes constant time. How does the cost of one undo() call compare with a history holding 10 commands, and which test would you write to confirm that undo after a new do() cannot bring back an old command?
Show answer
The cost is the same. undo() pops one entry and appends one entry, so it does not depend on the stack size, and the constant-time revert adds a fixed amount. To check the second point, do command a, undo it, do command b, then assert that redo() returns False and that the log shows no second apply of a.