test script for the dbm open function based on testdumbdbm py import unittest import dbm import os from test support import importhelper from test support import oshelper try from dbm import ndbm except importerror ndbm none dirname oshelper testfn fname os path joindirname oshelper testfn iterates over every database module supported by dbm currently available def dbmiterator for name in dbm names try mod importname fromlist open except importerror continue dbm modulesname mod yield mod clean up all scratch databases we might have created during testing def cleaunuptestdir oshelper rmtreedirname def setuptestdir cleaunuptestdir os mkdirdirname class anydbmtestcase dict a b python b b programming c b the d b way f b guido g b intended def initdbself f dbm openfname n for k in self dict fk encodeascii self dictk f close def keyshelperself f keys sortedk decodeascii for k in f keys dkeys sortedself dict keys self assertequalkeys dkeys return keys def testerrorself self asserttrueissubclassself module error oserror def testanydbmnotexistingself self assertraisesdbm error dbm open fname def testanydbmcreationself f dbm openfname c self assertequallistf keys for key in self dict fkey encodeascii self dictkey self readhelperf f close def testanydbmcreationnfileexistswithinvalidcontentsself create an empty file oshelper createemptyfilefname with dbm openfname n as f self assertequallenf 0 def testanydbmmodificationself self initdb f dbm openfname c self dict g fb g bindented self readhelperf setdefault works as in the dict interface self assertequalf setdefaultb xxx b foo b foo self assertequalfb xxx b foo f close def testanydbmreadself self initdb f dbm openfname r self readhelperf get works as in the dict interface self assertequalf getb a self dict a self assertequalf getb xxx b foo b foo self assertisnonef getb xxx with self assertraiseskeyerror fb xxx f close def testanydbmkeysself self initdb f dbm openfname r keys self keyshelperf f close def testemptyvalueself if getattrdbm defaultmod library none berkeley db self skiptestberkeley db doesn t distinguish the empty value from the absent one f dbm openfname c self assertequalf keys fb empty b self assertequalf keys b empty self assertinb empty f self assertequalfb empty b self assertequalf getb empty b self assertequalf setdefaultb empty b f close def testanydbmaccessself self initdb f dbm openfname r key a encodeascii self assertinkey f assertfkey bpython f close def testopenwithbytesself dbm openos fsencodefname c close def testopenwithpathlibpathself dbm openoshelper fakepathfname c close def testopenwithpathlibpathbytesself dbm openoshelper fakepathos fsencodefname c close def readhelperself f keys self keyshelperf for key in self dict self assertequalself dictkey fkey encodeascii def testkeysself with dbm openfname c as d self assertequald keys a b a b b b 12345678910 b 019237410982340912840198242 for k v in a dk v self assertequalsortedd keys sortedk for k v in a for k v in a self assertink d self assertequaldk v self assertnotinb xxx d self assertraiseskeyerror lambda db xxx def testclearself with dbm openfname c as d self assertequald keys a b a b b b 12345678910 b 019237410982340912840198242 for k v in a dk v for k in a self assertink d self assertequallend lena d clear self assertequallend 0 for k in a self assertnotink d def setupself self addcleanupsetattr dbm defaultmod dbm defaultmod dbm defaultmod self module self addcleanupcleaunuptestdir setuptestdir class whichdbtestcaseunittest testcase def testwhichdbself self addcleanupsetattr dbm defaultmod dbm defaultmod bytesfname os fsencodefname fnames fname oshelper fakepathfname bytesfname oshelper fakepathbytesfname for module in dbmiterator check whether whichdb correctly guesses module name for databases opened with module module name module name setuptestdir dbm defaultmod module try with empty files first with module openfname c pass for path in fnames self assertequalname self dbm whichdbpath now add a key with module openfname w as f fb1 b1 and test that we can find it self assertinb1 f and read it self assertequalfb1 b1 for path in fnames self assertequalname self dbm whichdbpath unittest skipunlessndbm reason test requires ndbm def testwhichdbndbmself issue 17198 check that ndbm which is referenced in whichdb is defined with openfname db wb pass bytesfname os fsencodefname fnames fname oshelper fakepathfname bytesfname oshelper fakepathbytesfname for path in fnames self assertisnoneself dbm whichdbpath def setupself self addcleanupcleaunuptestdir setuptestdir self dbm importhelper importfreshmodule dbm for mod in dbmiterator assert mod name startswith dbm suffix mod name4 testname f testcasesuffix globalstestname typetestname anydbmtestcase unittest testcase module mod if name main unittest main iterates over every database module supported by dbm currently available clean up all scratch databases we might have created during testing create an empty file setdefault works as in the dict interface get works as in the dict interface check whether whichdb correctly guesses module name for databases opened with module module try with empty files first now add a key and test that we can find it and read it issue 17198 check that ndbm which is referenced in whichdb is defined
import unittest
import dbm
import os
from test.support import import_helper
from test.support import os_helper

