-
Notifications
You must be signed in to change notification settings - Fork 22
/
test_hashtable.py
105 lines (91 loc) · 2.92 KB
/
test_hashtable.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#!python
from hashtable import HashTable
import unittest
class HashTableTest(unittest.TestCase):
def test_init(self):
ht = HashTable(4)
assert len(ht.buckets) == 4
assert ht.length() == 0
def test_length(self):
ht = HashTable()
assert ht.length() == 0
ht.set('I', 1)
assert ht.length() == 1
ht.set('V', 5)
assert ht.length() == 2
ht.set('X', 10)
assert ht.length() == 3
def test_contains(self):
ht = HashTable()
ht.set('I', 1)
ht.set('V', 5)
ht.set('X', 10)
assert ht.contains('I') is True
assert ht.contains('V') is True
assert ht.contains('X') is True
assert ht.contains('A') is False
def test_set_and_get(self):
ht = HashTable()
ht.set('I', 1)
ht.set('V', 5)
ht.set('X', 10)
assert ht.get('I') == 1
assert ht.get('V') == 5
assert ht.get('X') == 10
assert ht.length() == 3
with self.assertRaises(KeyError):
ht.get('A') # Key does not exist
def test_set_twice_and_get(self):
ht = HashTable()
ht.set('I', 1)
ht.set('V', 4)
ht.set('X', 9)
assert ht.length() == 3
ht.set('V', 5) # Update value
ht.set('X', 10) # Update value
assert ht.get('I') == 1
assert ht.get('V') == 5
assert ht.get('X') == 10
assert ht.length() == 3 # Check length is not overcounting
def test_delete(self):
ht = HashTable()
ht.set('I', 1)
ht.set('V', 5)
ht.set('X', 10)
assert ht.length() == 3
ht.delete('I')
ht.delete('X')
assert ht.length() == 1
with self.assertRaises(KeyError):
ht.delete('X') # Key no longer exists
with self.assertRaises(KeyError):
ht.delete('A') # Key does not exist
def test_keys(self):
ht = HashTable()
assert ht.keys() == []
ht.set('I', 1)
assert ht.keys() == ['I']
ht.set('V', 5)
self.assertItemsEqual(ht.keys(), ['I', 'V']) # Ignore item order
ht.set('X', 10)
self.assertItemsEqual(ht.keys(), ['I', 'V', 'X']) # Ignore item order
def test_values(self):
ht = HashTable()
assert ht.values() == []
ht.set('I', 1)
assert ht.values() == [1]
ht.set('V', 5)
self.assertItemsEqual(ht.values(), [1, 5]) # Ignore item order
ht.set('X', 10)
self.assertItemsEqual(ht.values(), [1, 5, 10]) # Ignore item order
def test_items(self):
ht = HashTable()
assert ht.items() == []
ht.set('I', 1)
assert ht.items() == [('I', 1)]
ht.set('V', 5)
self.assertItemsEqual(ht.items(), [('I', 1), ('V', 5)])
ht.set('X', 10)
self.assertItemsEqual(ht.items(), [('I', 1), ('V', 5), ('X', 10)])
if __name__ == '__main__':
unittest.main()