| 1 |
from hassil.trie import Trie |
| 2 |
|
| 3 |
|
| 4 |
def test_insert_find() -> None: |
| 5 |
"""Test inserting and finding values in the trie.""" |
| 6 |
trie = Trie() |
| 7 |
trie.insert("1", 1) |
| 8 |
trie.insert("two", 2) |
| 9 |
trie.insert("10", 10) |
| 10 |
trie.insert("twenty two", 22) |
| 11 |
|
| 12 |
text = "set to 10" |
| 13 |
results = list(trie.find(text)) |
| 14 |
assert results == [(8, "1", 1), (9, "10", 10)] |
| 15 |
for end_pos, number_text, number_value in results: |
| 16 |
start_pos = end_pos - len(number_text) |
| 17 |
assert text[start_pos:end_pos] == number_text |
| 18 |
assert int(number_text) == number_value |
| 19 |
|
| 20 |
# With word boundaries |
| 21 |
results = list(trie.find(text, word_boundaries=True)) |
| 22 |
assert results == [(9, "10", 10)] |
| 23 |
|
| 24 |
assert list(trie.find("set to 1, then *two*, then finally twenty two please!")) == [ |
| 25 |
(8, "1", 1), |
| 26 |
(19, "two", 2), |
| 27 |
(45, "twenty two", 22), |
| 28 |
] |
| 29 |
|
| 30 |
# Without unique, *[two]* and twenty [two] will return 2 |
| 31 |
assert list( |
| 32 |
trie.find("set to 1, then *two*, then finally twenty two please!", unique=False) |
| 33 |
) == [ |
| 34 |
(8, "1", 1), |
| 35 |
(19, "two", 2), |
| 36 |
(45, "twenty two", 22), |
| 37 |
(45, "two", 2), |
| 38 |
] |
| 39 |
|
| 40 |
# Test a character in between |
| 41 |
assert not list(trie.find("tw|o")) |
| 42 |
|
| 43 |
# Test non-existent value |
| 44 |
assert not list(trie.find("three")) |
| 45 |
|
| 46 |
# Test empty string |
| 47 |
assert not list(trie.find("")) |
| 48 |
|
| 49 |
# Test word boundaries |
| 50 |
assert not list(trie.find("1two", word_boundaries=True)) |
| 51 |
assert list(trie.find("1,two", word_boundaries=True)) == [ |
| 52 |
(1, "1", 1), |
| 53 |
(5, "two", 2), |
| 54 |
] |
| 55 |
|
| 56 |
# ° is not a word boundary |
| 57 |
assert not list(trie.find("10°", word_boundaries=True)) |
| 58 |
|
| 59 |
|
| 60 |
def test_multiple_values() -> None: |
| 61 |
"""Test that we can insert multiple values for the same string.""" |
| 62 |
trie = Trie() |
| 63 |
trie.insert("test", 1) |
| 64 |
trie.insert("test", 2) |
| 65 |
|
| 66 |
assert list(trie.find("this is a test")) == [(14, "test", 1), (14, "test", 2)] |
| 67 |
|
| 68 |
|
| 69 |
def test_find_ignore_case() -> None: |
| 70 |
"""Test ignoring case with find.""" |
| 71 |
trie = Trie() |
| 72 |
trie.insert("tEsT", 1) |
| 73 |
|
| 74 |
assert list(trie.find("this is a tEsT")) == [(14, "tEsT", 1)] |
| 75 |
|
| 76 |
# Not ignoring case |
| 77 |
for word in ("test", "TEST", "TeSt"): |
| 78 |
assert not list(trie.find(f"this is a {word}")), word |
| 79 |
|
| 80 |
# Ignoring case |
| 81 |
for word in ("test", "TEST", "TeSt", "tEsT"): |
| 82 |
assert list(trie.find(f"this is a {word}", ignore_case=True)) == [ |
| 83 |
(14, "tEsT", 1) |
| 84 |
], word |