run.py 9.9 KB

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