PageRenderTime 115ms CodeModel.GetById 26ms RepoModel.GetById 2ms app.codeStats 0ms

/scripts/testMaker.py

https://bitbucket.org/JonLoy/unittestframework
Python | 206 lines | 180 code | 7 blank | 19 comment | 4 complexity | b1c3b47239fe7d0aafd92d3ce00ff7d8 MD5 | raw file
  1. #! /usr/bin/python
  2. #
  3. # Filename: testMaker.py
  4. # Reads each testCaseXX.txt file in the testCases directory
  5. # and creates the corresponding TestCaseXX.java and TestCaseXXresults.txt file
  6. import os
  7. import fnmatch
  8. def run():
  9. """Runs the script"""
  10. text_path = "../testCases/"
  11. os.chdir(text_path)
  12. for file in os.listdir('.'):
  13. if file.endswith('.txt'):
  14. java_dict = dictMaker(file)
  15. # Write the test specications in the testCaseXresults.txt
  16. filename = os.path.splitext(file)[0]
  17. testResultsFile = open("../temp/"+ testResultsWriter(filename), "w")
  18. dictWriter(testResultsFile, java_dict)
  19. testResultsFile.close()
  20. javaFileWriter(filename, java_dict)
  21. def dictMaker(file):
  22. """Reads in testCaseXX.txt and creates a dictionary
  23. Returns a dictionary with values assigned to their corresponding key
  24. Args:
  25. file: the testCaseXX.txt file to be read
  26. Returns:
  27. A dictionary mapping values to the given keys. For example:
  28. {'TestCaseNumber:': ('01'),
  29. 'Component:': ('PatientState.java'),
  30. 'Method:': ('Boolean getActive(Date range)'),
  31. 'Requirement:': ('Should return false if patientState is not
  32. voided but the but the date range is valid'),
  33. 'TestInputs:': ('false, Day, startDate, endDate'),
  34. 'Oracle:': ('TestCase01oracle.txt'),
  35. 'Import:': ('org.openmrs.notification.*;', 'java.util.Date;'),
  36. 'TestCode:': ('PatientState ps = new PatientState();',
  37. 'Date day = new Date();',
  38. 'Date startDate = new Date(day.getTime() - 40000);',
  39. 'Date endDate = new Date(day.getTime() + 40000);',
  40. 'ps.setStartDate(startDate);',
  41. 'ps.setEndDate(endDate);', 'ps.setVoided(true);',
  42. 'boolean outcome = ps.getActive(day);',
  43. 'out.write("Outcome: " + outcome);')')}
  44. If a value is missing from the dictionary then the key was not
  45. found in the text file.
  46. """
  47. KEYWORDS = "TestCaseNumber: Component: Method: Requirement: TestInputs: Oracle: "
  48. keywords_set = set(KEYWORDS.split())
  49. inputFile = open(file, "r")
  50. # creates an empty dictionary for storing text
  51. java_dict = {}
  52. testCode = []
  53. for line in inputFile:
  54. if not line.startswith('#'):
  55. if keywords_set.intersection(line.split()):
  56. firstword = line.partition(' ')[0]
  57. restOfLine = line.partition(' ')[2]
  58. java_dict[firstword] = restOfLine
  59. elif "Import:" in line.split():
  60. firstword = line.partition(' ')[0]
  61. restOfLine = line.partition(' ')[2]
  62. java_dict.setdefault("Import:",[]).append(restOfLine)
  63. else:
  64. if line != '\n':
  65. java_dict.setdefault("TestCode:",[]).append(line)
  66. return java_dict
  67. def javaFileWriter(filename, java_dict):
  68. """ Creates the testCaseXX.java files
  69. Uses values stored in java_dict and import to create a .java file
  70. to be used to in unit testing.
  71. Args:
  72. filename: the beginning of the name of the java file
  73. java_dict: information on what is to be tested
  74. """
  75. # file: the TestCaseXX.java file which contains the unit test to be run
  76. file = filename + ".java"
  77. javaFile = open("../testCasesExecutables/" +capitalize(file), "w")
  78. # write comments in the TestCaseXX.java file
  79. javaFile.write("/*\n")
  80. dictWriter(javaFile, java_dict)
  81. javaFile.write("*/\n")
  82. javaFile.write('\n')
  83. javaFile.write("import java.io.*;" + "\n")
  84. if java_dict.has_key("Import:") and java_dict["Import:"]:
  85. list_of_imports = java_dict["Import:"]
  86. for package in list_of_imports:
  87. javaFile.write("import " + package)
  88. else:
  89. pass # no additional import statements
  90. javaFile.write("\n")
  91. javaFile.write("class " + capitalize(filename) +"{\n")
  92. javaFile.write("\tpublic static void main(String args[]){\n")
  93. javaFile.write("\t\ttry{\n")
  94. javaFile.write("\t\t\tFileWriter fstream;\n")
  95. javaFile.write("\t\t\tBufferedWriter out;\n")
  96. javaFile.write("\n\t\t\t// FileWriter for " + filename +".java\n")
  97. javaFile.write("\t\t\tfstream = new FileWriter(\"../temp/" + capitalize(filename) + "results.txt\", true);\n")
  98. javaFile.write("\t\t\tout = new BufferedWriter(fstream);\n")
  99. javaFile.write("\n")
  100. if java_dict.has_key("TestCode:") and java_dict["TestCode:"]:
  101. testCodeList = java_dict["TestCode:"]
  102. for code in testCodeList:
  103. javaFile.write("\t\t\t" + code)
  104. else:
  105. pass # no additional import statements
  106. javaFile.write("\t\t\tout.close();\n")
  107. javaFile.write("\t\t\tfstream.close();\n\n")
  108. javaFile.write("\t\t}catch(Exception e){\n")
  109. javaFile.write("\t\t\tSystem.err.println(\"Error: \" + e.getMessage());\n")
  110. javaFile.write("\t\t}\n")
  111. javaFile.write("\t}\n")
  112. javaFile.write("}\n")
  113. javaFile.close()
  114. def testResultsWriter(filename):
  115. """Creates the testCaseXXresults.txt file
  116. Creates the testCaseXXresults.txt file
  117. Args:
  118. filename: the filename of the testCaseXX.txt file
  119. Returns:
  120. A filename of the text file where the results of the unit test is
  121. written. Filename uses the following format:
  122. testCaseXXresults.txt
  123. XX stands in for the test case number.
  124. """
  125. filename = os.path.splitext(filename)[0]
  126. resultsFile = capitalize(filename) + "results.txt"
  127. return resultsFile
  128. def dictWriter(file, java_dict):
  129. """Writes the information in java_dict to a file
  130. Retrives the values pertaining to the given keys from the dictionary
  131. instance represented by java_dict. It then writes the key and its value
  132. to the provided file in a standard format.
  133. Args:
  134. file: the file to be written to.
  135. java_dict: A dictionary containing information about a test case.
  136. """
  137. file.write("TestCaseNumber: " + java_dict["TestCaseNumber:"])
  138. file.write("Component: " + java_dict["Component:"])
  139. file.write("Method: " + java_dict["Method:"])
  140. file.write("Requirement: " + java_dict["Requirement:"])
  141. file.write("TestInputs: " + java_dict["TestInputs:"])
  142. file.write("Oracle: " + java_dict["Oracle:"])
  143. def capitalize(word):
  144. """Capitalizes the first letter in a word.
  145. Capitalizes the first letter in a word without altering
  146. the case of any other letter in the word.
  147. Args:
  148. word:
  149. Returns:
  150. A word with its first letter capitalized and the rest of the
  151. word retains its original cases. For example:
  152. capitalize(testCase01) returns
  153. TestCase01
  154. """
  155. return word[:1].upper() + word[1:]