run_project_tests.py 27 KB

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