mesontest.py 22 KB

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