testrunner.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. # Class for actually running tests.
  2. #
  3. # Copyright (c) 2020-2021 Virtuozzo International GmbH
  4. #
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 2 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. #
  18. import os
  19. from pathlib import Path
  20. import datetime
  21. import time
  22. import difflib
  23. import subprocess
  24. import contextlib
  25. import json
  26. import shutil
  27. import sys
  28. from multiprocessing import Pool
  29. from typing import List, Optional, Any, Sequence, Dict, \
  30. ContextManager
  31. from testenv import TestEnv
  32. def silent_unlink(path: Path) -> None:
  33. try:
  34. path.unlink()
  35. except OSError:
  36. pass
  37. def file_diff(file1: str, file2: str) -> List[str]:
  38. with open(file1, encoding="utf-8") as f1, \
  39. open(file2, encoding="utf-8") as f2:
  40. # We want to ignore spaces at line ends. There are a lot of mess about
  41. # it in iotests.
  42. # TODO: fix all tests to not produce extra spaces, fix all .out files
  43. # and use strict diff here!
  44. seq1 = [line.rstrip() for line in f1]
  45. seq2 = [line.rstrip() for line in f2]
  46. res = [line.rstrip()
  47. for line in difflib.unified_diff(seq1, seq2, file1, file2)]
  48. return res
  49. class LastElapsedTime(ContextManager['LastElapsedTime']):
  50. """ Cache for elapsed time for tests, to show it during new test run
  51. It is safe to use get() at any time. To use update(), you must either
  52. use it inside with-block or use save() after update().
  53. """
  54. def __init__(self, cache_file: str, env: TestEnv) -> None:
  55. self.env = env
  56. self.cache_file = cache_file
  57. self.cache: Dict[str, Dict[str, Dict[str, float]]]
  58. try:
  59. with open(cache_file, encoding="utf-8") as f:
  60. self.cache = json.load(f)
  61. except (OSError, ValueError):
  62. self.cache = {}
  63. def get(self, test: str,
  64. default: Optional[float] = None) -> Optional[float]:
  65. if test not in self.cache:
  66. return default
  67. if self.env.imgproto not in self.cache[test]:
  68. return default
  69. return self.cache[test][self.env.imgproto].get(self.env.imgfmt,
  70. default)
  71. def update(self, test: str, elapsed: float) -> None:
  72. d = self.cache.setdefault(test, {})
  73. d.setdefault(self.env.imgproto, {})[self.env.imgfmt] = elapsed
  74. def save(self) -> None:
  75. with open(self.cache_file, 'w', encoding="utf-8") as f:
  76. json.dump(self.cache, f)
  77. def __enter__(self) -> 'LastElapsedTime':
  78. return self
  79. def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
  80. self.save()
  81. class TestResult:
  82. def __init__(self, status: str, description: str = '',
  83. elapsed: Optional[float] = None, diff: Sequence[str] = (),
  84. casenotrun: str = '', interrupted: bool = False) -> None:
  85. self.status = status
  86. self.description = description
  87. self.elapsed = elapsed
  88. self.diff = diff
  89. self.casenotrun = casenotrun
  90. self.interrupted = interrupted
  91. class TestRunner(ContextManager['TestRunner']):
  92. shared_self = None
  93. @staticmethod
  94. def proc_run_test(test: str, test_field_width: int) -> TestResult:
  95. # We are in a subprocess, we can't change the runner object!
  96. runner = TestRunner.shared_self
  97. assert runner is not None
  98. return runner.run_test(test, test_field_width, mp=True)
  99. def run_tests_pool(self, tests: List[str],
  100. test_field_width: int, jobs: int) -> List[TestResult]:
  101. # passing self directly to Pool.starmap() just doesn't work, because
  102. # it's a context manager.
  103. assert TestRunner.shared_self is None
  104. TestRunner.shared_self = self
  105. with Pool(jobs) as p:
  106. results = p.starmap(self.proc_run_test,
  107. zip(tests, [test_field_width] * len(tests)))
  108. TestRunner.shared_self = None
  109. return results
  110. def __init__(self, env: TestEnv, tap: bool = False,
  111. color: str = 'auto') -> None:
  112. self.env = env
  113. self.tap = tap
  114. self.last_elapsed = LastElapsedTime('.last-elapsed-cache', env)
  115. assert color in ('auto', 'on', 'off')
  116. self.color = (color == 'on') or (color == 'auto' and
  117. sys.stdout.isatty())
  118. self._stack: contextlib.ExitStack
  119. def __enter__(self) -> 'TestRunner':
  120. self._stack = contextlib.ExitStack()
  121. self._stack.enter_context(self.env)
  122. self._stack.enter_context(self.last_elapsed)
  123. return self
  124. def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
  125. self._stack.close()
  126. def test_print_one_line(self, test: str,
  127. test_field_width: int,
  128. starttime: str,
  129. endtime: Optional[str] = None, status: str = '...',
  130. lasttime: Optional[float] = None,
  131. thistime: Optional[float] = None,
  132. description: str = '',
  133. end: str = '\n') -> None:
  134. """ Print short test info before/after test run """
  135. test = os.path.basename(test)
  136. if test_field_width is None:
  137. test_field_width = 8
  138. if self.tap:
  139. if status == 'pass':
  140. print(f'ok {self.env.imgfmt} {test}')
  141. elif status == 'fail':
  142. print(f'not ok {self.env.imgfmt} {test}')
  143. elif status == 'not run':
  144. print(f'ok {self.env.imgfmt} {test} # SKIP')
  145. return
  146. if lasttime:
  147. lasttime_s = f' (last: {lasttime:.1f}s)'
  148. else:
  149. lasttime_s = ''
  150. if thistime:
  151. thistime_s = f'{thistime:.1f}s'
  152. else:
  153. thistime_s = '...'
  154. if endtime:
  155. endtime = f'[{endtime}]'
  156. else:
  157. endtime = ''
  158. if self.color:
  159. if status == 'pass':
  160. col = '\033[32m'
  161. elif status == 'fail':
  162. col = '\033[1m\033[31m'
  163. elif status == 'not run':
  164. col = '\033[33m'
  165. else:
  166. col = ''
  167. col_end = '\033[0m'
  168. else:
  169. col = ''
  170. col_end = ''
  171. print(f'{test:{test_field_width}} {col}{status:10}{col_end} '
  172. f'[{starttime}] {endtime:13}{thistime_s:5} {lasttime_s:14} '
  173. f'{description}', end=end)
  174. def find_reference(self, test: str) -> str:
  175. if self.env.cachemode == 'none':
  176. ref = f'{test}.out.nocache'
  177. if os.path.isfile(ref):
  178. return ref
  179. ref = f'{test}.out.{self.env.imgfmt}'
  180. if os.path.isfile(ref):
  181. return ref
  182. ref = f'{test}.{self.env.qemu_default_machine}.out'
  183. if os.path.isfile(ref):
  184. return ref
  185. return f'{test}.out'
  186. def do_run_test(self, test: str) -> TestResult:
  187. """
  188. Run one test
  189. :param test: test file path
  190. Note: this method may be called from subprocess, so it does not
  191. change ``self`` object in any way!
  192. """
  193. f_test = Path(test)
  194. f_reference = Path(self.find_reference(test))
  195. if not f_test.exists():
  196. return TestResult(status='fail',
  197. description=f'No such test file: {f_test}')
  198. if not os.access(str(f_test), os.X_OK):
  199. sys.exit(f'Not executable: {f_test}')
  200. if not f_reference.exists():
  201. return TestResult(status='not run',
  202. description='No qualified output '
  203. f'(expected {f_reference})')
  204. args = [str(f_test.resolve())]
  205. env = self.env.prepare_subprocess(args)
  206. # Split test directories, so that tests running in parallel don't
  207. # break each other.
  208. for d in ['TEST_DIR', 'SOCK_DIR']:
  209. env[d] = os.path.join(
  210. env[d],
  211. f"{self.env.imgfmt}-{self.env.imgproto}-{f_test.name}")
  212. Path(env[d]).mkdir(parents=True, exist_ok=True)
  213. test_dir = env['TEST_DIR']
  214. f_bad = Path(test_dir, f_test.name + '.out.bad')
  215. f_notrun = Path(test_dir, f_test.name + '.notrun')
  216. f_casenotrun = Path(test_dir, f_test.name + '.casenotrun')
  217. for p in (f_notrun, f_casenotrun):
  218. silent_unlink(p)
  219. t0 = time.time()
  220. with f_bad.open('w', encoding="utf-8") as f:
  221. with subprocess.Popen(args, cwd=str(f_test.parent), env=env,
  222. stdin=subprocess.DEVNULL,
  223. stdout=f, stderr=subprocess.STDOUT) as proc:
  224. try:
  225. proc.wait()
  226. except KeyboardInterrupt:
  227. proc.terminate()
  228. proc.wait()
  229. return TestResult(status='not run',
  230. description='Interrupted by user',
  231. interrupted=True)
  232. ret = proc.returncode
  233. elapsed = round(time.time() - t0, 1)
  234. if ret != 0:
  235. return TestResult(status='fail', elapsed=elapsed,
  236. description=f'failed, exit status {ret}',
  237. diff=file_diff(str(f_reference), str(f_bad)))
  238. if f_notrun.exists():
  239. return TestResult(
  240. status='not run',
  241. description=f_notrun.read_text(encoding='utf-8').strip())
  242. casenotrun = ''
  243. if f_casenotrun.exists():
  244. casenotrun = f_casenotrun.read_text(encoding='utf-8')
  245. diff = file_diff(str(f_reference), str(f_bad))
  246. if diff:
  247. if os.environ.get("QEMU_IOTESTS_REGEN", None) is not None:
  248. shutil.copyfile(str(f_bad), str(f_reference))
  249. print("########################################")
  250. print("##### REFERENCE FILE UPDATED #####")
  251. print("########################################")
  252. return TestResult(status='fail', elapsed=elapsed,
  253. description=f'output mismatch (see {f_bad})',
  254. diff=diff, casenotrun=casenotrun)
  255. else:
  256. f_bad.unlink()
  257. return TestResult(status='pass', elapsed=elapsed,
  258. casenotrun=casenotrun)
  259. def run_test(self, test: str,
  260. test_field_width: int,
  261. mp: bool = False) -> TestResult:
  262. """
  263. Run one test and print short status
  264. :param test: test file path
  265. :param test_field_width: width for first field of status format
  266. :param mp: if true, we are in a multiprocessing environment, don't try
  267. to rewrite things in stdout
  268. Note: this method may be called from subprocess, so it does not
  269. change ``self`` object in any way!
  270. """
  271. last_el = self.last_elapsed.get(test)
  272. start = datetime.datetime.now().strftime('%H:%M:%S')
  273. if not self.tap:
  274. self.test_print_one_line(test=test,
  275. test_field_width=test_field_width,
  276. status = 'started' if mp else '...',
  277. starttime=start,
  278. lasttime=last_el,
  279. end = '\n' if mp else '\r')
  280. else:
  281. testname = os.path.basename(test)
  282. print(f'# running {self.env.imgfmt} {testname}')
  283. res = self.do_run_test(test)
  284. end = datetime.datetime.now().strftime('%H:%M:%S')
  285. self.test_print_one_line(test=test,
  286. test_field_width=test_field_width,
  287. status=res.status,
  288. starttime=start, endtime=end,
  289. lasttime=last_el, thistime=res.elapsed,
  290. description=res.description)
  291. if res.casenotrun:
  292. if self.tap:
  293. print('#' + res.casenotrun.replace('\n', '\n#'))
  294. else:
  295. print(res.casenotrun)
  296. sys.stdout.flush()
  297. return res
  298. def run_tests(self, tests: List[str], jobs: int = 1) -> bool:
  299. n_run = 0
  300. failed = []
  301. notrun = []
  302. casenotrun = []
  303. if self.tap:
  304. print('TAP version 13')
  305. self.env.print_env('# ')
  306. print('1..%d' % len(tests))
  307. else:
  308. self.env.print_env()
  309. test_field_width = max(len(os.path.basename(t)) for t in tests) + 2
  310. if jobs > 1:
  311. results = self.run_tests_pool(tests, test_field_width, jobs)
  312. for i, t in enumerate(tests):
  313. name = os.path.basename(t)
  314. if jobs > 1:
  315. res = results[i]
  316. else:
  317. res = self.run_test(t, test_field_width)
  318. assert res.status in ('pass', 'fail', 'not run')
  319. if res.casenotrun:
  320. casenotrun.append(t)
  321. if res.status != 'not run':
  322. n_run += 1
  323. if res.status == 'fail':
  324. failed.append(name)
  325. if res.diff:
  326. if self.tap:
  327. print('\n'.join(res.diff), file=sys.stderr)
  328. else:
  329. print('\n'.join(res.diff))
  330. elif res.status == 'not run':
  331. notrun.append(name)
  332. elif res.status == 'pass':
  333. assert res.elapsed is not None
  334. self.last_elapsed.update(t, res.elapsed)
  335. sys.stdout.flush()
  336. if res.interrupted:
  337. break
  338. if not self.tap:
  339. if notrun:
  340. print('Not run:', ' '.join(notrun))
  341. if casenotrun:
  342. print('Some cases not run in:', ' '.join(casenotrun))
  343. if failed:
  344. print('Failures:', ' '.join(failed))
  345. print(f'Failed {len(failed)} of {n_run} iotests')
  346. else:
  347. print(f'Passed all {n_run} iotests')
  348. return not failed