mesontest.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. #!/usr/bin/env python3
  2. # Copyright 2016 The Meson development team
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. # A tool to run tests in many different ways.
  13. import shlex
  14. import subprocess, sys, os, argparse
  15. import pickle
  16. from mesonbuild import build
  17. from mesonbuild import environment
  18. import time, datetime, multiprocessing, json
  19. import concurrent.futures as conc
  20. import platform
  21. import signal
  22. import random
  23. # GNU autotools interprets a return code of 77 from tests it executes to
  24. # mean that the test should be skipped.
  25. GNU_SKIP_RETURNCODE = 77
  26. def is_windows():
  27. platname = platform.system().lower()
  28. return platname == 'windows' or 'mingw' in platname
  29. def determine_worker_count():
  30. varname = 'MESON_TESTTHREADS'
  31. if varname in os.environ:
  32. try:
  33. num_workers = int(os.environ[varname])
  34. except ValueError:
  35. print('Invalid value in %s, using 1 thread.' % varname)
  36. num_workers = 1
  37. else:
  38. try:
  39. # Fails in some weird environments such as Debian
  40. # reproducible build.
  41. num_workers = multiprocessing.cpu_count()
  42. except Exception:
  43. num_workers = 1
  44. return num_workers
  45. parser = argparse.ArgumentParser()
  46. parser.add_argument('--repeat', default=1, dest='repeat', type=int,
  47. help='Number of times to run the tests.')
  48. parser.add_argument('--no-rebuild', default=False, action='store_true',
  49. help='Do not rebuild before running tests.')
  50. parser.add_argument('--gdb', default=False, dest='gdb', action='store_true',
  51. help='Run test under gdb.')
  52. parser.add_argument('--list', default=False, dest='list', action='store_true',
  53. help='List available tests.')
  54. parser.add_argument('--wrapper', default=None, dest='wrapper', type=shlex.split,
  55. help='wrapper to run tests with (e.g. Valgrind)')
  56. parser.add_argument('-C', default='.', dest='wd',
  57. help='directory to cd into before running')
  58. parser.add_argument('--suite', default=[], dest='include_suites', action='append', metavar='SUITE',
  59. help='Only run tests belonging to the given suite.')
  60. parser.add_argument('--no-suite', default=[], dest='exclude_suites', action='append', metavar='SUITE',
  61. help='Do not run tests belonging to the given suite.')
  62. parser.add_argument('--no-stdsplit', default=True, dest='split', action='store_false',
  63. help='Do not split stderr and stdout in test logs.')
  64. parser.add_argument('--print-errorlogs', default=False, action='store_true',
  65. help="Whether to print failing tests' logs.")
  66. parser.add_argument('--benchmark', default=False, action='store_true',
  67. help="Run benchmarks instead of tests.")
  68. parser.add_argument('--logbase', default='testlog',
  69. help="Base name for log file.")
  70. parser.add_argument('--num-processes', default=determine_worker_count(), type=int,
  71. help='How many parallel processes to use.')
  72. parser.add_argument('-v', '--verbose', default=False, action='store_true',
  73. help='Do not redirect stdout and stderr')
  74. parser.add_argument('-q', '--quiet', default=False, action='store_true',
  75. help='Produce less output to the terminal.')
  76. parser.add_argument('-t', '--timeout-multiplier', type=float, default=None,
  77. help='Define a multiplier for test timeout, for example '
  78. ' when running tests in particular conditions they might take'
  79. ' more time to execute.')
  80. parser.add_argument('--setup', default=None, dest='setup',
  81. help='Which test setup to use.')
  82. parser.add_argument('--test-args', default=[], type=shlex.split,
  83. help='Arguments to pass to the specified test(s) or all tests')
  84. parser.add_argument('args', nargs='*',
  85. help='Optional list of tests to run')
  86. class TestRun:
  87. def __init__(self, res, returncode, should_fail, duration, stdo, stde, cmd,
  88. env):
  89. self.res = res
  90. self.returncode = returncode
  91. self.duration = duration
  92. self.stdo = stdo
  93. self.stde = stde
  94. self.cmd = cmd
  95. self.env = env
  96. self.should_fail = should_fail
  97. def get_log(self):
  98. res = '--- command ---\n'
  99. if self.cmd is None:
  100. res += 'NONE\n'
  101. else:
  102. res += "%s%s\n" % (''.join(["%s='%s' " % (k, v) for k, v in self.env.items()]), ' ' .join(self.cmd))
  103. if self.stdo:
  104. res += '--- stdout ---\n'
  105. res += self.stdo
  106. if self.stde:
  107. if res[-1:] != '\n':
  108. res += '\n'
  109. res += '--- stderr ---\n'
  110. res += self.stde
  111. if res[-1:] != '\n':
  112. res += '\n'
  113. res += '-------\n\n'
  114. return res
  115. def decode(stream):
  116. if stream is None:
  117. return ''
  118. try:
  119. return stream.decode('utf-8')
  120. except UnicodeDecodeError:
  121. return stream.decode('iso-8859-1', errors='ignore')
  122. def write_json_log(jsonlogfile, test_name, result):
  123. jresult = {'name': test_name,
  124. 'stdout': result.stdo,
  125. 'result': result.res,
  126. 'duration': result.duration,
  127. 'returncode': result.returncode,
  128. 'command': result.cmd}
  129. if isinstance(result.env, dict):
  130. jresult['env'] = result.env
  131. else:
  132. jresult['env'] = result.env.get_env(os.environ)
  133. if result.stde:
  134. jresult['stderr'] = result.stde
  135. jsonlogfile.write(json.dumps(jresult) + '\n')
  136. def run_with_mono(fname):
  137. if fname.endswith('.exe') and not is_windows():
  138. return True
  139. return False
  140. class TestHarness:
  141. def __init__(self, options):
  142. self.options = options
  143. self.collected_logs = []
  144. self.fail_count = 0
  145. self.success_count = 0
  146. self.skip_count = 0
  147. self.timeout_count = 0
  148. self.is_run = False
  149. self.tests = None
  150. self.suites = None
  151. if self.options.benchmark:
  152. self.load_datafile(os.path.join(options.wd, 'meson-private', 'meson_benchmark_setup.dat'))
  153. else:
  154. self.load_datafile(os.path.join(options.wd, 'meson-private', 'meson_test_setup.dat'))
  155. def run_single_test(self, wrap, test):
  156. if test.fname[0].endswith('.jar'):
  157. cmd = ['java', '-jar'] + test.fname
  158. elif not test.is_cross and run_with_mono(test.fname[0]):
  159. cmd = ['mono'] + test.fname
  160. else:
  161. if test.is_cross:
  162. if test.exe_runner is None:
  163. # Can not run test on cross compiled executable
  164. # because there is no execute wrapper.
  165. cmd = None
  166. else:
  167. cmd = [test.exe_runner] + test.fname
  168. else:
  169. cmd = test.fname
  170. if cmd is None:
  171. res = 'SKIP'
  172. duration = 0.0
  173. stdo = 'Not run because can not execute cross compiled binaries.'
  174. stde = None
  175. returncode = GNU_SKIP_RETURNCODE
  176. else:
  177. cmd = wrap + cmd + test.cmd_args + self.options.test_args
  178. starttime = time.time()
  179. child_env = os.environ.copy()
  180. child_env.update(self.options.global_env.get_env(child_env))
  181. if isinstance(test.env, build.EnvironmentVariables):
  182. test.env = test.env.get_env(child_env)
  183. child_env.update(test.env)
  184. if len(test.extra_paths) > 0:
  185. child_env['PATH'] += ';'.join([''] + test.extra_paths)
  186. # If MALLOC_PERTURB_ is not set, or if it is set to an empty value,
  187. # (i.e., the test or the environment don't explicitly set it), set
  188. # it ourselves. We do this unconditionally because it is extremely
  189. # useful to have in tests.
  190. # Setting MALLOC_PERTURB_="0" will completely disable this feature.
  191. if 'MALLOC_PERTURB_' not in child_env or not child_env['MALLOC_PERTURB_']:
  192. child_env['MALLOC_PERTURB_'] = str(random.randint(1, 255))
  193. setsid = None
  194. stdout = None
  195. stderr = None
  196. if not self.options.verbose:
  197. stdout = subprocess.PIPE
  198. stderr = subprocess.PIPE if self.options and self.options.split else subprocess.STDOUT
  199. if not is_windows():
  200. setsid = os.setsid
  201. p = subprocess.Popen(cmd,
  202. stdout=stdout,
  203. stderr=stderr,
  204. env=child_env,
  205. cwd=test.workdir,
  206. preexec_fn=setsid)
  207. timed_out = False
  208. if test.timeout is None:
  209. timeout = None
  210. else:
  211. timeout = test.timeout * self.options.timeout_multiplier
  212. try:
  213. (stdo, stde) = p.communicate(timeout=timeout)
  214. except subprocess.TimeoutExpired:
  215. if self.options.verbose:
  216. print("%s time out (After %d seconds)" % (test.name, timeout))
  217. timed_out = True
  218. # Python does not provide multiplatform support for
  219. # killing a process and all its children so we need
  220. # to roll our own.
  221. if is_windows():
  222. subprocess.call(['taskkill', '/F', '/T', '/PID', str(p.pid)])
  223. else:
  224. os.killpg(os.getpgid(p.pid), signal.SIGKILL)
  225. (stdo, stde) = p.communicate()
  226. endtime = time.time()
  227. duration = endtime - starttime
  228. stdo = decode(stdo)
  229. if stde:
  230. stde = decode(stde)
  231. if timed_out:
  232. res = 'TIMEOUT'
  233. self.timeout_count += 1
  234. self.fail_count += 1
  235. elif p.returncode == GNU_SKIP_RETURNCODE:
  236. res = 'SKIP'
  237. self.skip_count += 1
  238. elif test.should_fail == bool(p.returncode):
  239. res = 'OK'
  240. self.success_count += 1
  241. else:
  242. res = 'FAIL'
  243. self.fail_count += 1
  244. returncode = p.returncode
  245. result = TestRun(res, returncode, test.should_fail, duration, stdo, stde, cmd, test.env)
  246. return result
  247. def print_stats(self, numlen, tests, name, result, i, logfile, jsonlogfile):
  248. startpad = ' ' * (numlen - len('%d' % (i + 1)))
  249. num = '%s%d/%d' % (startpad, i + 1, len(tests))
  250. padding1 = ' ' * (38 - len(name))
  251. padding2 = ' ' * (8 - len(result.res))
  252. result_str = '%s %s %s%s%s%5.2f s' % \
  253. (num, name, padding1, result.res, padding2, result.duration)
  254. if not self.options.quiet or result.res != 'OK':
  255. print(result_str)
  256. result_str += "\n\n" + result.get_log()
  257. if (result.returncode != GNU_SKIP_RETURNCODE) \
  258. and (result.returncode != 0) != result.should_fail:
  259. if self.options.print_errorlogs:
  260. self.collected_logs.append(result_str)
  261. if logfile:
  262. logfile.write(result_str)
  263. if jsonlogfile:
  264. write_json_log(jsonlogfile, name, result)
  265. def print_summary(self, logfile, jsonlogfile):
  266. msg = '''
  267. OK: %4d
  268. FAIL: %4d
  269. SKIP: %4d
  270. TIMEOUT: %4d
  271. ''' % (self.success_count, self.fail_count, self.skip_count, self.timeout_count)
  272. print(msg)
  273. if logfile:
  274. logfile.write(msg)
  275. def print_collected_logs(self):
  276. if len(self.collected_logs) > 0:
  277. if len(self.collected_logs) > 10:
  278. print('\nThe output from 10 first failed tests:\n')
  279. else:
  280. print('\nThe output from the failed tests:\n')
  281. for log in self.collected_logs[:10]:
  282. lines = log.splitlines()
  283. if len(lines) > 104:
  284. print('\n'.join(lines[0:4]))
  285. print('--- Listing only the last 100 lines from a long log. ---')
  286. lines = lines[-100:]
  287. for line in lines:
  288. print(line)
  289. def doit(self):
  290. if self.is_run:
  291. raise RuntimeError('Test harness object can only be used once.')
  292. if not os.path.isfile(self.datafile):
  293. print('Test data file. Probably this means that you did not run this in the build directory.')
  294. return 1
  295. self.is_run = True
  296. tests = self.get_tests()
  297. if not tests:
  298. return 0
  299. self.run_tests(tests)
  300. return self.fail_count
  301. @staticmethod
  302. def split_suite_string(suite):
  303. if ':' in suite:
  304. return suite.split(':', 1)
  305. else:
  306. return suite, ""
  307. @staticmethod
  308. def test_in_suites(test, suites):
  309. for suite in suites:
  310. (prj_match, st_match) = TestHarness.split_suite_string(suite)
  311. for prjst in test.suite:
  312. (prj, st) = TestHarness.split_suite_string(prjst)
  313. if prj_match and prj != prj_match:
  314. continue
  315. if st_match and st != st_match:
  316. continue
  317. return True
  318. return False
  319. def test_suitable(self, test):
  320. return (len(self.options.include_suites) == 0 or TestHarness.test_in_suites(test, self.options.include_suites)) \
  321. and not TestHarness.test_in_suites(test, self.options.exclude_suites)
  322. def load_suites(self):
  323. ss = set()
  324. for t in self.tests:
  325. for s in t.suite:
  326. ss.add(s)
  327. self.suites = list(ss)
  328. def load_tests(self):
  329. with open(self.datafile, 'rb') as f:
  330. self.tests = pickle.load(f)
  331. def load_datafile(self, datafile):
  332. self.datafile = datafile
  333. self.load_tests()
  334. self.load_suites()
  335. def get_tests(self):
  336. if not self.tests:
  337. print('No tests defined.')
  338. return []
  339. if len(self.options.include_suites) or len(self.options.exclude_suites):
  340. tests = []
  341. for tst in self.tests:
  342. if self.test_suitable(tst):
  343. tests.append(tst)
  344. else:
  345. tests = self.tests
  346. if self.options.args:
  347. tests = [t for t in tests if t.name in self.options.args]
  348. if not tests:
  349. print('No suitable tests defined.')
  350. return []
  351. for test in tests:
  352. test.rebuilt = False
  353. return tests
  354. def open_log_files(self):
  355. if not self.options.logbase or self.options.verbose:
  356. return None, None, None, None
  357. namebase = None
  358. logfile_base = os.path.join(self.options.wd, 'meson-logs', self.options.logbase)
  359. if self.options.wrapper:
  360. namebase = os.path.split(self.get_wrapper()[0])[1]
  361. elif self.options.setup:
  362. namebase = self.options.setup
  363. if namebase:
  364. logfile_base += '-' + namebase.replace(' ', '_')
  365. logfilename = logfile_base + '.txt'
  366. jsonlogfilename = logfile_base + '.json'
  367. jsonlogfile = open(jsonlogfilename, 'w')
  368. logfile = open(logfilename, 'w')
  369. logfile.write('Log of Meson test suite run on %s\n\n'
  370. % datetime.datetime.now().isoformat())
  371. return logfile, logfilename, jsonlogfile, jsonlogfilename
  372. def get_wrapper(self):
  373. wrap = []
  374. if self.options.gdb:
  375. wrap = ['gdb', '--quiet', '--nh']
  376. if self.options.repeat > 1:
  377. wrap += ['-ex', 'run', '-ex', 'quit']
  378. # Signal the end of arguments to gdb
  379. wrap += ['--args']
  380. if self.options.wrapper:
  381. wrap += self.options.wrapper
  382. assert(isinstance(wrap, list))
  383. return wrap
  384. def get_pretty_suite(self, test, tests):
  385. if len(self.suites) > 1:
  386. rv = TestHarness.split_suite_string(test.suite[0])[0]
  387. s = "+".join(TestHarness.split_suite_string(s)[1] for s in test.suite)
  388. if len(s):
  389. rv += ":"
  390. return rv + s + " / " + test.name
  391. else:
  392. return test.name
  393. def run_tests(self, tests):
  394. try:
  395. executor = None
  396. logfile = None
  397. jsonlogfile = None
  398. futures = []
  399. numlen = len('%d' % len(tests))
  400. (logfile, logfilename, jsonlogfile, jsonlogfilename) = self.open_log_files()
  401. wrap = self.get_wrapper()
  402. for i in range(self.options.repeat):
  403. for i, test in enumerate(tests):
  404. visible_name = self.get_pretty_suite(test, tests)
  405. if self.options.gdb:
  406. test.timeout = None
  407. if not test.is_parallel or self.options.gdb:
  408. self.drain_futures(futures, logfile, jsonlogfile)
  409. futures = []
  410. res = self.run_single_test(wrap, test)
  411. self.print_stats(numlen, tests, visible_name, res, i, logfile, jsonlogfile)
  412. else:
  413. if not executor:
  414. executor = conc.ThreadPoolExecutor(max_workers=self.options.num_processes)
  415. f = executor.submit(self.run_single_test, wrap, test)
  416. futures.append((f, numlen, tests, visible_name, i, logfile, jsonlogfile))
  417. if self.options.repeat > 1 and self.fail_count:
  418. break
  419. if self.options.repeat > 1 and self.fail_count:
  420. break
  421. self.drain_futures(futures, logfile, jsonlogfile)
  422. self.print_summary(logfile, jsonlogfile)
  423. self.print_collected_logs()
  424. if logfilename:
  425. print('Full log written to %s' % logfilename)
  426. finally:
  427. if jsonlogfile:
  428. jsonlogfile.close()
  429. if logfile:
  430. logfile.close()
  431. def drain_futures(self, futures, logfile, jsonlogfile):
  432. for i in futures:
  433. (result, numlen, tests, name, i, logfile, jsonlogfile) = i
  434. if self.options.repeat > 1 and self.fail_count:
  435. result.cancel()
  436. if self.options.verbose:
  437. result.result()
  438. self.print_stats(numlen, tests, name, result.result(), i, logfile, jsonlogfile)
  439. def run_special(self):
  440. 'Tests run by the user, usually something like "under gdb 1000 times".'
  441. if self.is_run:
  442. raise RuntimeError('Can not use run_special after a full run.')
  443. if os.path.isfile('build.ninja'):
  444. subprocess.check_call([environment.detect_ninja(), 'all'])
  445. tests = self.get_tests()
  446. if not tests:
  447. return 0
  448. self.run_tests(tests)
  449. return self.fail_count
  450. def list_tests(th):
  451. tests = th.get_tests()
  452. for t in tests:
  453. print(th.get_pretty_suite(t, tests))
  454. def merge_suite_options(options):
  455. buildfile = os.path.join(options.wd, 'meson-private/build.dat')
  456. with open(buildfile, 'rb') as f:
  457. build = pickle.load(f)
  458. setups = build.test_setups
  459. if options.setup not in setups:
  460. sys.exit('Unknown test setup: %s' % options.setup)
  461. current = setups[options.setup]
  462. if not options.gdb:
  463. options.gdb = current.gdb
  464. if options.timeout_multiplier is None:
  465. options.timeout_multiplier = current.timeout_multiplier
  466. # if options.env is None:
  467. # options.env = current.env # FIXME, should probably merge options here.
  468. if options.wrapper is not None and current.exe_wrapper is not None:
  469. sys.exit('Conflict: both test setup and command line specify an exe wrapper.')
  470. if options.wrapper is None:
  471. options.wrapper = current.exe_wrapper
  472. return current.env
  473. def rebuild_all(wd):
  474. if not os.path.isfile(os.path.join(wd, 'build.ninja')):
  475. print("Only ninja backend is supported to rebuild tests before running them.")
  476. return True
  477. ninja = environment.detect_ninja()
  478. if not ninja:
  479. print("Can't find ninja, can't rebuild test.")
  480. return False
  481. p = subprocess.Popen([ninja, '-C', wd])
  482. (stdo, stde) = p.communicate()
  483. if p.returncode != 0:
  484. print("Could not rebuild")
  485. return False
  486. return True
  487. def run(args):
  488. options = parser.parse_args(args)
  489. if options.benchmark:
  490. options.num_processes = 1
  491. if options.setup is not None:
  492. global_env = merge_suite_options(options)
  493. else:
  494. global_env = build.EnvironmentVariables()
  495. if options.timeout_multiplier is None:
  496. options.timeout_multiplier = 1
  497. setattr(options, 'global_env', global_env)
  498. if options.verbose and options.quiet:
  499. print('Can not be both quiet and verbose at the same time.')
  500. return 1
  501. if options.gdb:
  502. options.verbose = True
  503. if options.wrapper:
  504. print('Must not specify both a wrapper and gdb at the same time.')
  505. return 1
  506. options.wd = os.path.abspath(options.wd)
  507. if not options.no_rebuild:
  508. if not rebuild_all(options.wd):
  509. sys.exit(-1)
  510. th = TestHarness(options)
  511. if options.list:
  512. list_tests(th)
  513. return 0
  514. if len(options.args) == 0:
  515. return th.doit()
  516. return th.run_special()
  517. if __name__ == '__main__':
  518. sys.exit(run(sys.argv[1:]))