class DBDB(object): def __init__(self, f): self._storage = Storage(f) self._tree = RedBlackTree(self._storage) def _assert_not_closed(self): if self._storage.closed: raise ValueError('Database closed.') def close(self): self._storage.close() def commit(self): self._assert_not_closed() self._tree.commit() def get(self, key): self._assert_not_closed() return self._tree.get(key) def set(self, key, value): self._assert_not_closed() return self._tree.set(key, value) def get_smaller_than(self, key): self._assert_not_closed() return self._tree.get_smaller_than(key)
def test_random_set_and_get_keys(): tree = RedBlackTree(StubStorage()) ten_k = list(range(10000)) pairs = list(zip(random.sample(ten_k, 10), random.sample(ten_k, 10))) for i, (k, v) in enumerate(pairs, start=1): tree.set(k, v) for k, v in pairs: assert tree.get(k) == v
def __init__(self, f): self._storage = Storage(f) self._tree = RedBlackTree(self._storage)
def test_overwrite_and_get_key(): tree = RedBlackTree(StubStorage()) tree.set('a', 'b') tree.set('a', 'c') assert tree.get('a') == 'c'
def test_set_and_get_key(): tree = RedBlackTree(StubStorage()) tree.set('a', 'b') assert tree.get('a') == 'b'
def test_missing_key(): tree = RedBlackTree(StubStorage()) with raises(KeyError): tree.get('key')
def test_red_children_are_black(): t = RedBlackTree(StubStorage()) t.set(2,1) t.set(7,1) t.set(3,1) t.set(5,1) t.set(6,1) t.set(1,1) t.set(4,1) t.set(8,1) t.set(9,1) t.set(10,1) t.set(11,1) t.set(12,1) t.set(13,1) t.set(14,1) t.set(15,1) t.set(16,1) rootNode = t._follow(t._tree_ref) assert red_children_are_black(t, rootNode)
def test_root_black_property(): t = RedBlackTree(StubStorage()) t.set(2,1) t.set(7,1) t.set(3,1) t.set(5,1) t.set(6,1) t.set(1,1) t.set(4,1) t.set(8,1) t.set(9,1) t.set(10,1) t.set(11,1) t.set(12,1) t.set(13,1) t.set(14,1) t.set(15,1) t.set(16,1) rootNode = t._follow(t._tree_ref) assert root_black(rootNode)