/scripts/testMaker.py
Python | 206 lines | 180 code | 7 blank | 19 comment | 4 complexity | b1c3b47239fe7d0aafd92d3ce00ff7d8 MD5 | raw file
- #! /usr/bin/python
- #
- # Filename: testMaker.py
- # Reads each testCaseXX.txt file in the testCases directory
- # and creates the corresponding TestCaseXX.java and TestCaseXXresults.txt file
- import os
- import fnmatch
- def run():
- """Runs the script"""
- text_path = "../testCases/"
- os.chdir(text_path)
- for file in os.listdir('.'):
- if file.endswith('.txt'):
- java_dict = dictMaker(file)
- # Write the test specications in the testCaseXresults.txt
- filename = os.path.splitext(file)[0]
- testResultsFile = open("../temp/"+ testResultsWriter(filename), "w")
- dictWriter(testResultsFile, java_dict)
- testResultsFile.close()
- javaFileWriter(filename, java_dict)
-
- def dictMaker(file):
- """Reads in testCaseXX.txt and creates a dictionary
- Returns a dictionary with values assigned to their corresponding key
- Args:
- file: the testCaseXX.txt file to be read
- Returns:
- A dictionary mapping values to the given keys. For example:
- {'TestCaseNumber:': ('01'),
- 'Component:': ('PatientState.java'),
- 'Method:': ('Boolean getActive(Date range)'),
- 'Requirement:': ('Should return false if patientState is not
- voided but the but the date range is valid'),
- 'TestInputs:': ('false, Day, startDate, endDate'),
- 'Oracle:': ('TestCase01oracle.txt'),
- 'Import:': ('org.openmrs.notification.*;', 'java.util.Date;'),
- 'TestCode:': ('PatientState ps = new PatientState();',
- 'Date day = new Date();',
- 'Date startDate = new Date(day.getTime() - 40000);',
- 'Date endDate = new Date(day.getTime() + 40000);',
- 'ps.setStartDate(startDate);',
- 'ps.setEndDate(endDate);', 'ps.setVoided(true);',
- 'boolean outcome = ps.getActive(day);',
- 'out.write("Outcome: " + outcome);')')}
- If a value is missing from the dictionary then the key was not
- found in the text file.
- """
- KEYWORDS = "TestCaseNumber: Component: Method: Requirement: TestInputs: Oracle: "
- keywords_set = set(KEYWORDS.split())
-
-
- inputFile = open(file, "r")
-
- # creates an empty dictionary for storing text
- java_dict = {}
- testCode = []
- for line in inputFile:
- if not line.startswith('#'):
- if keywords_set.intersection(line.split()):
- firstword = line.partition(' ')[0]
- restOfLine = line.partition(' ')[2]
- java_dict[firstword] = restOfLine
- elif "Import:" in line.split():
- firstword = line.partition(' ')[0]
- restOfLine = line.partition(' ')[2]
- java_dict.setdefault("Import:",[]).append(restOfLine)
- else:
- if line != '\n':
- java_dict.setdefault("TestCode:",[]).append(line)
-
- return java_dict
- def javaFileWriter(filename, java_dict):
- """ Creates the testCaseXX.java files
- Uses values stored in java_dict and import to create a .java file
- to be used to in unit testing.
- Args:
- filename: the beginning of the name of the java file
- java_dict: information on what is to be tested
-
- """
-
- # file: the TestCaseXX.java file which contains the unit test to be run
- file = filename + ".java"
- javaFile = open("../testCasesExecutables/" +capitalize(file), "w")
- # write comments in the TestCaseXX.java file
- javaFile.write("/*\n")
- dictWriter(javaFile, java_dict)
- javaFile.write("*/\n")
- javaFile.write('\n')
- javaFile.write("import java.io.*;" + "\n")
- if java_dict.has_key("Import:") and java_dict["Import:"]:
- list_of_imports = java_dict["Import:"]
- for package in list_of_imports:
- javaFile.write("import " + package)
- else:
- pass # no additional import statements
- javaFile.write("\n")
- javaFile.write("class " + capitalize(filename) +"{\n")
- javaFile.write("\tpublic static void main(String args[]){\n")
- javaFile.write("\t\ttry{\n")
- javaFile.write("\t\t\tFileWriter fstream;\n")
- javaFile.write("\t\t\tBufferedWriter out;\n")
- javaFile.write("\n\t\t\t// FileWriter for " + filename +".java\n")
- javaFile.write("\t\t\tfstream = new FileWriter(\"../temp/" + capitalize(filename) + "results.txt\", true);\n")
- javaFile.write("\t\t\tout = new BufferedWriter(fstream);\n")
- javaFile.write("\n")
- if java_dict.has_key("TestCode:") and java_dict["TestCode:"]:
- testCodeList = java_dict["TestCode:"]
- for code in testCodeList:
- javaFile.write("\t\t\t" + code)
- else:
- pass # no additional import statements
-
- javaFile.write("\t\t\tout.close();\n")
- javaFile.write("\t\t\tfstream.close();\n\n")
- javaFile.write("\t\t}catch(Exception e){\n")
- javaFile.write("\t\t\tSystem.err.println(\"Error: \" + e.getMessage());\n")
- javaFile.write("\t\t}\n")
- javaFile.write("\t}\n")
- javaFile.write("}\n")
- javaFile.close()
- def testResultsWriter(filename):
- """Creates the testCaseXXresults.txt file
- Creates the testCaseXXresults.txt file
- Args:
- filename: the filename of the testCaseXX.txt file
- Returns:
- A filename of the text file where the results of the unit test is
- written. Filename uses the following format:
- testCaseXXresults.txt
- XX stands in for the test case number.
-
- """
- filename = os.path.splitext(filename)[0]
- resultsFile = capitalize(filename) + "results.txt"
-
- return resultsFile
- def dictWriter(file, java_dict):
- """Writes the information in java_dict to a file
- Retrives the values pertaining to the given keys from the dictionary
- instance represented by java_dict. It then writes the key and its value
- to the provided file in a standard format.
- Args:
- file: the file to be written to.
- java_dict: A dictionary containing information about a test case.
- """
- file.write("TestCaseNumber: " + java_dict["TestCaseNumber:"])
- file.write("Component: " + java_dict["Component:"])
- file.write("Method: " + java_dict["Method:"])
- file.write("Requirement: " + java_dict["Requirement:"])
- file.write("TestInputs: " + java_dict["TestInputs:"])
- file.write("Oracle: " + java_dict["Oracle:"])
- def capitalize(word):
- """Capitalizes the first letter in a word.
- Capitalizes the first letter in a word without altering
- the case of any other letter in the word.
- Args:
- word:
- Returns:
- A word with its first letter capitalized and the rest of the
- word retains its original cases. For example:
- capitalize(testCase01) returns
- TestCase01
- """
- return word[:1].upper() + word[1:]