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