common.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. #
  2. # Metrix++, Copyright 2009-2019, Metrix++ Project
  3. # Link: https://github.com/metrixplusplus/metrixplusplus
  4. #
  5. # This file is a part of Metrix++ Tool.
  6. #
  7. import inspect
  8. import os.path
  9. import subprocess
  10. import logging
  11. import difflib
  12. import unittest
  13. import shutil
  14. class ToolRunner(object):
  15. def __init__(self,
  16. tool_name,
  17. opts_list = [],
  18. dirs_list = None,
  19. cwd='sources',
  20. prefix = "default",
  21. exit_code = 0,
  22. save_prev = False,
  23. use_prev = False,
  24. check_stderr = None,
  25. remove_exiting_dbfile = None,
  26. remove_exiting_dbfile_prev = False):
  27. self.message = ""
  28. # identify gold_file_location
  29. curframe = inspect.currentframe()
  30. calframe = inspect.getouterframes(curframe, 2)
  31. test_name = calframe[1][3]
  32. suite_name = os.path.splitext(os.path.basename(calframe[1][1]))[0]
  33. group_name = os.path.basename(os.path.dirname(calframe[1][1]))
  34. self.suite_location = os.path.join('tests', group_name, suite_name)
  35. self.test_location = os.path.join(self.suite_location, test_name + "_" + tool_name + "_" + str(prefix))
  36. db_file = os.path.join(os.environ['METRIXPLUSPLUS_INSTALL_DIR'], self.suite_location, test_name + ".db")
  37. self.dbfile = db_file
  38. if (remove_exiting_dbfile == True or (remove_exiting_dbfile == None and tool_name == 'collect')) and os.path.exists(db_file):
  39. os.unlink(db_file)
  40. db_file_prev = os.path.join(os.environ['METRIXPLUSPLUS_INSTALL_DIR'], self.suite_location, test_name + ".prev.db")
  41. self.dbfile_prev = db_file_prev
  42. if (remove_exiting_dbfile_prev == True or (remove_exiting_dbfile_prev == None and tool_name == 'collect')) and os.path.exists(db_file_prev):
  43. os.unlink(db_file_prev)
  44. self.cwd = cwd
  45. db_opts = ['--db-file=' + db_file]
  46. if use_prev == True:
  47. db_opts.append('--db-file-prev=' + db_file_prev)
  48. self.dbopts = db_opts
  49. self.dirs_list = []
  50. if dirs_list != None:
  51. for each in dirs_list:
  52. self.dirs_list.append(each)
  53. self.call_args = ['python', os.path.join(os.environ['METRIXPLUSPLUS_INSTALL_DIR'], "metrix++.py"), tool_name] \
  54. + db_opts + opts_list + ['--'] + self.dirs_list
  55. self.cmd = " ".join(self.call_args)
  56. self.exit_code_expected = exit_code
  57. self.stderr_lines = check_stderr
  58. self.save_prev = save_prev
  59. def run(self):
  60. logging.debug(self.get_description())
  61. child = subprocess.Popen(self.call_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  62. cwd=os.path.join(self.suite_location, self.cwd))
  63. (child_stdout, child_stderr) = child.communicate()
  64. self.exit_code = child.returncode
  65. gold_file_stdout = self.test_location + "_stdout.gold.txt"
  66. real_file_stdout = self.test_location + "_stdout.real.txt"
  67. diff_file_stdout = self.test_location + "_stdout.diff.html"
  68. gold_file_stderr = self.test_location + "_stderr.gold.txt"
  69. real_file_stderr = self.test_location + "_stderr.real.txt"
  70. diff_file_stderr = self.test_location + "_stderr.diff.html"
  71. # Regenerate gold files if it was requested
  72. if os.environ['METRIXPLUSPLUS_TEST_GENERATE_GOLDS'] == "True":
  73. f = open(gold_file_stdout, 'wb');
  74. f.write(child_stdout);
  75. f.close()
  76. if self.stderr_lines != None:
  77. f = open(gold_file_stderr, 'wb');
  78. f.write(child_stderr);
  79. f.close()
  80. # Match with gold
  81. self.is_stdout_matched = self.inetrnal_compare_with_gold(child_stdout, gold_file_stdout, real_file_stdout, diff_file_stdout)
  82. if self.stderr_lines != None:
  83. self.is_stderr_matched = self.inetrnal_compare_with_gold(child_stderr, gold_file_stderr, real_file_stderr, diff_file_stderr, self.stderr_lines)
  84. else:
  85. self.is_stderr_matched = None
  86. if self.is_stdout_matched == False:
  87. f = open(real_file_stderr, 'wb');
  88. f.write(child_stderr);
  89. f.close()
  90. else:
  91. if os.path.exists(real_file_stderr):
  92. os.unlink(real_file_stderr)
  93. if self.save_prev == True:
  94. shutil.copy2(self.dbfile, self.dbfile_prev)
  95. return self
  96. def inetrnal_compare_with_gold(self, text, gold_file, real_file, diff_file, lines = None):
  97. if os.path.exists(gold_file) == False:
  98. self.message += "\nGold file does not exist: " + gold_file
  99. return False
  100. f = open(gold_file, 'rU');
  101. gold_text = f.read();
  102. f.close()
  103. gold_to_compare = gold_text
  104. text_to_compare = text
  105. if lines != None:
  106. gold_to_compare = ""
  107. text_to_compare = ""
  108. gold_lines = gold_text.splitlines(True)
  109. text_lines = text.splitlines(True)
  110. for each in lines:
  111. gold_to_compare += "".join(gold_lines[each[0] : each[1]])
  112. text_to_compare += "".join(text_lines[each[0] : each[1]])
  113. gold_to_compare = gold_to_compare.replace('\r', '')
  114. text_to_compare = text_to_compare.replace('\r', '')
  115. result = (gold_to_compare == text_to_compare)
  116. if result == False:
  117. f = open(real_file, 'wb');
  118. f.write(text);
  119. f.close()
  120. diff_text = difflib.HtmlDiff().make_file(gold_to_compare.splitlines(), text_to_compare.splitlines(), "Gold file", "Real output")
  121. f = open(diff_file, 'w');
  122. f.write(diff_text);
  123. f.close()
  124. else:
  125. if os.path.exists(real_file):
  126. os.unlink(real_file)
  127. if os.path.exists(diff_file):
  128. os.unlink(diff_file)
  129. return result
  130. def check_exit_code(self):
  131. return self.exit_code == self.exit_code_expected
  132. def check_stdout(self):
  133. return self.is_stdout_matched
  134. def check_stderr(self):
  135. if self.is_stderr_matched == None:
  136. return True
  137. return self.is_stderr_matched
  138. def check_all(self):
  139. result = self.check_exit_code() and self.check_stdout() and self.check_stderr()
  140. if result == False:
  141. self.message += "\nCheck for exit code: " + str(self.check_exit_code()) \
  142. + ", gold: " + str(self.exit_code_expected) + ", real: " + str(self.exit_code) + \
  143. "\nCheck for stdout: " + str(self.check_stdout()) + "\nCheck for stderr: " + str(self.check_stderr())
  144. return result
  145. def get_message(self):
  146. return self.message
  147. def get_cmd(self):
  148. return self.cmd
  149. def get_description(self):
  150. return self.get_message() + "\nProcess: " + self.get_cmd() + "\nCWD: " + os.path.join(self.suite_location, self.cwd)
  151. def get_dbfile(self):
  152. return self.dbfile
  153. def get_dbfile_prev(self):
  154. return self.dbfile_prev
  155. class TestCase(unittest.TestCase):
  156. def __init__(self, methodName='runTest'):
  157. unittest.TestCase.__init__(self, methodName=methodName)
  158. if 'METRIXPLUSPLUS_LOG_LEVEL' not in os.environ.keys():
  159. # launch of individual unit test
  160. os.environ['METRIXPLUSPLUS_LOG_LEVEL'] = 'ERROR'
  161. os.environ['METRIXPLUSPLUS_INSTALL_DIR'] = os.path.dirname(os.path.dirname(__file__))
  162. os.environ['METRIXPLUSPLUS_TEST_MODE'] = str("True")
  163. if 'METRIXPLUSPLUS_TEST_GENERATE_GOLDS' not in os.environ.keys():
  164. os.environ['METRIXPLUSPLUS_TEST_GENERATE_GOLDS'] = str("False")
  165. os.chdir(os.environ['METRIXPLUSPLUS_INSTALL_DIR'])
  166. def get_content_paths(self, cwd='sources'):
  167. curframe = inspect.currentframe()
  168. calframe = inspect.getouterframes(curframe, 2)
  169. test_name = calframe[1][3]
  170. suite_name = os.path.splitext(os.path.basename(calframe[1][1]))[0]
  171. group_name = os.path.basename(os.path.dirname(calframe[1][1]))
  172. class ContentPaths(object):
  173. def __init__(self, cwd, dbfile, dbfile_prev):
  174. self.cwd = cwd
  175. self.dbfile = dbfile
  176. self.dbfile_prev = dbfile_prev
  177. return ContentPaths(os.path.join('tests', group_name, suite_name, cwd),
  178. os.path.join(os.environ['METRIXPLUSPLUS_INSTALL_DIR'], 'tests', group_name, suite_name, test_name + ".db"),
  179. os.path.join(os.environ['METRIXPLUSPLUS_INSTALL_DIR'], 'tests', group_name, suite_name, test_name + ".prev.db"))
  180. def setUp(self):
  181. unittest.TestCase.setUp(self)
  182. logging.basicConfig(format="[TEST-LOG]: %(levelname)s:\t%(message)s", level=logging.WARN)
  183. log_level = os.environ['METRIXPLUSPLUS_LOG_LEVEL']
  184. if log_level == 'ERROR':
  185. log_level = logging.ERROR
  186. elif log_level == 'WARNING':
  187. log_level = logging.WARNING
  188. elif log_level == 'INFO':
  189. log_level = logging.INFO
  190. elif log_level == 'DEBUG':
  191. log_level = logging.DEBUG
  192. else:
  193. raise AssertionError("Unhandled choice of log level")
  194. logging.getLogger().setLevel(log_level)
  195. self.runners = []
  196. def assertExec(self, runner):
  197. # keep reference, so files are not removed during test case time
  198. self.runners.append(runner)
  199. self.assertTrue(runner.check_all(), runner.get_description())
  200. def run(self, result=None):
  201. self.current_result = result # remember result for use in tearDown
  202. unittest.TestCase.run(self, result)
  203. def tearDown(self):
  204. unittest.TestCase.tearDown(self)
  205. if self.current_result.wasSuccessful() == True:
  206. for each in self.runners:
  207. if each.check_all() == True:
  208. if os.path.exists(each.get_dbfile()):
  209. os.unlink(each.get_dbfile())
  210. if os.path.exists(each.get_dbfile_prev()):
  211. os.unlink(each.get_dbfile_prev())