|
| 1 | +import unittest |
| 2 | +import sys |
| 3 | +import os.path |
| 4 | + |
| 5 | +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))) |
| 6 | +import hashtable |
| 7 | + |
| 8 | + |
| 9 | +class HashFunctionTest(unittest.TestCase): |
| 10 | + |
| 11 | + def test(self): |
| 12 | + hash10 = lambda key: hashtable.hash_function(key, 10) |
| 13 | + self.assertIn(hash10("a"), range(10)) |
| 14 | + self.assertIn(hash10("b"), range(10)) |
| 15 | + self.assertIn(hash10("caleb"), range(10)) |
| 16 | + self.assertIn(hash10("more than a feeling"), range(10)) |
| 17 | + |
| 18 | + hash4 = lambda key: hashtable.hash_function(key, 4) |
| 19 | + self.assertIn(hash4("a"), range(4)) |
| 20 | + self.assertIn(hash4("b"), range(4)) |
| 21 | + self.assertIn(hash4("caleb"), range(4)) |
| 22 | + self.assertIn(hash4("more than a feeling"), range(4)) |
| 23 | + |
| 24 | + |
| 25 | +class HashTableTest(unittest.TestCase): |
| 26 | + def testCreate(self): |
| 27 | + ht = hashtable.HashTable(10) |
| 28 | + self.assertEqual(ht.capacity, 10) |
| 29 | + self.assertEqual(ht.size, 0) |
| 30 | + |
| 31 | + ht = hashtable.HashTable() |
| 32 | + self.assertEqual(ht.capacity, 1000) |
| 33 | + |
| 34 | + def testSetAndGet(self): |
| 35 | + ht = hashtable.HashTable(10) |
| 36 | + ht.set('a', 1) |
| 37 | + self.assertEqual(ht.get('a'), 1) |
| 38 | + self.assertEqual(ht.size, 1) |
| 39 | + |
| 40 | + ht.set('a', 2) |
| 41 | + self.assertEqual(ht.get('a'), 2) |
| 42 | + #self.assertEqual(ht.size, 1) |
| 43 | + |
| 44 | + ht.set('b', 10) |
| 45 | + self.assertEqual(ht.get('b'), 10) |
| 46 | + self.assertEqual(ht.get('a'), 2) |
| 47 | + #self.assertEqual(ht.size, 2) |
| 48 | + |
| 49 | + # Assert ht.set returns itself (for fluent calls) |
| 50 | + self.assertEqual(ht.set('c', 5), ht) |
| 51 | + |
| 52 | + ht.set('d', 100).set('e', 200).set('f', 300) |
| 53 | + self.assertEqual(ht.get('d'), 100) |
| 54 | + self.assertEqual(ht.get('e'), 200) |
| 55 | + self.assertEqual(ht.get('f'), 300) |
| 56 | + |
| 57 | + def testBadGet(self): |
| 58 | + ht = hashtable.HashTable(10) |
| 59 | + self.assertRaises(KeyError, ht.get, 'a') |
| 60 | + |
| 61 | + def testRemove(self): |
| 62 | + ht = hashtable.HashTable(10) |
| 63 | + self.assertRaises(KeyError, ht.remove, 'a') |
| 64 | + |
| 65 | + ht.set('a', 1) |
| 66 | + removed_item = ht.remove('a') |
| 67 | + self.assertEqual(removed_item, 1) |
| 68 | + self.assertEqual(ht.size, 0) |
| 69 | + |
| 70 | + |
| 71 | +if __name__ == '__main__': |
| 72 | + unittest.main() |
| 73 | + |
0 commit comments