Home | History | Annotate | Download | only in test
      1 from test import support
      2 support.import_module("dbm.ndbm") #skip if not supported
      3 import unittest
      4 import dbm.ndbm
      5 from dbm.ndbm import error
      6 
      7 class DbmTestCase(unittest.TestCase):
      8 
      9     def setUp(self):
     10         self.filename = support.TESTFN
     11         self.d = dbm.ndbm.open(self.filename, 'c')
     12         self.d.close()
     13 
     14     def tearDown(self):
     15         for suffix in ['', '.pag', '.dir', '.db']:
     16             support.unlink(self.filename + suffix)
     17 
     18     def test_keys(self):
     19         self.d = dbm.ndbm.open(self.filename, 'c')
     20         self.assertTrue(self.d.keys() == [])
     21         self.d['a'] = 'b'
     22         self.d[b'bytes'] = b'data'
     23         self.d['12345678910'] = '019237410982340912840198242'
     24         self.d.keys()
     25         self.assertIn('a', self.d)
     26         self.assertIn(b'a', self.d)
     27         self.assertEqual(self.d[b'bytes'], b'data')
     28         self.d.close()
     29 
     30     def test_modes(self):
     31         for mode in ['r', 'rw', 'w', 'n']:
     32             try:
     33                 self.d = dbm.ndbm.open(self.filename, mode)
     34                 self.d.close()
     35             except error:
     36                 self.fail()
     37 
     38     def test_context_manager(self):
     39         with dbm.ndbm.open(self.filename, 'c') as db:
     40             db["ndbm context manager"] = "context manager"
     41 
     42         with dbm.ndbm.open(self.filename, 'r') as db:
     43             self.assertEqual(list(db.keys()), [b"ndbm context manager"])
     44 
     45         with self.assertRaises(dbm.ndbm.error) as cm:
     46             db.keys()
     47         self.assertEqual(str(cm.exception),
     48                          "DBM object has already been closed")
     49 
     50 
     51 if __name__ == '__main__':
     52     unittest.main()
     53