1 #! /usr/bin/env python 2 """Test script for the anydbm module 3 based on testdumbdbm.py 4 """ 5 6 import os 7 import unittest 8 import glob 9 from test import test_support 10 11 _fname = test_support.TESTFN 12 13 # Silence Py3k warning 14 anydbm = test_support.import_module('anydbm', deprecated=True) 15 16 def _delete_files(): 17 # we don't know the precise name the underlying database uses 18 # so we use glob to locate all names 19 for f in glob.glob(_fname + "*"): 20 try: 21 os.unlink(f) 22 except OSError: 23 pass 24 25 class AnyDBMTestCase(unittest.TestCase): 26 _dict = {'0': '', 27 'a': 'Python:', 28 'b': 'Programming', 29 'c': 'the', 30 'd': 'way', 31 'f': 'Guido', 32 'g': 'intended' 33 } 34 35 def __init__(self, *args): 36 unittest.TestCase.__init__(self, *args) 37 38 def test_anydbm_creation(self): 39 f = anydbm.open(_fname, 'c') 40 self.assertEqual(f.keys(), []) 41 for key in self._dict: 42 f[key] = self._dict[key] 43 self.read_helper(f) 44 f.close() 45 46 def test_anydbm_modification(self): 47 self.init_db() 48 f = anydbm.open(_fname, 'c') 49 self._dict['g'] = f['g'] = "indented" 50 self.read_helper(f) 51 f.close() 52 53 def test_anydbm_read(self): 54 self.init_db() 55 f = anydbm.open(_fname, 'r') 56 self.read_helper(f) 57 f.close() 58 59 def test_anydbm_keys(self): 60 self.init_db() 61 f = anydbm.open(_fname, 'r') 62 keys = self.keys_helper(f) 63 f.close() 64 65 def read_helper(self, f): 66 keys = self.keys_helper(f) 67 for key in self._dict: 68 self.assertEqual(self._dict[key], f[key]) 69 70 def init_db(self): 71 f = anydbm.open(_fname, 'n') 72 for k in self._dict: 73 f[k] = self._dict[k] 74 f.close() 75 76 def keys_helper(self, f): 77 keys = f.keys() 78 keys.sort() 79 dkeys = self._dict.keys() 80 dkeys.sort() 81 self.assertEqual(keys, dkeys) 82 return keys 83 84 def tearDown(self): 85 _delete_files() 86 87 def setUp(self): 88 _delete_files() 89 90 def test_main(): 91 try: 92 test_support.run_unittest(AnyDBMTestCase) 93 finally: 94 _delete_files() 95 96 if __name__ == "__main__": 97 test_main() 98