def test_make_placeholders_format(self): for style in ('format', 'pyformat'): with utils.set_temporarily(fakedb, 'paramstyle', style): with dbkit.connect(fakedb, 'db'): self.assert_placeholders(1, '%s') self.assert_placeholders(2, '%s, %s') self.assert_placeholders(3, '%s, %s, %s')
def setup(): """Creates a context fit for testing.""" with dbkit.connect(sqlite3, ':memory:') as ctx: dbkit.execute(SCHEMA) with dbkit.transaction(): dbkit.execute(TEST_DATA) return ctx
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_make_placeholders_empty(self): with dbkit.connect(fakedb, 'db'): try: dbkit.make_placeholders([]) self.fail("Expected ValueError") except ValueError: pass
def test_make_placeholders_unsupported_named(self): with utils.set_temporarily(fakedb, 'paramstyle', 'named'): with dbkit.connect(fakedb, 'db'): try: dbkit.make_placeholders(['foo']) self.fail("Should've got 'NotSupported' exception.") except dbkit.NotSupported as exc: self.assertEqual(str(exc), "Param style 'named' does not support sequence type 'list'")
def setUp(self): """Creates a context fit for testing.""" self.ctx = dbkit.connect(sqlite3, ':memory:') with self.ctx: dbkit.execute(SCHEMA) with dbkit.transaction(): dbkit.execute(TEST_DATA) self.assertEqual(self.ctx.last_row_count, 1)
def test_logging(self): with dbkit.connect(sqlite3, ':memory:') as ctx: captured = six.StringIO() ctx.logger = dbkit.make_file_object_logger(captured) dbkit.query_column(LIST_TABLES) value = utils.skip_first_line(captured.getvalue()) captured.close() self.assertEqual(value, "%s\nArguments:\n()\n" % (LIST_TABLES,))
def test_create_table(): with dbkit.connect(sqlite3, ':memory:'): result = dbkit.query_column(LIST_TABLES) assert isinstance(result, types.GeneratorType) assert len(list(result)) == 0 dbkit.execute(SCHEMA) result = dbkit.query_column(LIST_TABLES) assert isinstance(result, types.GeneratorType) assert list(result) == [u'counters']
def test_create_table(): with dbkit.connect(sqlite3, ':memory:'): result = dbkit.query_column(LIST_TABLES) assert hasattr(result, '__iter__') assert len(list(result)) == 0 dbkit.execute(SCHEMA) result = dbkit.query_column(LIST_TABLES) assert hasattr(result, '__iter__') assert list(result) == [u'counters']
def test_create_table(self): with dbkit.connect(sqlite3, ':memory:'): result = dbkit.query_column(LIST_TABLES) self.assertTrue(hasattr(result, '__iter__')) self.assertEqual(len(list(result)), 0) dbkit.execute(SCHEMA) result = dbkit.query_column(LIST_TABLES) self.assertTrue(hasattr(result, '__iter__')) self.assertEqual(list(result), [u'counters'])
def test_bad_connect(self): try: with dbkit.connect(sqlite3, '/nonexistent.db') as ctx: # Wouldn't do this in real code as the mediator is private. with ctx.mdr: pass self.fail("Should not have been able to open database.") except sqlite3.OperationalError: pass
def test_procs(): with dbkit.connect(fakedb, 'db') as ctx: dbkit.execute_proc('execute_proc') dbkit.query_proc_row('query_proc_row') dbkit.query_proc_value('query_proc_value') list(dbkit.query_proc_column('query_proc_column')) conn = ctx.mdr.conn assert conn.executed == 4 assert conn.session == [ 'cursor', 'proc:execute_proc', 'cursor-close', 'cursor', 'proc:query_proc_row', 'cursor-close', 'cursor', 'proc:query_proc_value', 'cursor-close', 'cursor', 'proc:query_proc_column', 'cursor-close']
def test_make_placeholders(): with dbkit.connect(fakedb, 'db') as ctx: try: dbkit.make_placeholders([]) assert False, "Expected ValueError" except ValueError: pass with utils.set_temporarily(fakedb, 'paramstyle', 'qmark'): with dbkit.connect(fakedb, 'db') as ctx: assert dbkit.make_placeholders([0]) == '?' assert dbkit.make_placeholders([0, 1]) == '?, ?' assert dbkit.make_placeholders([0, 1, 4]) == '?, ?, ?' for style in ('format', 'pyformat'): with utils.set_temporarily(fakedb, 'paramstyle', style): with dbkit.connect(fakedb, 'db') as ctx: assert dbkit.make_placeholders([0]) == '%s' assert dbkit.make_placeholders([0, 2]) == '%s, %s' assert dbkit.make_placeholders([0, 2, 7]) == '%s, %s, %s' with utils.set_temporarily(fakedb, 'paramstyle', 'numeric'): with dbkit.connect(fakedb, 'db') as ctx: assert dbkit.make_placeholders([0], 7) == ':7' assert dbkit.make_placeholders([0, 1], 7) == ':7, :8' assert dbkit.make_placeholders([0, 1, 4], 7) == ':7, :8, :9' def sort_fields(fields): """Helper to ensure named fields are sorted for the test.""" return ', '.join(sorted(field.lstrip() for field in fields.split(','))) def make_sorted(seq): """Wrap repetitive code for the next few checks.""" return sort_fields(dbkit.make_placeholders(seq)) with utils.set_temporarily(fakedb, 'paramstyle', 'pyformat'): with dbkit.connect(fakedb, 'db') as ctx: assert make_sorted({'foo': None}) == '%(foo)s' assert make_sorted({'foo': None, 'bar': None}) == '%(bar)s, %(foo)s' assert make_sorted({'foo': None, 'bar': None, 'baz': None}) == '%(bar)s, %(baz)s, %(foo)s' with utils.set_temporarily(fakedb, 'paramstyle', 'named'): with dbkit.connect(fakedb, 'db') as ctx: assert make_sorted({'foo': None}) == ':foo' assert make_sorted({'foo': None, 'bar': None}) == ':bar, :foo' assert make_sorted({'foo': None, 'bar': None, 'baz': None}) == ':bar, :baz, :foo' with utils.set_temporarily(fakedb, 'paramstyle', 'qmark'): with dbkit.connect(fakedb, 'db') as ctx: try: print dbkit.make_placeholders({'foo': None}) assert False, "Should've got 'NotSupported' exception." except dbkit.NotSupported, exc: assert str(exc) == "Param style 'qmark' does not support sequence type 'dict'"
def main(): # This table tells us the subcommands, the functions to dispatch to, # and their signatures. command_table = { 'set': (set_counter, str, int), 'del': (delete_counter, str), 'get': (get_counter, str), 'list': (list_counters,), 'incr': (increment_counter, str, int), 'dump': (print_counters_and_values,), } with connect(sqlite3, 'counters.sqlite') as ctx: with closing(ctx): dispatch(command_table, sys.argv)
def test_procs(self): def expected(*args): result = [] for arg in args: result += ['cursor', arg, 'commit', 'cursor-close'] return result with dbkit.connect(fakedb, 'db') as ctx: dbkit.execute_proc('execute_proc') dbkit.query_proc_row('query_proc_row') dbkit.query_proc_value('query_proc_value') list(dbkit.query_proc_column('query_proc_column')) conn = ctx.mdr.conn self.assertEqual(conn.executed, 4) self.assertEqual(conn.session, expected('proc:execute_proc', 'proc:query_proc_row', 'proc:query_proc_value', 'proc:query_proc_column'))
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)
def test_good_connect(self): with contextlib.closing(dbkit.connect(sqlite3, ':memory:')) as ctx: self.assertTrue(isinstance(ctx, dbkit.Context))
def test_good_connect(): ctx = dbkit.connect(sqlite3, ':memory:') assert isinstance(ctx, dbkit.Context) ctx.close()
def test_make_placeholders_named(self): with utils.set_temporarily(fakedb, 'paramstyle', 'named'): with dbkit.connect(fakedb, 'db'): self.assert_named(['foo'], ':%s') self.assert_named(['foo', 'bar'], ':%s') self.assert_named(['foo', 'bar', 'baz'], ':%s')
def test_make_placeholders_format_dict(self): with utils.set_temporarily(fakedb, 'paramstyle', 'pyformat'): with dbkit.connect(fakedb, 'db'): self.assert_named(['foo'], '%%(%s)s') self.assert_named(['foo', 'bar'], '%%(%s)s') self.assert_named(['foo', 'bar', 'baz'], '%%(%s)s')
def test_make_placeholders_numeric(self): with utils.set_temporarily(fakedb, 'paramstyle', 'numeric'): with dbkit.connect(fakedb, 'db'): self.assert_placeholders(1, ':7', start=7) self.assert_placeholders(2, ':7, :8', start=7) self.assert_placeholders(3, ':7, :8, :9', start=7)
def test_make_placeholders_qmark(self): with utils.set_temporarily(fakedb, 'paramstyle', 'qmark'): with dbkit.connect(fakedb, 'db'): self.assert_placeholders(1, '?') self.assert_placeholders(2, '?, ?') self.assert_placeholders(3, '?, ?, ?')
with utils.set_temporarily(fakedb, 'paramstyle', 'pyformat'): with dbkit.connect(fakedb, 'db') as ctx: assert make_sorted({'foo': None}) == '%(foo)s' assert make_sorted({'foo': None, 'bar': None}) == '%(bar)s, %(foo)s' assert make_sorted({'foo': None, 'bar': None, 'baz': None}) == '%(bar)s, %(baz)s, %(foo)s' with utils.set_temporarily(fakedb, 'paramstyle', 'named'): with dbkit.connect(fakedb, 'db') as ctx: assert make_sorted({'foo': None}) == ':foo' assert make_sorted({'foo': None, 'bar': None}) == ':bar, :foo' assert make_sorted({'foo': None, 'bar': None, 'baz': None}) == ':bar, :baz, :foo' with utils.set_temporarily(fakedb, 'paramstyle', 'qmark'): with dbkit.connect(fakedb, 'db') as ctx: try: print dbkit.make_placeholders({'foo': None}) assert False, "Should've got 'NotSupported' exception." except dbkit.NotSupported, exc: assert str(exc) == "Param style 'qmark' does not support sequence type 'dict'" with utils.set_temporarily(fakedb, 'paramstyle', 'named'): with dbkit.connect(fakedb, 'db') as ctx: try: print dbkit.make_placeholders(['foo']) assert False, "Should've got 'NotSupported' exception." except dbkit.NotSupported, exc: assert str(exc) == "Param style 'named' does not support sequence type 'list'" # vim:set et ai: