run_project_tests.py 28 KB

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