

selenium_template= """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="" />
<title>%(title)s</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">%(title)s</td></tr>
</thead><tbody>
%(tbody)s
</tbody></table>
</body>
</html>
"""

def addArticles(reader, writer):
    """create selenium tests from csv file to add articles in the magazine

    * reader: csv.reader object where the first line define input names
    * writer: file object where to write the html

    """
    base_url = "/anticancer/www.anticancer.fr/magazine/createObject?type_name=AntiCancerDocuments_Article"
    tr_head = "<tr>\n<td>open</td>\n<td>%s</td><td></td></tr>"%base_url
    tr_submit = "<tr>\n<td>clickAndWait</td>\n<td>form_submit</td><td></td></tr>"
    keys = reader.next() #first line must content the keys to type

    testsToAdd = []
    for row in reader:
        row_str = "" + tr_head
        for i,key in enumerate(keys):
            row_str += "<tr>\n"
            row_str += "<td>type</td>"
            row_str += "<td>%s</td>"%key
            row_str += "<td>%s</td>"%row[i]
            row_str += "</tr>\n"
        row_str += tr_submit
        testsToAdd.append(row_str)
    writer.write(selenium_template%{'title':'generated',
                                    'tbody':'\n'.join(testsToAdd)})
    writer.close()

if __name__ == "__main__":
    from optparse import OptionParser
    from os import linesep
    import csv
    parser = OptionParser()
    parser.add_option("-c", "--csv", dest="csv",
          help="csv filename where to take datas")
    parser.add_option("-d", "--destination", dest="destination",
          help="destination file path where to generate selenium html file")
    parser.add_option("-o", "--operation", dest="operation",
          help="operation you want to generate [addArticles]")

    (options, args) = parser.parse_args()

    reader = csv.reader(open(options.csv,'r'))
    writer = open(options.destination, 'w')
    if options.operation == 'addArticles': addArticles(reader, writer)
