generate-summary.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. #!/usr/bin/env python3
  2. import argparse
  3. import dataclasses
  4. import os
  5. import sys
  6. import traceback
  7. from codeowners import CodeOwners
  8. from enum import Enum
  9. from operator import attrgetter
  10. from typing import List, Dict
  11. from jinja2 import Environment, FileSystemLoader, StrictUndefined
  12. from junit_utils import get_property_value, iter_xml_files
  13. from get_test_history import get_test_history
  14. class TestStatus(Enum):
  15. PASS = 0
  16. FAIL = 1
  17. ERROR = 2
  18. SKIP = 3
  19. MUTE = 4
  20. @property
  21. def is_error(self):
  22. return self in (TestStatus.FAIL, TestStatus.ERROR, TestStatus.MUTE)
  23. def __lt__(self, other):
  24. return self.value < other.value
  25. @dataclasses.dataclass
  26. class TestResult:
  27. classname: str
  28. name: str
  29. status: TestStatus
  30. log_urls: Dict[str, str]
  31. elapsed: float
  32. count_of_passed: int
  33. owners: str
  34. @property
  35. def status_display(self):
  36. return {
  37. TestStatus.PASS: "PASS",
  38. TestStatus.FAIL: "FAIL",
  39. TestStatus.ERROR: "ERROR",
  40. TestStatus.SKIP: "SKIP",
  41. TestStatus.MUTE: "MUTE",
  42. }[self.status]
  43. @property
  44. def elapsed_display(self):
  45. m, s = divmod(self.elapsed, 60)
  46. parts = []
  47. if m > 0:
  48. parts.append(f'{int(m)}m')
  49. parts.append(f"{s:.3f}s")
  50. return ' '.join(parts)
  51. def __str__(self):
  52. return f"{self.full_name:<138} {self.status_display}"
  53. @property
  54. def full_name(self):
  55. return f"{self.classname}/{self.name}"
  56. @classmethod
  57. def from_junit(cls, testcase):
  58. classname, name = testcase.get("classname"), testcase.get("name")
  59. if testcase.find("failure") is not None:
  60. status = TestStatus.FAIL
  61. elif testcase.find("error") is not None:
  62. status = TestStatus.ERROR
  63. elif get_property_value(testcase, "mute") is not None:
  64. status = TestStatus.MUTE
  65. elif testcase.find("skipped") is not None:
  66. status = TestStatus.SKIP
  67. else:
  68. status = TestStatus.PASS
  69. log_urls = {
  70. 'Log': get_property_value(testcase, "url:Log"),
  71. 'log': get_property_value(testcase, "url:log"),
  72. 'logsdir': get_property_value(testcase, "url:logsdir"),
  73. 'stdout': get_property_value(testcase, "url:stdout"),
  74. 'stderr': get_property_value(testcase, "url:stderr"),
  75. }
  76. log_urls = {k: v for k, v in log_urls.items() if v}
  77. elapsed = testcase.get("time")
  78. try:
  79. elapsed = float(elapsed)
  80. except (TypeError, ValueError):
  81. elapsed = 0
  82. print(f"Unable to cast elapsed time for {classname}::{name} value={elapsed!r}")
  83. return cls(classname, name, status, log_urls, elapsed, 0,'')
  84. class TestSummaryLine:
  85. def __init__(self, title):
  86. self.title = title
  87. self.tests = []
  88. self.is_failed = False
  89. self.report_fn = self.report_url = None
  90. self.counter = {s: 0 for s in TestStatus}
  91. def add(self, test: TestResult):
  92. self.is_failed |= test.status in (TestStatus.ERROR, TestStatus.FAIL)
  93. self.counter[test.status] += 1
  94. self.tests.append(test)
  95. def add_report(self, fn, url):
  96. self.report_fn = fn
  97. self.report_url = url
  98. @property
  99. def test_count(self):
  100. return len(self.tests)
  101. @property
  102. def passed(self):
  103. return self.counter[TestStatus.PASS]
  104. @property
  105. def errors(self):
  106. return self.counter[TestStatus.ERROR]
  107. @property
  108. def failed(self):
  109. return self.counter[TestStatus.FAIL]
  110. @property
  111. def skipped(self):
  112. return self.counter[TestStatus.SKIP]
  113. @property
  114. def muted(self):
  115. return self.counter[TestStatus.MUTE]
  116. class TestSummary:
  117. def __init__(self, is_retry: bool):
  118. self.lines: List[TestSummaryLine] = []
  119. self.is_failed = False
  120. self.is_retry = is_retry
  121. def add_line(self, line: TestSummaryLine):
  122. self.is_failed |= line.is_failed
  123. self.lines.append(line)
  124. def render_line(self, items):
  125. return f"| {' | '.join(items)} |"
  126. def render(self, add_footnote=False, is_retry=False):
  127. github_srv = os.environ.get("GITHUB_SERVER_URL", "https://github.com")
  128. repo = os.environ.get("GITHUB_REPOSITORY", "ydb-platform/ydb")
  129. footnote_url = f"{github_srv}/{repo}/tree/main/.github/config/muted_ya.txt"
  130. footnote = "[^1]" if add_footnote else f'<sup>[?]({footnote_url} "All mute rules are defined here")</sup>'
  131. columns = [
  132. "TESTS", "PASSED", "ERRORS", "FAILED", "SKIPPED", f"MUTED{footnote}"
  133. ]
  134. need_first_column = len(self.lines) > 1
  135. if need_first_column:
  136. columns.insert(0, "")
  137. result = []
  138. result.append(self.render_line(columns))
  139. if need_first_column:
  140. result.append(self.render_line([':---'] + ['---:'] * (len(columns) - 1)))
  141. else:
  142. result.append(self.render_line(['---:'] * len(columns)))
  143. for line in self.lines:
  144. report_url = line.report_url
  145. row = []
  146. if need_first_column:
  147. row.append(line.title)
  148. row.extend([
  149. render_pm(f"{line.test_count}" + (" (only retried tests)" if self.is_retry else ""), f"{report_url}", 0),
  150. render_pm(line.passed, f"{report_url}#PASS", 0),
  151. render_pm(line.errors, f"{report_url}#ERROR", 0),
  152. render_pm(line.failed, f"{report_url}#FAIL", 0),
  153. render_pm(line.skipped, f"{report_url}#SKIP", 0),
  154. render_pm(line.muted, f"{report_url}#MUTE", 0),
  155. ])
  156. result.append(self.render_line(row))
  157. if add_footnote:
  158. result.append("")
  159. result.append(f"[^1]: All mute rules are defined [here]({footnote_url}).")
  160. return result
  161. def render_pm(value, url, diff=None):
  162. if value:
  163. text = f"[{value}]({url})"
  164. else:
  165. text = str(value)
  166. if diff is not None and diff != 0:
  167. if diff == 0:
  168. sign = "±"
  169. elif diff < 0:
  170. sign = "-"
  171. else:
  172. sign = "+"
  173. text = f"{text} {sign}{abs(diff)}"
  174. return text
  175. def render_testlist_html(rows, fn, build_preset):
  176. TEMPLATES_PATH = os.path.join(os.path.dirname(__file__), "templates")
  177. env = Environment(loader=FileSystemLoader(TEMPLATES_PATH), undefined=StrictUndefined)
  178. status_test = {}
  179. last_n_runs = 5
  180. has_any_log = set()
  181. for t in rows:
  182. status_test.setdefault(t.status, []).append(t)
  183. if any(t.log_urls.values()):
  184. has_any_log.add(t.status)
  185. for status in status_test.keys():
  186. status_test[status].sort(key=attrgetter("full_name"))
  187. status_order = [TestStatus.ERROR, TestStatus.FAIL, TestStatus.SKIP, TestStatus.MUTE, TestStatus.PASS]
  188. # remove status group without tests
  189. status_order = [s for s in status_order if s in status_test]
  190. # get testowners
  191. all_tests = [test for status in status_order for test in status_test.get(status)]
  192. dir = os.path.dirname(__file__)
  193. git_root = f"{dir}/../../.."
  194. codeowners = f"{git_root}/.github/TESTOWNERS"
  195. get_codeowners_for_tests(codeowners, all_tests)
  196. # statuses for history
  197. status_for_history = [TestStatus.FAIL, TestStatus.MUTE]
  198. status_for_history = [s for s in status_for_history if s in status_test]
  199. tests_names_for_history = []
  200. history= {}
  201. tests_in_statuses = [test for status in status_for_history for test in status_test.get(status)]
  202. # get tests for history
  203. for test in tests_in_statuses:
  204. tests_names_for_history.append(test.full_name)
  205. try:
  206. history = get_test_history(tests_names_for_history, last_n_runs, build_preset)
  207. except Exception:
  208. print(traceback.format_exc())
  209. #geting count of passed tests in history for sorting
  210. for test in tests_in_statuses:
  211. if test.full_name in history:
  212. test.count_of_passed = len(
  213. [
  214. history[test.full_name][x]
  215. for x in history[test.full_name]
  216. if history[test.full_name][x]["status"] == "passed"
  217. ]
  218. )
  219. # sorting,
  220. # at first - show tests with passed resuts in history
  221. # at second - sorted by test name
  222. for current_status in status_for_history:
  223. status_test.get(current_status,[]).sort(key=lambda val: (-val.count_of_passed, val.full_name))
  224. content = env.get_template("summary.html").render(
  225. status_order=status_order,
  226. tests=status_test,
  227. has_any_log=has_any_log,
  228. history=history,
  229. )
  230. with open(fn, "w") as fp:
  231. fp.write(content)
  232. def write_summary(summary: TestSummary):
  233. summary_fn = os.environ.get("GITHUB_STEP_SUMMARY")
  234. if summary_fn:
  235. fp = open(summary_fn, "at")
  236. else:
  237. fp = sys.stdout
  238. for line in summary.render(add_footnote=True):
  239. fp.write(f"{line}\n")
  240. fp.write("\n")
  241. if summary_fn:
  242. fp.close()
  243. def get_codeowners_for_tests(codeowners_file_path, tests_data):
  244. with open(codeowners_file_path, 'r') as file:
  245. data = file.read()
  246. owners_odj = CodeOwners(data)
  247. tests_data_with_owners = []
  248. for test in tests_data:
  249. target_path = test.classname
  250. owners = owners_odj.of(target_path)
  251. test.owners = joined_owners = ";;".join(
  252. [(":".join(x)) for x in owners])
  253. tests_data_with_owners.append(test)
  254. def gen_summary(public_dir, public_dir_url, paths, is_retry: bool, build_preset):
  255. summary = TestSummary(is_retry=is_retry)
  256. for title, html_fn, path in paths:
  257. summary_line = TestSummaryLine(title)
  258. for fn, suite, case in iter_xml_files(path):
  259. test_result = TestResult.from_junit(case)
  260. summary_line.add(test_result)
  261. if os.path.isabs(html_fn):
  262. html_fn = os.path.relpath(html_fn, public_dir)
  263. report_url = f"{public_dir_url}/{html_fn}"
  264. render_testlist_html(summary_line.tests, os.path.join(public_dir, html_fn),build_preset)
  265. summary_line.add_report(html_fn, report_url)
  266. summary.add_line(summary_line)
  267. return summary
  268. def get_comment_text(summary: TestSummary, summary_links: str, is_last_retry: bool, is_test_result_ignored: bool)->tuple[str, list[str]]:
  269. color = "red"
  270. if summary.is_failed:
  271. if is_test_result_ignored:
  272. color = "yellow"
  273. result = f"Some tests failed, follow the links below. This fail is not in blocking policy yet"
  274. else:
  275. color = "red" if is_last_retry else "yellow"
  276. result = f"Some tests failed, follow the links below."
  277. if not is_last_retry:
  278. result += " Going to retry failed tests..."
  279. else:
  280. color = "green"
  281. result = f"Tests successful."
  282. body = []
  283. body.append(result)
  284. if not is_last_retry:
  285. body.append("")
  286. body.append("<details>")
  287. body.append("")
  288. with open(summary_links) as f:
  289. links = f.readlines()
  290. links.sort()
  291. links = [line.split(" ", 1)[1].strip() for line in links]
  292. if links:
  293. body.append("")
  294. body.append(" | ".join(links))
  295. body.extend(summary.render())
  296. if not is_last_retry:
  297. body.append("")
  298. body.append("</details>")
  299. body.append("")
  300. else:
  301. body.append("")
  302. return color, body
  303. def main():
  304. parser = argparse.ArgumentParser()
  305. parser.add_argument("--public_dir", required=True)
  306. parser.add_argument("--public_dir_url", required=True)
  307. parser.add_argument("--summary_links", required=True)
  308. parser.add_argument('--build_preset', default="default-linux-x86-64-relwithdebinfo", required=False)
  309. parser.add_argument('--status_report_file', required=False)
  310. parser.add_argument('--is_retry', required=True, type=int)
  311. parser.add_argument('--is_last_retry', required=True, type=int)
  312. parser.add_argument('--is_test_result_ignored', required=True, type=int)
  313. parser.add_argument('--comment_color_file', required=True)
  314. parser.add_argument('--comment_text_file', required=True)
  315. parser.add_argument("args", nargs="+", metavar="TITLE html_out path")
  316. args = parser.parse_args()
  317. if len(args.args) % 3 != 0:
  318. print("Invalid argument count")
  319. raise SystemExit(-1)
  320. paths = iter(args.args)
  321. title_path = list(zip(paths, paths, paths))
  322. summary = gen_summary(args.public_dir, args.public_dir_url, title_path, is_retry=bool(args.is_retry),build_preset=args.build_preset)
  323. write_summary(summary)
  324. if summary.is_failed and not args.is_test_result_ignored:
  325. overall_status = "failure"
  326. else:
  327. overall_status = "success"
  328. color, text = get_comment_text(summary, args.summary_links, is_last_retry=bool(args.is_last_retry), is_test_result_ignored=args.is_test_result_ignored)
  329. with open(args.comment_color_file, "w") as f:
  330. f.write(color)
  331. with open(args.comment_text_file, "w") as f:
  332. f.write('\n'.join(text))
  333. f.write('\n')
  334. with open(args.status_report_file, "w") as f:
  335. f.write(overall_status)
  336. if __name__ == "__main__":
  337. main()