Sub topic 11
Testing wraparound and edge cases
This chapter assumes you can read the Python RingBuffer from the earlier chapters: push, pop, a _count field, and (head + count) % capacity for the tail. It also assumes you know Python's unittest module. The tests below use only the standard library.
Where ring buffer bugs hide
Most ring buffer bugs show up only after the indices have wrapped at least once. A buffer that passes "push three, pop three" can still fail on the fourth push. Good tests therefore target the boundaries of the structure.
| Case | What it catches |
|---|---|
| Pop from an empty buffer | A missing empty check, or a stale value returned |
| Push to a full buffer | Silent overwrite of unread data |
| Capacity of 1 | Off-by-one errors, since head and tail share one slot |
| Many laps around the array | A wrong modulo, or a count that drifts |
| Overwrite policy after many pushes | Dropping the wrong end |
| State after a failed call | An exception that still changes the count or the indices |
The states you must visit
A buffer is always empty, partly filled, or full. Your tests should cross every edge between these states, in both directions.
A test suite
Save the RingBuffer class and push_overwrite from earlier chapters as ring_buffer.py. Then save this file next to it as test_ring_buffer.py.
import random
import unittest
from collections import deque
from ring_buffer import RingBuffer, push_overwrite
def drain(rb):
return [rb.pop() for _ in range(len(rb))]
class RingBufferTests(unittest.TestCase):
def test_rejects_bad_capacity(self):
with self.assertRaises(ValueError):
RingBuffer(0)
def test_pop_empty_raises(self):
with self.assertRaises(IndexError):
RingBuffer(3).pop()
def test_push_full_raises_and_keeps_state(self):
rb = RingBuffer(2)
rb.push(1)
rb.push(2)
with self.assertRaises(OverflowError):
rb.push(3)
self.assertEqual(len(rb), 2)
self.assertEqual(drain(rb), [1, 2])
def test_capacity_one(self):
rb = RingBuffer(1)
for i in range(5):
rb.push(i)
self.assertEqual(rb.pop(), i)
def test_many_laps_keep_fifo_order(self):
rb = RingBuffer(3)
for i in range(100):
rb.push(i)
self.assertEqual(rb.pop(), i)
self.assertEqual(len(rb), 0)
def test_overwrite_keeps_newest(self):
rb = RingBuffer(3)
for i in range(10):
push_overwrite(rb, i)
self.assertEqual(drain(rb), [7, 8, 9])
def test_matches_deque_model(self):
rng = random.Random(1234)
rb, model = RingBuffer(4), deque()
for step in range(2000):
if rng.random() < 0.5:
if len(model) == 4:
with self.assertRaises(OverflowError):
rb.push(step)
else:
rb.push(step)
model.append(step)
elif not model:
with self.assertRaises(IndexError):
rb.pop()
else:
self.assertEqual(rb.pop(), model.popleft())
self.assertEqual(len(rb), len(model))
if __name__ == "__main__":
unittest.main()Run it with python test_ring_buffer.py.
Why the model test matters
The last test is a model-based test. It runs random pushes and pops against both your buffer and a deque, which is a trusted queue, and compares every result. A fixed seed makes any failure reproducible. This finds sequences you would not think to write by hand, such as pop, pop, push, push, push on a half-wrapped buffer.
The test also checks len(rb) after every step. A drifting count is the most common silent failure, because the data can look right for a while.
Testing the C versions
The C ring with free-running indices has one extra risk. The unsigned indices overflow after 2^32 operations, and no realistic test loop reaches that. Instead, set head and tail to a value just below the limit, for example 0xFFFFFFFE, and push a few items. tail - head must still give the right count, and the mask must still select the right slots.
For the lock-free version, single-threaded tests are not enough. A stress test with one producer thread and one consumer thread should send a long numbered sequence. The consumer then checks that it receives every number, in order. Running it under ThreadSanitizer finds missing acquire or release ordering that ordinary runs hide.
Exercise
A buffer of capacity 4 passes a test that pushes 4 items and pops 4 items. Name one more test that would catch a wrong modulo, and say why the first test misses it.
Show answer
Push and pop one item at a time for more than 4 rounds, checking each popped value, so the indices wrap past the end of the array. The first test only touches slots 0 to 3 and never wraps, so a wrong modulo is never exercised.