[DB-SIG] fakedb - a stub database for unit testing

Anthony Baxter anthony at interlink.com.au
Sun Oct 19 23:14:31 EDT 2003

Here's a little toy I've whipped up for a project at work - it
pretends to be a database connection, but records the (parsed)
SQL that was fed to it. It also uses the parsed SQL to produce 
a valid cursor.description after a select - note, though, that
it never returns any rows. It needs gadfly for the SQL parsing -
this seemed to be the only available SQL parser for python, and
writing my own was way too much work. 

Anyway, here 'tis, feel free to do with it what you will. Any
suggestions for improvements are more than welcome.


#------------------start fakedb.py--------------------

class FakeDBCursor(object):
    "Fake up enough stuff to get away with it ;)"

    def __init__(self):
        self.SQLs = []

    def execute(self, sql):
        from sqlparse import SQLParse
        dqltype, res = SQLParse(sql)
        if dqltype != 'Selector':
            self.description  = ()
            self.description  = []
            columns = res[1]
            for name, boundattr in columns.order:
                if name is not None:
                    self.description.append((name, 0,0,0,0,0,0))
                    self.description.append((boundattr.name, 0,0,0,0,0,0))
            self.description = tuple(self.description)
        self.SQLs.append((sql, (dqltype,res)))
        return None

    def fetchone(self): 
        return None

    def fetchmany(self): 
        return []

    def fetchall(self): 
        return []

class FakeDBConnection(FakeDBCursor):

    def cursor(self):
        return FakeDBCursor()

    def commit(self): 
        return None

    def rollback(self): 
        return None

def Connect(*args, **kwargs):
    return FakeDBConnection()

    import gadfly
except ImportError:
    gadfly = None

def SQLParse(sqltext):
    if gadfly is None:
        return None, None
    from gadfly import sql, bindings
    sql = sql.getSQL()
    bind = bindings.BindRules(sql)
    from gadfly.semantics import Parse_Context
    context = Parse_Context()
    cs = sql.DoParse1(sqltext, context)
    return cs[0].__class__.__name__, cs[0].initargs()

#--------------------end fakedb.py--------------------

More information about the DB-SIG mailing list