#!/usr/bin/python # # A script to add a new test function to a CppUnit test class # Copyright David Dibben 2010 # import re import string import sys import getopt import os.path version="0.1 " def addFunc(s, testname): added = 1 tmatch = re.search(r'CPPUNIT_TEST_SUITE(.*)_TEST[(]\s*(.*?)\s*[)];(.*?)CPPUNIT_TEST_SUITE_END', s, re.DOTALL) if tmatch: if re.search(testname, tmatch.group(0)): print "Test \"" + testname + "\" already exist" return [s, 0] lasttest = tmatch.group(2) insertpos = tmatch.end(3) s = s[:insertpos] + "CPPUNIT_TEST( " + testname + ");" + tmatch.group(3) + s[insertpos:] tmatch = re.search(r'([ \t]*)void(\s*)' + lasttest +r'[(][)];',s) if tmatch: insertpos = tmatch.end(0) newfunc = tmatch.group(1) + "void" + tmatch.group(2) + testname + "();" s = s[:insertpos] + "\n" + newfunc + s[insertpos:] else: print "nomatch" added = 0 return [s, added]; def addImpl(s, classname, testname): s += "\n" s += "void "+ classname + "::" + testname + "()\n" s += "{\n" s += "\t\n" s += "}\n\n" return s # # print the usage message # def usage(): print version print "usage: addfile testcase function [function...]" print "A simple a program to test functions to a test case class" #the main function def main(argv): # the name of the .pro or .pri file profile="" global _debug _debug = 0 try: opts, args = getopt.getopt(argv, "hd", ["help"]) except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ("-h", "--help"): usage() sys.exit() elif opt == '-d': _debug = 1 if len( args ) == 0: print "Error: No files test case class specified" usage() sys.exit(2) if len( args ) == 1: print "Error: No files test function specified" usage() sys.exit(2) testcase = args[0] filepath, filename = os.path.split(args[0]) classname = os.path.splitext(os.path.basename(filename))[0] headerfile = os.path.join(filepath, classname) + ".h" sourcefile = os.path.join(filepath, classname) + ".cpp" if _debug: print "headerfile = " + headerfile if _debug: print "sourcefile = " + sourcefile args = args[1:] if _debug: print "Class = " + classname try: header = open(headerfile).read() source = open(sourcefile).read() for test in args: print "Adding " + test header, added = addFunc(header, test) if added: source = addImpl(source, classname, test) except IOError: print "Cannot open file" sys.exit(2) open(headerfile, 'w').write(header) open(sourcefile, 'w').write(source) if __name__ == "__main__": main(sys.argv[1:])