def test_hash_table(): ht = HashTable() print('hash table: {}'.format(ht)) print('\nTesting set:') for key, value in [('I', 1), ('V', 5), ('X', 10)]: print('set({!r}, {!r})'.format(key, value)) ht.set(key, value) print('hash table: {}'.format(ht)) print('\nTesting get:') for key in ['I', 'V', 'X']: value = ht.get(key) print('get({!r}): {!r}'.format(key, value)) print('contains({!r}): {}'.format('X', ht.contains('X'))) print('length: {}'.format(ht.length())) # Enable this after implementing delete method delete_implemented = False if delete_implemented: print('\nTesting delete:') for key in ['I', 'V', 'X']: print('delete({!r})'.format(key)) ht.delete(key) print('hash table: {}'.format(ht)) print('contains(X): {}'.format(ht.contains('X'))) print('length: {}'.format(ht.length()))
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_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_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_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_items(self): ht = HashTable() assert ht.items() == [] ht.set('I', 1) assert ht.items() == [('I', 1)] ht.set('V', 5) self.assertCountEqual(ht.items(), [('I', 1), ('V', 5)]) ht.set('X', 10) self.assertCountEqual(ht.items(), [('I', 1), ('V', 5), ('X', 10)])
def test_values(self): ht = HashTable() assert ht.values() == [] ht.set('I', 1) assert ht.values() == [1] ht.set('V', 5) self.assertCountEqual(ht.values(), [1, 5]) # Ignore item order ht.set('X', 10) self.assertCountEqual(ht.values(), [1, 5, 10]) # Ignore item order
def test_keys(self): ht = HashTable() assert ht.keys() == [] ht.set('I', 1) assert ht.keys() == ['I'] ht.set('V', 5) self.assertCountEqual(ht.keys(), ['I', 'V']) # Ignore item order ht.set('X', 10) self.assertCountEqual(ht.keys(), ['I', 'V', 'X']) # Ignore item order