2 Specialised psycopg2 cursor with shortcut functions useful for testing.
6 class TestingCursor(psycopg2.extras.DictCursor):
7 """ Extension to the DictCursor class that provides execution
8 short-cuts that simplify writing assertions.
11 def scalar(self, sql, params=None):
12 """ Execute a query with a single return value and return this value.
13 Raises an assertion when not exactly one row is returned.
15 self.execute(sql, params)
16 assert self.rowcount == 1
17 return self.fetchone()[0]
20 def row_set(self, sql, params=None):
21 """ Execute a query and return the result as a set of tuples.
22 Fails when the SQL command returns duplicate rows.
24 self.execute(sql, params)
26 result = set((tuple(row) for row in self))
27 assert len(result) == self.rowcount
32 def table_exists(self, table):
33 """ Check that a table with the given name exists in the database.
35 num = self.scalar("""SELECT count(*) FROM pg_tables
36 WHERE tablename = %s""", (table, ))
40 def table_rows(self, table, where=None):
41 """ Return the number of rows in the given table.
44 return self.scalar('SELECT count(*) FROM ' + table)
46 return self.scalar('SELECT count(*) FROM {} WHERE {}'.format(table, where))
49 def execute_values(self, *args, **kwargs):
50 """ Execute the execute_values() function on the cursor.
52 psycopg2.extras.execute_values(self, *args, **kwargs)