def connect(dbname): try: f = open(dbname, 'r+b') # r+ won't create the file except IOError: #In case file is not found, create it fd = os.open(dbname, os.O_RDWR | os.O_CREAT) f = os.fdopen(fd, 'r+b') return DBDB(f)
def connect(dbname): try: f = open(dbname, 'r+b') except IOError: fd = os.open(dbname, os.O_RDWR | os.O_CREAT) f = os.fdopen(fd, 'r+b') return DBDB(f)
def connect(dbname): try: f = open(dbname, 'r+b') except IOError: fd = os.open(dbname, os.O_RDWR | os.O_CREAT) # O_RDWR只读打开 O_CREAT创建并打开 http://www.runoob.com/python/os-open.html f = os.fdopen(fd, 'r+b') # # http://www.runoob.com/python/os-fdopen.html return DBDB(f)
def connect(dbname): try: f = open(dbname, 'r+b') except IOError: #os.O_RDWR 以读写的方式打开;os.O_CREAT 创建并打开一个新文件 fd = os.open(dbname, os.O_RDWR | os.O_CREAT) f = os.fdopen(fd, 'r+b') #fdopen取一个现存的文件描述符 return DBDB(f)
def setup(self): self.f = tempfile.NamedTemporaryFile(delete=False) self.dbdb = DBDB(self.f)
class TestDBDB(object): def setup(self): self.f = tempfile.NamedTemporaryFile(delete=False) self.dbdb = DBDB(self.f) def test_can_close_and_assert_closed(self): self.dbdb.close() with pytest.raises(ValueError, match='Database closed.'): self.dbdb._assert_not_closed() def test_can_set_and_get(self): self.dbdb["a"] = "1" self.dbdb.commit() eq_(self.dbdb["a"], "1") def test_can_delete(self): self.dbdb["a"] = "1" self.dbdb.commit() eq_(self.dbdb["a"], "1") del self.dbdb["a"] with pytest.raises(KeyError): val = self.dbdb["a"] def test_can_set_and_contain_returns_true(self): self.dbdb["a"] = "1" self.dbdb.commit() eq_("a" in self.dbdb, True) eq_(self.dbdb["a"], "1") eq_("b" in self.dbdb, False) def test_can_get_correct_length(self): self.dbdb["a"] = "1" self.dbdb.commit() self.dbdb["b"] = "2" self.dbdb.commit() self.dbdb["c"] = "3" self.dbdb.commit() eq_(len(self.dbdb), 3)