Last active
August 31, 2015 22:03
-
-
Save squirrelo/72f14d3c974831e3007f to your computer and use it in GitHub Desktop.
Test skeleton creator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# with help from http://stackoverflow.com/q/17171878 | |
import ast | |
from argparse import ArgumentParser | |
from os.path import basename, splitext | |
parser = ArgumentParser(description='Creates test code skeleton for a given file') | |
parser.add_argument('-i', type=str, | |
help='File to generate test framework for') | |
parser.add_argument('-o', type=str, | |
help='File to write test framework to.') | |
parser.add_argument('-f', action='store_true', | |
help='File contains all functions (Default classes)') | |
args = parser.parse_args() | |
modname = splitext(basename(args.i))[0] | |
# Get list of classes and functions in those classes | |
parsed = None | |
with open(args.i) as fin: | |
parsed = ast.parse(fin.read()) | |
if(args.f): | |
# parse out all functions in the file and use them as base | |
classes = [modname] | |
funcs = [[node.name for node in ast.walk(parsed) | |
if isinstance(node, ast.FunctionDef)]] | |
else: | |
# parse out all classes in teh file and use them as base | |
classes = [node for node in ast.walk(parsed) | |
if isinstance(node, ast.ClassDef)] | |
funcs = [] | |
# build list of functions in each class | |
for cl in classes: | |
funcs.append([node.name for node in ast.walk(cl) | |
if isinstance(node, ast.FunctionDef)]) | |
# change classes to just the names of the classes | |
classes = [c.name for c in classes] | |
# write out test file | |
with open(args.o, 'w') as fout: | |
fout.write('from unittest import TestCase, main\n') | |
if args.f: | |
fout.write('from %s import %s\n\n\n' % | |
(modname, ', '.join([f for f in funcs[0]]))) | |
else: | |
fout.write('from %s import %s\n\n\n' % | |
(modname, ', '.join([c for c in classes]))) | |
for pos, cl in enumerate(classes): | |
fout.write('class Test%s(TestCase):\n' % cl) | |
for func in funcs[pos]: | |
fout.write(' def test_%s(self):\n' | |
' raise NotImplementedError()\n\n' % func) | |
fout.write('\n') | |
fout.write('if __name__ == "__main__":\n main()\n') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This script reads an input python file and creates a basic test class for each class in the file, then a test function for each function in the class. Alternately, if it is a file of functions, pass the
-f
flag and it will create a single test class for the file and a test function for each function in the file. Give it a whirl and it will make more sense.