def test_keys_items_values(): t = Trie() t[b"foo"] = 5 assert t.keys() == ["foo"] assert t.values() == [5] assert t.items() == [("foo", 5)] t[b"foobar"] = 3 t[b"hello"] = 7 assert set(t.keys()) == set(["foo", "foobar", "hello"]) assert set(t.values()) == set([5, 3, 7]) assert set(t.items()) == set([("foo", 5), ("foobar", 3), ("hello", 7)]) t = Trie() n = 1000 for i in xrange(n): t[b(str(i))] = i assert len(t.keys()) == n values = xrange(n) keys = [str(x) for x in values] assert set(t.keys()) == set(keys) assert set(t.values()) == set(values) assert set(t.items()) == set(zip(keys, values))
def test_iter(): """Test iterating over a Trie""" t = Trie() words = [b"hello", b"foo", b"foobar", b"foozle"] for key in words: t[key] = 1 assert set([b(key) for key in t]) == set(words) # Modify values in the trie using t's iterator for key in t: t[b(key)] = 2 assert t.values() == [2]*len(words) # It should be an error to continue to iterate after adding and/or removing # nodes. i1 = iter(t) next(i1) # This should be fine t[b"new"] = 1 with pytest.raises(RuntimeError): next(i1) # Alright, so addition was detected, now for deletion i2 = iter(t) del t[b"new"] with pytest.raises(RuntimeError): next(i2) # Detection should not be on number of nodes, so let's add and remove a # single node. i3 = iter(t) next(i3) # should be fine n = t.num_nodes() t[b"a"] = 1 assert t.num_nodes() == n + 1 del t[b"a"] assert t.num_nodes() == n with pytest.raises(RuntimeError): next(i3)