Generating seed data for PHPUnit tests

Python    2009-04-16

I'm working on a pretty massive test harness for a custom framework extension - I won't bore anyone with the details, but I'm using PHPUnit, and for our particular implementation I needed to generate large numbers of XML files to seed a test database with about 80 tables. Two things I already had were 1) a list of all the tables:

tables = ['product_links', 'product_type', 'reviews']
And 2) list of the columns in each table:
cols_product_type = ['id', 'title', 'description', 'active', 'approved', 'deprecated']
(I had these on hand from a previous project, but by all means, if you know of an alternative to SHOW COLUMNS or DESCRIBE that returns only the column names, please let me know.)
db = Database.connect("myhost", "username", "passwd", "dbname")
cursor = db.cursor()

def report(table):
    a = open(table + "_seed.xml", "w")
    cols = eval('cols_'+table)
    a.write('<?xml version="1.0" encoding="UTF-8"?>\n\r<dataset>\n\r')
    sql = """SELECT * FROM %s""" %(table)
    cursor.execute(sql)
    rows = cursor.fetchall()
    for row in rows:
        a.write('<' + table + ' ')
        loopcount = len(cols)
        for n in range(0, loopcount):
            a.write(cols[n] + '="' + str(row[n]) + '" ')
        a.write(' />\n\r')
    a.write('')

for table in tables:
    report(table)

cursor.close()
db.close()