def test_transaction(): with dbkit.connect(sqlite3, ':memory:'): dbkit.execute(SCHEMA) # First, make sure the normal case behaves correctly. assert dbkit.context()._depth == 0 with dbkit.transaction(): assert dbkit.context()._depth == 1 dbkit.execute(TEST_DATA) assert dbkit.context()._depth == 0 assert dbkit.query_value(GET_COUNTER, ('foo',)) == 42 assert dbkit.query_value(GET_COUNTER, ('bar',)) is None # Now, ensure transactions are rolled back in case of exceptions. exception_caught = False try: with dbkit.transaction(): dbkit.execute(UPDATE_COUNTER, (13, 'foo')) raise dbkit.AbortTransaction() assert False, "Should've raised an exception." except dbkit.AbortTransaction: exception_caught = True assert exception_caught value = dbkit.query_value(GET_COUNTER, ('foo',)) assert value == 42
def test_context(self): self.assertTrue(dbkit.Context.current(with_exception=False) is None) ctx = dbkit.connect(sqlite3, ':memory:') with ctx: # Check nesting. self.assertEqual(len(ctx.stack), 1) with ctx: self.assertEqual(len(ctx.stack), 2) self.assertEqual(len(ctx.stack), 1) self.assertTrue(dbkit.Context.current(with_exception=False) is ctx) self.assertTrue(ctx.mdr is not None) self.assertTrue(ctx.logger is not None) ctx.close() try: dbkit.context() self.fail("Should not have been able to access context.") except: pass self.assertTrue(ctx.mdr is None) self.assertTrue(ctx.logger is None) self.assertEqual(len(ctx.stack), 0)
def test_context(): assert dbkit.Context.current(with_exception=False) is None ctx = dbkit.connect(sqlite3, ':memory:') with ctx: # Check nesting. assert len(ctx.state.stack) == 1 with ctx: assert len(ctx.state.stack) == 2 assert len(ctx.state.stack) == 1 assert dbkit.Context.current(with_exception=False) is ctx assert ctx._mdr is not None assert ctx.logger is not None ctx.close() try: dbkit.context() assert False, "Should not have been able to access context." except: pass assert ctx._mdr is None assert ctx.logger is None assert len(ctx.state.stack) == 0
def test_transaction(self): with dbkit.connect(sqlite3, ':memory:'): dbkit.execute(SCHEMA) # First, make sure the normal case behaves correctly. self.assertEqual(dbkit.context()._depth, 0) with dbkit.transaction(): self.assertEqual(dbkit.context()._depth, 1) dbkit.execute(TEST_DATA) self.assertEqual(dbkit.context()._depth, 0) self.assertEqual(dbkit.query_value(GET_COUNTER, ('foo',)), 42) self.assertTrue(dbkit.query_value(GET_COUNTER, ('bar',)) is None) # Now, ensure transactions are rolled back in case of exceptions. exception_caught = False try: with dbkit.transaction(): dbkit.execute(UPDATE_COUNTER, (13, 'foo')) raise dbkit.AbortTransaction() self.fail("Should've raised an exception.") except dbkit.AbortTransaction: exception_caught = True self.assertTrue(exception_caught) self.assertEqual(dbkit.query_value(GET_COUNTER, ('foo',)), 42)