try:
    from dbm import ndbm
except ImportError:
    ndbm = None

dirname = os_helper.TESTFN
_fname = os.path.join(dirname, os_helper.TESTFN)




def dbm_iterator():
    for name in dbm._names:
        try:
            mod = __import__(name, fromlist=['open'])
        except ImportError:
            continue
        dbm._modules[name] = mod
        yield mod




def cleaunup_test_dir():
    os_helper.rmtree(dirname)

def setup_test_dir():
    cleaunup_test_dir()
    os.mkdir(dirname)


class AnyDBMTestCase:
    _dict = {'a': b'Python:',
             'b': b'Programming',
             'c': b'the',
             'd': b'way',
             'f': b'Guido',
             'g': b'intended',
             }

    def init_db(self):
        f = dbm.open(_fname, 'n')
        for k in self._dict:
            f[k.encode("ascii")] = self._dict[k]
        f.close()

    def keys_helper(self, f):
        keys = sorted(k.decode("ascii") for k in f.keys())
        dkeys = sorted(self._dict.keys())
        self.assertEqual(keys, dkeys)
        return keys

    def test_error(self):
        self.assertTrue(issubclass(self.module.error, OSError))

    def test_anydbm_not_existing(self):
        self.assertRaises(dbm.error, dbm.open, _fname)

    def test_anydbm_creation(self):
        f = dbm.open(_fname, 'c')
        self.assertEqual(list(f.keys()), [])
        for key in self._dict:
            f[key.encode("ascii")] = self._dict[key]
        self.read_helper(f)
        f.close()

    def test_anydbm_creation_n_file_exists_with_invalid_contents(self):
        
        os_helper.create_empty_file(_fname)
        with dbm.open(_fname, 'n') as f:
            self.assertEqual(len(f), 0)

    def test_anydbm_modification(self):
        self.init_db()
        f = dbm.open(_fname, 'c')
        self._dict['g'] = f[b'g'] = b"indented"
        self.read_helper(f)
        
        self.assertEqual(f.setdefault(b'xxx', b'foo'), b'foo')
        self.assertEqual(f[b'xxx'], b'foo')
        f.close()

    def test_anydbm_read(self):
        self.init_db()
        f = dbm.open(_fname, 'r')
        self.read_helper(f)
        
        self.assertEqual(f.get(b'a'), self._dict['a'])
        self.assertEqual(f.get(b'xxx', b'foo'), b'foo')
        self.assertIsNone(f.get(b'xxx'))
        with self.assertRaises(KeyError):
            f[b'xxx']
        f.close()

    def test_anydbm_keys(self):
        self.init_db()
        f = dbm.open(_fname, 'r')
        keys = self.keys_helper(f)
        f.close()

    def test_empty_value(self):
        if getattr(dbm._defaultmod, 'library', None) == 'Berkeley DB':
            self.skipTest("Berkeley DB doesn't distinguish the empty value "
                          "from the absent one")
        f = dbm.open(_fname, 'c')
        self.assertEqual(f.keys(), [])
        f[b'empty'] = b''
        self.assertEqual(f.keys(), [b'empty'])
        self.assertIn(b'empty', f)
        self.assertEqual(f[b'empty'], b'')
        self.assertEqual(f.get(b'empty'), b'')
        self.assertEqual(f.setdefault(b'empty'), b'')
        f.close()

    def test_anydbm_access(self):
        self.init_db()
        f = dbm.open(_fname, 'r')
        key = "a".encode("ascii")
        self.assertIn(key, f)
        assert(f[key] == b"Python:")
        f.close()

    def test_open_with_bytes(self):
        dbm.open(os.fsencode(_fname), "c").close()

    def test_open_with_pathlib_path(self):
        dbm.open(os_helper.FakePath(_fname), "c").close()

    def test_open_with_pathlib_path_bytes(self):
        dbm.open(os_helper.FakePath(os.fsencode(_fname)), "c").close()

    def read_helper(self, f):
        keys = self.keys_helper(f)
        for key in self._dict:
            self.assertEqual(self._dict[key], f[key.encode("ascii")])

    def test_keys(self):
        with dbm.open(_fname, 'c') as d:
            self.assertEqual(d.keys(), [])
            a = [(b'a', b'b'), (b'12345678910', b'019237410982340912840198242')]
            for k, v in a:
                d[k] = v
            self.assertEqual(sorted(d.keys()), sorted(k for (k, v) in a))
            for k, v in a:
                self.assertIn(k, d)
                self.assertEqual(d[k], v)
            self.assertNotIn(b'xxx', d)
            self.assertRaises(KeyError, lambda: d[b'xxx'])

    def test_clear(self):
        with dbm.open(_fname, 'c') as d:
            self.assertEqual(d.keys(), [])
            a = [(b'a', b'b'), (b'12345678910', b'019237410982340912840198242')]
            for k, v in a:
                d[k] = v
            for k, _ in a:
                self.assertIn(k, d)
            self.assertEqual(len(d), len(a))

            d.clear()
            self.assertEqual(len(d), 0)
            for k, _ in a:
                self.assertNotIn(k, d)

    def setUp(self):
        self.addCleanup(setattr, dbm, '_defaultmod', dbm._defaultmod)
        dbm._defaultmod = self.module
        self.addCleanup(cleaunup_test_dir)
        setup_test_dir()


