run_project_tests.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  1. #!/usr/bin/env python3
  2. # Copyright 2012-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. from glob import glob
  13. import itertools
  14. import os, subprocess, shutil, sys, signal
  15. from io import StringIO
  16. from ast import literal_eval
  17. from enum import Enum
  18. import tempfile
  19. from mesonbuild import mtest
  20. from mesonbuild import environment
  21. from mesonbuild import mesonlib
  22. from mesonbuild import mlog
  23. from mesonbuild.mesonlib import stringlistify, Popen_safe
  24. from mesonbuild.coredata import backendlist
  25. import argparse
  26. import xml.etree.ElementTree as ET
  27. import time
  28. import multiprocessing
  29. import concurrent.futures as conc
  30. import re
  31. from run_unittests import get_fake_options, run_configure
  32. from run_tests import get_backend_commands, get_backend_args_for_dir, Backend
  33. from run_tests import ensure_backend_detects_changes
  34. class BuildStep(Enum):
  35. configure = 1
  36. build = 2
  37. test = 3
  38. install = 4
  39. clean = 5
  40. validate = 6
  41. class TestResult:
  42. def __init__(self, msg, step, stdo, stde, mlog, conftime=0, buildtime=0, testtime=0):
  43. self.msg = msg
  44. self.step = step
  45. self.stdo = stdo
  46. self.stde = stde
  47. self.mlog = mlog
  48. self.conftime = conftime
  49. self.buildtime = buildtime
  50. self.testtime = testtime
  51. class DummyFuture(conc.Future):
  52. '''
  53. Dummy Future implementation that executes the provided function when you
  54. ask for the result. Used on platforms where sem_open() is not available:
  55. MSYS2, OpenBSD, etc: https://bugs.python.org/issue3770
  56. '''
  57. def set_function(self, fn, *args, **kwargs):
  58. self.fn = fn
  59. self.fn_args = args
  60. self.fn_kwargs = kwargs
  61. def result(self, **kwargs):
  62. try:
  63. result = self.fn(*self.fn_args, **self.fn_kwargs)
  64. except BaseException as e:
  65. self.set_exception(e)
  66. else:
  67. self.set_result(result)
  68. return super().result(**kwargs)
  69. class DummyExecutor(conc.Executor):
  70. '''
  71. Dummy single-thread 'concurrent' executor for use on platforms where
  72. sem_open is not available: https://bugs.python.org/issue3770
  73. '''
  74. def __init__(self):
  75. from threading import Lock
  76. self._shutdown = False
  77. self._shutdownLock = Lock()
  78. def submit(self, fn, *args, **kwargs):
  79. with self._shutdownLock:
  80. if self._shutdown:
  81. raise RuntimeError('Cannot schedule new futures after shutdown')
  82. f = DummyFuture()
  83. f.set_function(fn, *args, **kwargs)
  84. return f
  85. def shutdown(self, wait=True):
  86. with self._shutdownLock:
  87. self._shutdown = True
  88. class AutoDeletedDir:
  89. def __init__(self, d):
  90. self.dir = d
  91. def __enter__(self):
  92. os.makedirs(self.dir, exist_ok=True)
  93. return self.dir
  94. def __exit__(self, _type, value, traceback):
  95. # We don't use tempfile.TemporaryDirectory, but wrap the
  96. # deletion in the AutoDeletedDir class because
  97. # it fails on Windows due antivirus programs
  98. # holding files open.
  99. mesonlib.windows_proof_rmtree(self.dir)
  100. failing_logs = []
  101. print_debug = 'MESON_PRINT_TEST_OUTPUT' in os.environ
  102. do_debug = not {'MESON_PRINT_TEST_OUTPUT', 'TRAVIS', 'APPVEYOR'}.isdisjoint(os.environ)
  103. no_meson_log_msg = 'No meson-log.txt found.'
  104. system_compiler = None
  105. meson_command = os.path.join(os.getcwd(), 'meson')
  106. if not os.path.exists(meson_command):
  107. meson_command += '.py'
  108. if not os.path.exists(meson_command):
  109. raise RuntimeError('Could not find main Meson script to run.')
  110. class StopException(Exception):
  111. def __init__(self):
  112. super().__init__('Stopped by user')
  113. stop = False
  114. def stop_handler(signal, frame):
  115. global stop
  116. stop = True
  117. signal.signal(signal.SIGINT, stop_handler)
  118. signal.signal(signal.SIGTERM, stop_handler)
  119. def setup_commands(optbackend):
  120. global do_debug, backend, backend_flags
  121. global compile_commands, clean_commands, test_commands, install_commands, uninstall_commands
  122. backend = optbackend
  123. msbuild_exe = shutil.which('msbuild')
  124. # Auto-detect backend if unspecified
  125. if backend is None:
  126. if msbuild_exe is not None:
  127. backend = 'vs' # Meson will auto-detect VS version to use
  128. elif mesonlib.is_osx():
  129. backend = 'xcode'
  130. else:
  131. backend = 'ninja'
  132. # Set backend arguments for Meson
  133. if backend.startswith('vs'):
  134. backend_flags = ['--backend=' + backend]
  135. backend = Backend.vs
  136. elif backend == 'xcode':
  137. backend_flags = ['--backend=xcode']
  138. backend = Backend.xcode
  139. elif backend == 'ninja':
  140. backend_flags = ['--backend=ninja']
  141. backend = Backend.ninja
  142. else:
  143. raise RuntimeError('Unknown backend: {!r}'.format(backend))
  144. compile_commands, clean_commands, test_commands, install_commands, \
  145. uninstall_commands = get_backend_commands(backend, do_debug)
  146. def get_relative_files_list_from_dir(fromdir):
  147. paths = []
  148. for (root, _, files) in os.walk(fromdir):
  149. reldir = os.path.relpath(root, start=fromdir)
  150. for f in files:
  151. path = os.path.join(reldir, f).replace('\\', '/')
  152. if path.startswith('./'):
  153. path = path[2:]
  154. paths.append(path)
  155. return paths
  156. def platform_fix_name(fname, compiler):
  157. if '?lib' in fname:
  158. if mesonlib.is_cygwin():
  159. fname = re.sub(r'\?lib(.*)\.dll$', r'cyg\1.dll', fname)
  160. else:
  161. fname = re.sub(r'\?lib', 'lib', fname)
  162. if fname.endswith('?exe'):
  163. fname = fname[:-4]
  164. if mesonlib.is_windows() or mesonlib.is_cygwin():
  165. return fname + '.exe'
  166. if fname.startswith('?msvc:'):
  167. fname = fname[6:]
  168. if compiler != 'cl':
  169. return None
  170. if fname.startswith('?gcc:'):
  171. fname = fname[5:]
  172. if compiler == 'cl':
  173. return None
  174. return fname
  175. def validate_install(srcdir, installdir, compiler):
  176. # List of installed files
  177. info_file = os.path.join(srcdir, 'installed_files.txt')
  178. # If this exists, the test does not install any other files
  179. noinst_file = 'usr/no-installed-files'
  180. expected = {}
  181. ret_msg = ''
  182. # Generate list of expected files
  183. if os.path.exists(os.path.join(installdir, noinst_file)):
  184. expected[noinst_file] = False
  185. elif os.path.exists(info_file):
  186. with open(info_file) as f:
  187. for line in f:
  188. line = platform_fix_name(line.strip(), compiler)
  189. if line:
  190. expected[line] = False
  191. # Check if expected files were found
  192. for fname in expected:
  193. file_path = os.path.join(installdir, fname)
  194. if os.path.exists(file_path) or os.path.islink(file_path):
  195. expected[fname] = True
  196. for (fname, found) in expected.items():
  197. if not found:
  198. # Ignore missing PDB files if we aren't using cl
  199. if fname.endswith('.pdb') and compiler != 'cl':
  200. continue
  201. ret_msg += 'Expected file {0} missing.\n'.format(fname)
  202. # Check if there are any unexpected files
  203. found = get_relative_files_list_from_dir(installdir)
  204. for fname in found:
  205. # Windows-specific tests check for the existence of installed PDB
  206. # files, but common tests do not, for obvious reasons. Ignore any
  207. # extra PDB files found.
  208. if fname not in expected and not fname.endswith('.pdb') and compiler == 'cl':
  209. ret_msg += 'Extra file {0} found.\n'.format(fname)
  210. return ret_msg
  211. def log_text_file(logfile, testdir, stdo, stde):
  212. global stop, executor, futures
  213. logfile.write('%s\nstdout\n\n---\n' % testdir)
  214. logfile.write(stdo)
  215. logfile.write('\n\n---\n\nstderr\n\n---\n')
  216. logfile.write(stde)
  217. logfile.write('\n\n---\n\n')
  218. if print_debug:
  219. print(stdo)
  220. print(stde, file=sys.stderr)
  221. if stop:
  222. print("Aborting..")
  223. for f in futures:
  224. f[2].cancel()
  225. executor.shutdown()
  226. raise StopException()
  227. def bold(text):
  228. return mlog.bold(text).get_text(mlog.colorize_console)
  229. def green(text):
  230. return mlog.green(text).get_text(mlog.colorize_console)
  231. def red(text):
  232. return mlog.red(text).get_text(mlog.colorize_console)
  233. def yellow(text):
  234. return mlog.yellow(text).get_text(mlog.colorize_console)
  235. def run_test_inprocess(testdir):
  236. old_stdout = sys.stdout
  237. sys.stdout = mystdout = StringIO()
  238. old_stderr = sys.stderr
  239. sys.stderr = mystderr = StringIO()
  240. old_cwd = os.getcwd()
  241. os.chdir(testdir)
  242. test_log_fname = 'meson-logs/testlog.txt'
  243. try:
  244. returncode_test = mtest.run(['--no-rebuild'])
  245. if os.path.exists(test_log_fname):
  246. test_log = open(test_log_fname, errors='ignore').read()
  247. else:
  248. test_log = ''
  249. returncode_benchmark = mtest.run(['--no-rebuild', '--benchmark', '--logbase', 'benchmarklog'])
  250. finally:
  251. sys.stdout = old_stdout
  252. sys.stderr = old_stderr
  253. os.chdir(old_cwd)
  254. return max(returncode_test, returncode_benchmark), mystdout.getvalue(), mystderr.getvalue(), test_log
  255. def parse_test_args(testdir):
  256. args = []
  257. try:
  258. with open(os.path.join(testdir, 'test_args.txt'), 'r') as f:
  259. content = f.read()
  260. try:
  261. args = literal_eval(content)
  262. except Exception:
  263. raise Exception('Malformed test_args file.')
  264. args = stringlistify(args)
  265. except FileNotFoundError:
  266. pass
  267. return args
  268. def run_test(skipped, testdir, extra_args, compiler, backend, flags, commands, should_fail):
  269. if skipped:
  270. return None
  271. with AutoDeletedDir(tempfile.mkdtemp(prefix='b ', dir='.')) as build_dir:
  272. with AutoDeletedDir(tempfile.mkdtemp(prefix='i ', dir=os.getcwd())) as install_dir:
  273. try:
  274. return _run_test(testdir, build_dir, install_dir, extra_args, compiler, backend, flags, commands, should_fail)
  275. finally:
  276. mlog.shutdown() # Close the log file because otherwise Windows wets itself.
  277. def pass_prefix_to_test(dirname):
  278. if '40 prefix' in dirname:
  279. return False
  280. return True
  281. def pass_libdir_to_test(dirname):
  282. if '8 install' in dirname:
  283. return False
  284. if '39 libdir' in dirname:
  285. return False
  286. return True
  287. def _run_test(testdir, test_build_dir, install_dir, extra_args, compiler, backend, flags, commands, should_fail):
  288. compile_commands, clean_commands, install_commands, uninstall_commands = commands
  289. test_args = parse_test_args(testdir)
  290. gen_start = time.time()
  291. # Configure in-process
  292. if pass_prefix_to_test(testdir):
  293. gen_args = ['--prefix', '/usr']
  294. else:
  295. gen_args = []
  296. if pass_libdir_to_test(testdir):
  297. gen_args += ['--libdir', 'lib']
  298. gen_args += [testdir, test_build_dir] + flags + test_args + extra_args
  299. (returncode, stdo, stde) = run_configure(meson_command, gen_args)
  300. try:
  301. logfile = os.path.join(test_build_dir, 'meson-logs/meson-log.txt')
  302. with open(logfile, errors='ignore') as f:
  303. mesonlog = f.read()
  304. except Exception:
  305. mesonlog = no_meson_log_msg
  306. gen_time = time.time() - gen_start
  307. if should_fail == 'meson':
  308. if returncode != 0:
  309. return TestResult('', BuildStep.configure, stdo, stde, mesonlog, gen_time)
  310. return TestResult('Test that should have failed succeeded', BuildStep.configure, stdo, stde, mesonlog, gen_time)
  311. if returncode != 0:
  312. return TestResult('Generating the build system failed.', BuildStep.configure, stdo, stde, mesonlog, gen_time)
  313. # Touch the meson.build file to force a regenerate so we can test that
  314. # regeneration works before a build is run.
  315. ensure_backend_detects_changes(backend)
  316. os.utime(os.path.join(testdir, 'meson.build'))
  317. # Build with subprocess
  318. dir_args = get_backend_args_for_dir(backend, test_build_dir)
  319. build_start = time.time()
  320. pc, o, e = Popen_safe(compile_commands + dir_args, cwd=test_build_dir)
  321. build_time = time.time() - build_start
  322. stdo += o
  323. stde += e
  324. if should_fail == 'build':
  325. if pc.returncode != 0:
  326. return TestResult('', BuildStep.build, stdo, stde, mesonlog, gen_time)
  327. return TestResult('Test that should have failed to build succeeded', BuildStep.build, stdo, stde, mesonlog, gen_time)
  328. if pc.returncode != 0:
  329. return TestResult('Compiling source code failed.', BuildStep.build, stdo, stde, mesonlog, gen_time, build_time)
  330. # Touch the meson.build file to force a regenerate so we can test that
  331. # regeneration works after a build is complete.
  332. ensure_backend_detects_changes(backend)
  333. os.utime(os.path.join(testdir, 'meson.build'))
  334. test_start = time.time()
  335. # Test in-process
  336. (returncode, tstdo, tstde, test_log) = run_test_inprocess(test_build_dir)
  337. test_time = time.time() - test_start
  338. stdo += tstdo
  339. stde += tstde
  340. mesonlog += test_log
  341. if should_fail == 'test':
  342. if returncode != 0:
  343. return TestResult('', BuildStep.test, stdo, stde, mesonlog, gen_time)
  344. return TestResult('Test that should have failed to run unit tests succeeded', BuildStep.test, stdo, stde, mesonlog, gen_time)
  345. if returncode != 0:
  346. return TestResult('Running unit tests failed.', BuildStep.test, stdo, stde, mesonlog, gen_time, build_time, test_time)
  347. # Do installation, if the backend supports it
  348. if install_commands:
  349. env = os.environ.copy()
  350. env['DESTDIR'] = install_dir
  351. # Install with subprocess
  352. pi, o, e = Popen_safe(install_commands, cwd=test_build_dir, env=env)
  353. stdo += o
  354. stde += e
  355. if pi.returncode != 0:
  356. return TestResult('Running install failed.', BuildStep.install, stdo, stde, mesonlog, gen_time, build_time, test_time)
  357. # Clean with subprocess
  358. env = os.environ.copy()
  359. pi, o, e = Popen_safe(clean_commands + dir_args, cwd=test_build_dir, env=env)
  360. stdo += o
  361. stde += e
  362. if pi.returncode != 0:
  363. return TestResult('Running clean failed.', BuildStep.clean, stdo, stde, mesonlog, gen_time, build_time, test_time)
  364. if not install_commands:
  365. return TestResult('', BuildStep.install, '', '', mesonlog, gen_time, build_time, test_time)
  366. return TestResult(validate_install(testdir, install_dir, compiler), BuildStep.validate, stdo, stde, mesonlog, gen_time, build_time, test_time)
  367. def gather_tests(testdir):
  368. tests = [t.replace('\\', '/').split('/', 2)[2] for t in glob(testdir + '/*')]
  369. testlist = [(int(t.split()[0]), t) for t in tests]
  370. testlist.sort()
  371. tests = [os.path.join(testdir, t[1]) for t in testlist]
  372. return tests
  373. def have_d_compiler():
  374. if shutil.which("ldc2"):
  375. return True
  376. elif shutil.which("ldc"):
  377. return True
  378. elif shutil.which("gdc"):
  379. return True
  380. elif shutil.which("dmd"):
  381. return True
  382. return False
  383. def have_objc_compiler():
  384. with AutoDeletedDir(tempfile.mkdtemp(prefix='b ', dir='.')) as build_dir:
  385. env = environment.Environment(None, build_dir, None, get_fake_options('/'), [])
  386. try:
  387. objc_comp = env.detect_objc_compiler(False)
  388. except:
  389. return False
  390. if not objc_comp:
  391. return False
  392. try:
  393. objc_comp.sanity_check(env.get_scratch_dir(), env)
  394. objcpp_comp = env.detect_objc_compiler(False)
  395. except:
  396. return False
  397. if not objcpp_comp:
  398. return False
  399. try:
  400. objcpp_comp.sanity_check(env.get_scratch_dir(), env)
  401. except:
  402. return False
  403. return True
  404. def have_java():
  405. if shutil.which('javac') and shutil.which('java'):
  406. return True
  407. return False
  408. def detect_tests_to_run():
  409. # Name, subdirectory, skip condition.
  410. all_tests = [
  411. ('common', 'common', False),
  412. ('failing-meson', 'failing', False),
  413. ('failing-build', 'failing build', False),
  414. ('failing-tests', 'failing tests', False),
  415. ('platform-osx', 'osx', not mesonlib.is_osx()),
  416. ('platform-windows', 'windows', not mesonlib.is_windows() and not mesonlib.is_cygwin()),
  417. ('platform-linux', 'linuxlike', mesonlib.is_osx() or mesonlib.is_windows()),
  418. ('java', 'java', backend is not Backend.ninja or mesonlib.is_osx() or not have_java()),
  419. ('C#', 'csharp', backend is not Backend.ninja or not shutil.which('mcs')),
  420. ('vala', 'vala', backend is not Backend.ninja or not shutil.which('valac')),
  421. ('rust', 'rust', backend is not Backend.ninja or not shutil.which('rustc')),
  422. ('d', 'd', backend is not Backend.ninja or not have_d_compiler()),
  423. ('objective c', 'objc', backend not in (Backend.ninja, Backend.xcode) or mesonlib.is_windows() or not have_objc_compiler()),
  424. ('fortran', 'fortran', backend is not Backend.ninja or not shutil.which('gfortran')),
  425. ('swift', 'swift', backend not in (Backend.ninja, Backend.xcode) or not shutil.which('swiftc')),
  426. ('python3', 'python3', backend is not Backend.ninja),
  427. ]
  428. gathered_tests = [(name, gather_tests('test cases/' + subdir), skip) for name, subdir, skip in all_tests]
  429. if mesonlib.is_windows():
  430. # TODO: Set BOOST_ROOT in .appveyor.yml
  431. gathered_tests += [('framework', ['test cases/frameworks/1 boost'], 'BOOST_ROOT' not in os.environ)]
  432. elif mesonlib.is_osx() or mesonlib.is_cygwin():
  433. gathered_tests += [('framework', gather_tests('test cases/frameworks'), True)]
  434. else:
  435. gathered_tests += [('framework', gather_tests('test cases/frameworks'), False)]
  436. return gathered_tests
  437. def run_tests(all_tests, log_name_base, extra_args):
  438. global logfile
  439. txtname = log_name_base + '.txt'
  440. with open(txtname, 'w', encoding="utf_8") as lf:
  441. logfile = lf
  442. return _run_tests(all_tests, log_name_base, extra_args)
  443. def _run_tests(all_tests, log_name_base, extra_args):
  444. global stop, executor, futures, system_compiler
  445. xmlname = log_name_base + '.xml'
  446. junit_root = ET.Element('testsuites')
  447. conf_time = 0
  448. build_time = 0
  449. test_time = 0
  450. passing_tests = 0
  451. failing_tests = 0
  452. skipped_tests = 0
  453. commands = (compile_commands, clean_commands, install_commands, uninstall_commands)
  454. try:
  455. # This fails in some CI environments for unknown reasons.
  456. num_workers = multiprocessing.cpu_count()
  457. except Exception as e:
  458. print('Could not determine number of CPUs due to the following reason:' + str(e))
  459. print('Defaulting to using only one process')
  460. num_workers = 1
  461. # Due to Ninja deficiency, almost 50% of build time
  462. # is spent waiting. Do something useful instead.
  463. #
  464. # Remove this once the following issue has been resolved:
  465. # https://github.com/mesonbuild/meson/pull/2082
  466. num_workers *= 2
  467. try:
  468. executor = conc.ProcessPoolExecutor(max_workers=num_workers)
  469. except ImportError:
  470. print('Platform doesn\'t ProcessPoolExecutor, falling back to single-threaded testing\n')
  471. executor = DummyExecutor()
  472. for name, test_cases, skipped in all_tests:
  473. current_suite = ET.SubElement(junit_root, 'testsuite', {'name': name, 'tests': str(len(test_cases))})
  474. print()
  475. if skipped:
  476. print(bold('Not running %s tests.' % name))
  477. else:
  478. print(bold('Running %s tests.' % name))
  479. print()
  480. futures = []
  481. for t in test_cases:
  482. # Jenkins screws us over by automatically sorting test cases by name
  483. # and getting it wrong by not doing logical number sorting.
  484. (testnum, testbase) = os.path.split(t)[-1].split(' ', 1)
  485. testname = '%.3d %s' % (int(testnum), testbase)
  486. should_fail = False
  487. if name.startswith('failing'):
  488. should_fail = name.split('failing-')[1]
  489. result = executor.submit(run_test, skipped, t, extra_args, system_compiler, backend, backend_flags, commands, should_fail)
  490. futures.append((testname, t, result))
  491. for (testname, t, result) in futures:
  492. sys.stdout.flush()
  493. result = result.result()
  494. if result is None or 'MESON_SKIP_TEST' in result.stdo:
  495. print(yellow('Skipping:'), t)
  496. current_test = ET.SubElement(current_suite, 'testcase', {'name': testname,
  497. 'classname': name})
  498. ET.SubElement(current_test, 'skipped', {})
  499. skipped_tests += 1
  500. else:
  501. without_install = "" if len(install_commands) > 0 else " (without install)"
  502. if result.msg != '':
  503. print(red('Failed test{} during {}: {!r}'.format(without_install, result.step.name, t)))
  504. print('Reason:', result.msg)
  505. failing_tests += 1
  506. if result.step == BuildStep.configure and result.mlog != no_meson_log_msg:
  507. # For configure failures, instead of printing stdout,
  508. # print the meson log if available since it's a superset
  509. # of stdout and often has very useful information.
  510. failing_logs.append(result.mlog)
  511. else:
  512. failing_logs.append(result.stdo)
  513. failing_logs.append(result.stde)
  514. else:
  515. print('Succeeded test%s: %s' % (without_install, t))
  516. passing_tests += 1
  517. conf_time += result.conftime
  518. build_time += result.buildtime
  519. test_time += result.testtime
  520. total_time = conf_time + build_time + test_time
  521. log_text_file(logfile, t, result.stdo, result.stde)
  522. current_test = ET.SubElement(current_suite, 'testcase', {'name': testname,
  523. 'classname': name,
  524. 'time': '%.3f' % total_time})
  525. if result.msg != '':
  526. ET.SubElement(current_test, 'failure', {'message': result.msg})
  527. stdoel = ET.SubElement(current_test, 'system-out')
  528. stdoel.text = result.stdo
  529. stdeel = ET.SubElement(current_test, 'system-err')
  530. stdeel.text = result.stde
  531. print("\nTotal configuration time: %.2fs" % conf_time)
  532. print("Total build time: %.2fs" % build_time)
  533. print("Total test time: %.2fs" % test_time)
  534. ET.ElementTree(element=junit_root).write(xmlname, xml_declaration=True, encoding='UTF-8')
  535. return passing_tests, failing_tests, skipped_tests
  536. def check_file(fname):
  537. linenum = 1
  538. with open(fname, 'rb') as f:
  539. lines = f.readlines()
  540. for line in lines:
  541. if line.startswith(b'\t'):
  542. print("File %s contains a literal tab on line %d. Only spaces are permitted." % (fname, linenum))
  543. sys.exit(1)
  544. if b'\r' in line:
  545. print("File %s contains DOS line ending on line %d. Only unix-style line endings are permitted." % (fname, linenum))
  546. sys.exit(1)
  547. linenum += 1
  548. def check_format():
  549. for (root, _, files) in os.walk('.'):
  550. for file in files:
  551. if file.endswith('.py') or file.endswith('.build') or file == 'meson_options.txt':
  552. fullname = os.path.join(root, file)
  553. check_file(fullname)
  554. def check_meson_commands_work():
  555. global backend, meson_command, compile_commands, test_commands, install_commands
  556. testdir = 'test cases/common/1 trivial'
  557. with AutoDeletedDir(tempfile.mkdtemp(prefix='b ', dir='.')) as build_dir:
  558. print('Checking that configuring works...')
  559. gen_cmd = mesonlib.meson_command + [testdir, build_dir] + backend_flags
  560. pc, o, e = Popen_safe(gen_cmd)
  561. if pc.returncode != 0:
  562. raise RuntimeError('Failed to configure {!r}:\n{}\n{}'.format(testdir, e, o))
  563. print('Checking that building works...')
  564. dir_args = get_backend_args_for_dir(backend, build_dir)
  565. pc, o, e = Popen_safe(compile_commands + dir_args, cwd=build_dir)
  566. if pc.returncode != 0:
  567. raise RuntimeError('Failed to build {!r}:\n{}\n{}'.format(testdir, e, o))
  568. print('Checking that testing works...')
  569. pc, o, e = Popen_safe(test_commands, cwd=build_dir)
  570. if pc.returncode != 0:
  571. raise RuntimeError('Failed to test {!r}:\n{}\n{}'.format(testdir, e, o))
  572. if install_commands:
  573. print('Checking that installing works...')
  574. pc, o, e = Popen_safe(install_commands, cwd=build_dir)
  575. if pc.returncode != 0:
  576. raise RuntimeError('Failed to install {!r}:\n{}\n{}'.format(testdir, e, o))
  577. def detect_system_compiler():
  578. global system_compiler
  579. if shutil.which('cl'):
  580. system_compiler = 'cl'
  581. elif shutil.which('cc'):
  582. system_compiler = 'cc'
  583. elif shutil.which('gcc'):
  584. system_compiler = 'gcc'
  585. else:
  586. raise RuntimeError("Could not find C compiler.")
  587. if __name__ == '__main__':
  588. parser = argparse.ArgumentParser(description="Run the test suite of Meson.")
  589. parser.add_argument('extra_args', nargs='*',
  590. help='arguments that are passed directly to Meson (remember to have -- before these).')
  591. parser.add_argument('--backend', default=None, dest='backend',
  592. choices=backendlist)
  593. options = parser.parse_args()
  594. setup_commands(options.backend)
  595. detect_system_compiler()
  596. script_dir = os.path.split(__file__)[0]
  597. if script_dir != '':
  598. os.chdir(script_dir)
  599. check_format()
  600. check_meson_commands_work()
  601. try:
  602. all_tests = detect_tests_to_run()
  603. (passing_tests, failing_tests, skipped_tests) = run_tests(all_tests, 'meson-test-run', options.extra_args)
  604. except StopException:
  605. pass
  606. print('\nTotal passed tests:', green(str(passing_tests)))
  607. print('Total failed tests:', red(str(failing_tests)))
  608. print('Total skipped tests:', yellow(str(skipped_tests)))
  609. if failing_tests > 0:
  610. print('\nMesonlogs of failing tests\n')
  611. for l in failing_logs:
  612. print(l, '\n')
  613. for name, dirs, skip in all_tests:
  614. dirs = (os.path.basename(x) for x in dirs)
  615. for k, g in itertools.groupby(dirs, key=lambda x: x.split()[0]):
  616. tests = list(g)
  617. if len(tests) != 1:
  618. print('WARNING: The %s suite contains duplicate "%s" tests: "%s"' % (name, k, '", "'.join(tests)))
  619. sys.exit(failing_tests)