mtest.py 23 KB

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