run.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. #!/usr/bin/env python3
  2. #
  3. # Copyright (C) 2019 Intel Corporation. All rights reserved.
  4. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  5. #
  6. import json
  7. import os
  8. import subprocess
  9. import glob
  10. import re
  11. import argparse
  12. from typing import Dict, Optional, List
  13. WORK_DIR = os.getcwd()
  14. TEST_WASM_COMMAND = (
  15. "./build/build-{runtime}/iwasm {running_options} {running_mode} {file} {argument}"
  16. )
  17. COMPILE_AOT_COMMAND = "./build/build-wamrc/{compiler} {options} -o {out_file} {in_file}"
  18. TEST_AOT_COMMAND = "./build/build-{runtime}/iwasm {running_options} {file} {argument}"
  19. LOG_FILE = "issues_tests.log"
  20. LOG_ENTRY = """
  21. =======================================================
  22. Failing issue id: {}.
  23. run with command_lists: {}
  24. {}
  25. {}
  26. =======================================================
  27. """
  28. # Function to read and parse JSON file
  29. def read_json_file(file_path):
  30. with open(file_path, "r") as file:
  31. return json.load(file)
  32. return None
  33. def dump_error_log(failing_issue_id, command_lists, exit_code_cmp, stdout_cmp):
  34. with open(LOG_FILE, "a") as file:
  35. file.write(
  36. LOG_ENTRY.format(failing_issue_id, command_lists, exit_code_cmp, stdout_cmp)
  37. )
  38. def get_issue_ids_should_test(selected_ids: Optional[List[int]] = None):
  39. """Find all issue IDs that should be tested in folder issues."""
  40. # If specific issue IDs are provided, return them as a set
  41. if selected_ids:
  42. return set(selected_ids)
  43. # Define the path pattern
  44. path_pattern = "issues/issue-*"
  45. # Regular expression to extract the number
  46. pattern = r"issue-(\d+)"
  47. # Initialize a set to store the issue numbers
  48. issue_numbers = set()
  49. # Use glob to find directories matching the pattern
  50. for dir_path in glob.glob(path_pattern):
  51. # Extract the issue number using regular expression
  52. match = re.search(pattern, dir_path)
  53. if match:
  54. issue_number = int(match.group(1))
  55. issue_numbers.add(issue_number)
  56. # Print the set of issue numbers
  57. return issue_numbers
  58. def get_and_check(d, key, default=None, nullable=False):
  59. element = d.get(key, default)
  60. if not nullable and element is None:
  61. raise Exception(f"Missing {key} in {d}")
  62. return element
  63. def run_and_compare_results(
  64. issue_id, cmd, description, ret_code, stdout_content
  65. ) -> bool:
  66. print(f"####################################")
  67. print(f"test BA issue #{issue_id} `{description}`...")
  68. command_list = cmd.split()
  69. result = subprocess.run(
  70. command_list,
  71. stdout=subprocess.PIPE,
  72. stderr=subprocess.PIPE,
  73. text=True,
  74. errors="ignore",
  75. )
  76. actual_exit_code = result.returncode
  77. actual_output = result.stdout.rstrip("\n")
  78. exit_code_cmp = f"exit code (actual, expected) : {actual_exit_code, ret_code}"
  79. stdout_cmp = f"stdout (actual, expected) : {actual_output, stdout_content}"
  80. if actual_exit_code == ret_code and (
  81. actual_output == stdout_content
  82. or (
  83. stdout_content == "Compile success"
  84. and actual_output.find(stdout_content) != -1
  85. )
  86. or (len(stdout_content) > 30 and actual_output.find(stdout_content) != -1)
  87. ):
  88. print("== PASS ==")
  89. return True
  90. else:
  91. print(cmd)
  92. print(exit_code_cmp)
  93. print(stdout_cmp)
  94. print(f"== FAILED: {issue_id} ==")
  95. dump_error_log(
  96. issue_id,
  97. command_list,
  98. exit_code_cmp,
  99. stdout_cmp,
  100. )
  101. return False
  102. def run_issue_test_wamrc(issue_id, compile_options):
  103. compiler = get_and_check(compile_options, "compiler")
  104. in_file = get_and_check(compile_options, "in file")
  105. out_file = get_and_check(compile_options, "out file")
  106. options = get_and_check(compile_options, "options")
  107. expected_return = get_and_check(compile_options, "expected return")
  108. ret_code = get_and_check(expected_return, "ret code")
  109. stdout_content = get_and_check(expected_return, "stdout content")
  110. description = get_and_check(expected_return, "description")
  111. issue_path = os.path.join(WORK_DIR, f"issues/issue-{issue_id}/")
  112. # file maybe *.wasm or *.aot, needs to the match the exact file name
  113. actual_file = glob.glob(issue_path + in_file)
  114. assert len(actual_file) == 1
  115. # the absolute file path
  116. in_file_path = os.path.join(issue_path, actual_file[0])
  117. out_file_path = os.path.join(issue_path, out_file)
  118. cmd = COMPILE_AOT_COMMAND.format(
  119. compiler=compiler, options=options, out_file=out_file_path, in_file=in_file_path
  120. )
  121. return run_and_compare_results(issue_id, cmd, description, ret_code, stdout_content)
  122. def run_issue_test_iwasm(issue_id, test_case) -> bool:
  123. runtime = get_and_check(test_case, "runtime")
  124. mode = get_and_check(test_case, "mode")
  125. file = get_and_check(test_case, "file")
  126. options = get_and_check(test_case, "options")
  127. argument = get_and_check(test_case, "argument")
  128. expected_return = get_and_check(test_case, "expected return")
  129. ret_code = get_and_check(expected_return, "ret code")
  130. stdout_content = get_and_check(expected_return, "stdout content")
  131. description = get_and_check(expected_return, "description")
  132. issue_path = os.path.join(WORK_DIR, f"issues/issue-{issue_id}/")
  133. # file maybe *.wasm or *.aot, needs to the match the exact file name
  134. actual_file = glob.glob(issue_path + file)
  135. assert len(actual_file) == 1
  136. # the absolute file path
  137. file_path = os.path.join(issue_path, actual_file[0])
  138. if mode == "aot":
  139. cmd = TEST_AOT_COMMAND.format(
  140. runtime=runtime,
  141. file=file_path,
  142. running_options=options,
  143. argument=argument,
  144. )
  145. else:
  146. if mode == "classic-interp":
  147. running_mode = "--interp"
  148. elif mode == "fast-interp":
  149. running_mode = ""
  150. else:
  151. running_mode = f"--{mode}"
  152. cmd = TEST_WASM_COMMAND.format(
  153. runtime=runtime,
  154. running_mode=running_mode,
  155. file=file_path,
  156. running_options=options,
  157. argument=argument,
  158. )
  159. return run_and_compare_results(issue_id, cmd, description, ret_code, stdout_content)
  160. def process_and_run_test_cases(
  161. data: Dict[str, Dict], selected_ids: Optional[List[int]] = None
  162. ):
  163. issue_ids_should_test = get_issue_ids_should_test(selected_ids)
  164. passed_ids = set()
  165. failed_ids = set()
  166. json_only_ids = set()
  167. # Iterate through each test case in the json data
  168. for test_case in data.get("test cases", []):
  169. is_deprecated = get_and_check(test_case, "deprecated")
  170. issue_ids = get_and_check(test_case, "ids", default=[])
  171. if is_deprecated:
  172. print(f"test case {issue_ids} are deprecated, continue running nest one(s)")
  173. continue
  174. compile_options = get_and_check(test_case, "compile_options", nullable=True)
  175. for issue_id in issue_ids:
  176. if issue_id not in issue_ids_should_test:
  177. json_only_ids.add(issue_id)
  178. continue
  179. # cross out the this issue_id in the should test set
  180. issue_ids_should_test.remove(issue_id)
  181. only_compile = False
  182. # if this issue needs to test wamrc to compile the test case first
  183. if compile_options:
  184. only_compile = compile_options["only compile"]
  185. compile_res = run_issue_test_wamrc(issue_id, compile_options)
  186. if only_compile:
  187. if compile_res:
  188. passed_ids.add(issue_id)
  189. else:
  190. failed_ids.add(issue_id)
  191. continue
  192. else:
  193. # if compile success, then continue to test iwasm
  194. if not compile_res:
  195. failed_ids.add(issue_id)
  196. continue
  197. # if this issue requires to test iwasm to run the test case
  198. if not only_compile:
  199. if run_issue_test_iwasm(issue_id, test_case):
  200. passed_ids.add(issue_id)
  201. else:
  202. failed_ids.add(issue_id)
  203. total = len(passed_ids) + len(failed_ids)
  204. passed = len(passed_ids)
  205. failed = len(failed_ids)
  206. format_issue_ids_should_test = (
  207. " ".join(f"#{x}" for x in issue_ids_should_test)
  208. if issue_ids_should_test
  209. else "no more"
  210. )
  211. format_json_only_ids = (
  212. " ".join(f"#{x}" for x in json_only_ids) if json_only_ids else "no more"
  213. )
  214. print(f"####################################")
  215. print(f"==== Test results ====")
  216. print(f" Total: {total}")
  217. print(f" Passed: {passed}")
  218. print(f" Failed: {failed}")
  219. if not selected_ids:
  220. print(f" Left issues in folder: {format_issue_ids_should_test}")
  221. print(f" Cases in JSON but not found in folder: {format_json_only_ids}")
  222. else:
  223. print(f" Issues not found in folder: {format_issue_ids_should_test}")
  224. def main():
  225. parser = argparse.ArgumentParser(description="Run BA issue tests.")
  226. parser.add_argument(
  227. "-i",
  228. "--issues",
  229. type=str,
  230. help="Comma separated list of issue ids to run, e.g. 1,2,3. Default: all.",
  231. )
  232. args = parser.parse_args()
  233. selected_ids = None
  234. if args.issues:
  235. selected_ids = [int(x) for x in args.issues.split(",") if x.strip().isdigit()]
  236. # Path to the JSON file
  237. file_path = "running_config.json"
  238. # Read and parse the JSON file
  239. data = read_json_file(file_path)
  240. # Check if data is successfully read
  241. if data is None:
  242. assert 0, "No data to process."
  243. # Remove the log file from last run if it exists
  244. if os.path.exists(LOG_FILE):
  245. os.remove(LOG_FILE)
  246. # Process the data
  247. process_and_run_test_cases(data, selected_ids)
  248. if __name__ == "__main__":
  249. main()