Before writing example-based tests for a container, I write one property: "it behaves like the obvious slow implementation." Here the container is a fixed-capacity ring buffer, the model is a deque plus a length check.
from collections import deque
from hypothesis import given, strategies as st
class RingBuffer:
def __init__(self, cap):
self.buf = [None] * cap
self.head = 0
self.size = 0
def push(self, x):
if self.size == len(self.buf):
return False
self.buf[(self.head + self.size) % len(self.buf)] = x
self.size += 1
return True
def pop(self):
if self.size == 0:
return None
x = self.buf[self.head]
self.head = (self.head + 1) % len(self.buf)
self.size -= 1
return x
ops = st.lists(st.one_of(
st.tuples(st.just("push"), st.integers()),
st.tuples(st.just("pop"), st.none())))
@given(ops, st.integers(min_value=1, max_value=8))
def test_matches_model(operations, cap):
rb, model = RingBuffer(cap), deque()
for op, x in operations:
if op == "push":
ok = rb.push(x)
assert ok == (len(model) < cap)
if ok:
model.append(x)
else:
assert rb.pop() == (model.popleft() if model else None)
The framework generates hundreds of operation sequences, and when one fails it shrinks it to a minimal one. Bugs in wraparound (an off-by-one in % len) show up in seconds. My failure model for the test: single thread, no crash. Concurrency is another post.