class WhichDBTestCase(unittest.TestCase):
    def test_whichdb(self):
        self.addCleanup(setattr, dbm, '_defaultmod', dbm._defaultmod)
        _bytes_fname = os.fsencode(_fname)
        fnames = [_fname, os_helper.FakePath(_fname),
                  _bytes_fname, os_helper.FakePath(_bytes_fname)]
        for module in dbm_iterator():
            
            
            name = module.__name__
            setup_test_dir()
            dbm._defaultmod = module
            
            with module.open(_fname, 'c'): pass
            for path in fnames:
                self.assertEqual(name, self.dbm.whichdb(path))
            
            with module.open(_fname, 'w') as f:
                f[b"1"] = b"1"
                
                self.assertIn(b"1", f)
                
                self.assertEqual(f[b"1"], b"1")
            for path in fnames:
                self.assertEqual(name, self.dbm.whichdb(path))

    @unittest.skipUnless(ndbm, reason='Test requires ndbm')
    def test_whichdb_ndbm(self):
        
        with open(_fname + '.db', 'wb'): pass
        _bytes_fname = os.fsencode(_fname)
        fnames = [_fname, os_helper.FakePath(_fname),
                  _bytes_fname, os_helper.FakePath(_bytes_fname)]
        for path in fnames:
            self.assertIsNone(self.dbm.whichdb(path))

    def setUp(self):
        self.addCleanup(cleaunup_test_dir)
        setup_test_dir()
        self.dbm = import_helper.import_fresh_module('dbm')


for mod in dbm_iterator():
    assert mod.__name__.startswith('dbm.')
    suffix = mod.__name__[4:]
    testname = f'TestCase_{suffix}'
    globals()[testname] = type(testname,
                               (AnyDBMTestCase, unittest.TestCase),
                               {'module': mod})


if __name__ == "__main__":
    unittest.main()