interactive-coding-challenges/graphs_trees/trie/test_trie.py

73 lines
2.1 KiB
Python
Raw Normal View History

import unittest
2017-03-30 17:38:16 +08:00
class TestTrie(unittest.TestCase):
2017-03-30 17:38:16 +08:00
def test_trie(self):
trie = Trie()
print('Test: Insert')
words = ['a', 'at', 'has', 'hat', 'he',
'me', 'men', 'mens', 'met']
for word in words:
trie.insert(word)
for word in trie.list_words():
self.assertTrue(trie.find(word) is not None)
2017-03-30 17:38:16 +08:00
print('Test: Remove me')
trie.remove('me')
words_removed = ['me']
words = ['a', 'at', 'has', 'hat', 'he',
'men', 'mens', 'met']
for word in words:
self.assertTrue(trie.find(word) is not None)
2017-03-30 17:38:16 +08:00
for word in words_removed:
self.assertTrue(trie.find(word) is None)
2017-03-30 17:38:16 +08:00
print('Test: Remove mens')
trie.remove('mens')
words_removed = ['me', 'mens']
words = ['a', 'at', 'has', 'hat', 'he',
'men', 'met']
for word in words:
self.assertTrue(trie.find(word) is not None)
2017-03-30 17:38:16 +08:00
for word in words_removed:
self.assertTrue(trie.find(word) is None)
2017-03-30 17:38:16 +08:00
print('Test: Remove a')
trie.remove('a')
words_removed = ['a', 'me', 'mens']
words = ['at', 'has', 'hat', 'he',
'men', 'met']
for word in words:
self.assertTrue(trie.find(word) is not None)
2017-03-30 17:38:16 +08:00
for word in words_removed:
self.assertTrue(trie.find(word) is None)
2017-03-30 17:38:16 +08:00
print('Test: Remove has')
trie.remove('has')
words_removed = ['a', 'has', 'me', 'mens']
words = ['at', 'hat', 'he',
'men', 'met']
for word in words:
self.assertTrue(trie.find(word) is not None)
2017-03-30 17:38:16 +08:00
for word in words_removed:
self.assertTrue(trie.find(word) is None)
2017-03-30 17:38:16 +08:00
print('Success: test_trie')
def test_trie_remove_invalid(self):
print('Test: Remove from empty trie')
trie = Trie()
self.assertTrue(trie.remove('foo') is None)
2017-03-30 17:38:16 +08:00
def main():
test = TestTrie()
test.test_trie()
test.assertRaises(KeyError, test.test_trie_remove_invalid)
2017-03-30 17:38:16 +08:00
if __name__ == '__main__':
main()