Skip to content

Instantly share code, notes, and snippets.

@philipaconrad
Last active December 13, 2017 07:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philipaconrad/99c1706e2ed2c99a36f2e03cee0af356 to your computer and use it in GitHub Desktop.
Save philipaconrad/99c1706e2ed2c99a36f2e03cee0af356 to your computer and use it in GitHub Desktop.
Generate JUnit test stubs using Python/regexes.
from __future__ import print_function
import os
import sys
import re
import string
template_decl = " @Test public void test{}()"
template_get_body = """ assertTrue(my{}.{}() == /* ... */);"""
template_set_body = """ my{}.{}();
assertTrue(my{}./*getter goes here*/ == /*...*/);"""
# Matches all public methods in a class.
# Ignores return type and parameters.
re_method_name = "public (?P<type>\w+) (?P<method>\w+)\("
# Hack, but it will work.
def capitalize(s):
first = s[0]
first_cap = first.capitalize()
return first_cap + s[1:]
if __name__ == '__main__':
fixture = sys.argv[1].split('.')[0]
text = open(sys.argv[1], 'r').read()
method_name = re.compile(re_method_name)
matches = re.findall(method_name, text)
for match in matches:
# Pull out capture group parts.
return_type = match[0]
method = match[1]
# Capitalize the first letter of the method name,
# shove it into the template, and bail.
out = template_decl.format(capitalize(match[1])) + " {\n"
if method.startswith("get"):
out += template_get_body.format(fixture,
method)
elif method.startswith("set"):
out += template_set_body.format(fixture,
method,
fixture)
out += "\n }\n"
print(out)
@philipaconrad
Copy link
Author

Updated to give prettier output.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment