Exemplo n.º 1
0
def test_has_node():
    t = Trie()
    assert t.has_node(b"")
    assert not t.has_node(b"a")
    t[b"Hello"] = 0
    assert t.has_node(b"He")
    with pytest.raises(KeyError):
        t[b"He"]
    assert t.has_node(b"Hello")
    assert not t.has_node(b"Hello!")
    assert t[b"Hello"] == 0
Exemplo n.º 2
0
def test_delitem():
    t = Trie()
    t[b"hellothere"] = 0
    t[b"helloworld"] = 1
    assert t[b"hellothere"] == 0
    assert t[b"helloworld"] == 1
    assert t.has_node(b"hello")

    del t[b"hellothere"]
    with pytest.raises(KeyError):
        t[b"hellothere"]
    assert not t.has_node(b"hellothere")
    assert not t.has_node(b"hellot")
    assert t.has_node(b"hello")
    with pytest.raises(KeyError):
        t[b"hello"]
    assert t[b"helloworld"] == 1

    # Test removing strings with insertions staggered
    t = Trie()
    strings = [b"AB", b"ABCD", b"ABCDEFG", b"ABCDEFGHIJK"]
    for i, s in enumerate(strings):
        t[s] = i;
    assert t[b"AB"] == 0
    assert t[b"ABCDEFGHIJK"] == 3
    del t[b"AB"]
    assert t.has_node(b"AB")
    # Make sure string is removed
    with pytest.raises(KeyError):
        t[b"AB"]
    # Check the other strings were not affected
    for i, s in enumerate(strings[1:]):
        assert t[s] == i + 1
    # Should not be able to remove non-existent string
    assert t.has_node(b"ABC")
    with pytest.raises(Exception):
        del t[b"ABC"]
    with pytest.raises(Exception):
        del t[b"ABCDEFGHIJKL"]
    # Remove string in between two others
    del t[b"ABCDEFG"]
    assert t.has_node(b"ABCDEFG")
    with pytest.raises(KeyError):
        t[b"ABCDEFG"]
    assert t[b"ABCDEFGHIJK"] == 3
    # See if nodes are actually removed when a string at a leaf is removed
    del t[b"ABCDEFGHIJK"]
    assert t.has_node(b"ABCD")
    assert t[b"ABCD"] == 1
    assert not t.has_node(b"ABCDE")
    with pytest.raises(KeyError):
        t[b"ABCDEFG"]
    with pytest.raises(KeyError):
        t[b"ABCDEFGHIJK"]
    # Remove the last string
    del t[b"ABCD"]
    assert not t.has_node(b"ABCD")
    assert not t.has_node(b"A")
    assert t.has_node(b"")
    with pytest.raises(KeyError):
        t[b""]

    # Test edge case where empty string is inserted and removed
    with pytest.raises(KeyError):
        t[b""]
    t[b""] = 0
    assert t[b""] == 0
    del t[b""]
    assert t.has_node(b"")
    with pytest.raises(KeyError):
        t[b""]