run_tests.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. #!/usr/bin/env python3
  2. # Copyright 2012-2017 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 os
  13. import sys
  14. import time
  15. import shutil
  16. import subprocess
  17. import tempfile
  18. import platform
  19. import argparse
  20. from io import StringIO
  21. from enum import Enum
  22. from glob import glob
  23. from pathlib import Path
  24. import mesonbuild
  25. from mesonbuild import mesonlib
  26. from mesonbuild import mesonmain
  27. from mesonbuild import mtest
  28. from mesonbuild import mlog
  29. from mesonbuild.environment import Environment, detect_ninja
  30. from mesonbuild.coredata import backendlist
  31. def guess_backend(backend, msbuild_exe):
  32. # Auto-detect backend if unspecified
  33. backend_flags = []
  34. if backend is None:
  35. if msbuild_exe is not None and mesonlib.is_windows():
  36. backend = 'vs' # Meson will auto-detect VS version to use
  37. else:
  38. backend = 'ninja'
  39. # Set backend arguments for Meson
  40. if backend.startswith('vs'):
  41. backend_flags = ['--backend=' + backend]
  42. backend = Backend.vs
  43. elif backend == 'xcode':
  44. backend_flags = ['--backend=xcode']
  45. backend = Backend.xcode
  46. elif backend == 'ninja':
  47. backend_flags = ['--backend=ninja']
  48. backend = Backend.ninja
  49. else:
  50. raise RuntimeError('Unknown backend: {!r}'.format(backend))
  51. return (backend, backend_flags)
  52. # Fake classes and objects for mocking
  53. class FakeBuild:
  54. def __init__(self, env):
  55. self.environment = env
  56. class FakeCompilerOptions:
  57. def __init__(self):
  58. self.value = []
  59. def get_fake_options(prefix=''):
  60. import argparse
  61. opts = argparse.Namespace()
  62. opts.cross_file = None
  63. opts.wrap_mode = None
  64. opts.prefix = prefix
  65. opts.cmd_line_options = {}
  66. opts.native_file = []
  67. return opts
  68. def get_fake_env(sdir='', bdir=None, prefix='', opts=None):
  69. if opts is None:
  70. opts = get_fake_options(prefix)
  71. env = Environment(sdir, bdir, opts)
  72. env.coredata.compiler_options.host['c_args'] = FakeCompilerOptions()
  73. env.machines.host.cpu_family = 'x86_64' # Used on macOS inside find_library
  74. return env
  75. Backend = Enum('Backend', 'ninja vs xcode')
  76. if 'MESON_EXE' in os.environ:
  77. import shlex
  78. meson_exe = shlex.split(os.environ['MESON_EXE'])
  79. else:
  80. meson_exe = None
  81. if mesonlib.is_windows() or mesonlib.is_cygwin():
  82. exe_suffix = '.exe'
  83. else:
  84. exe_suffix = ''
  85. def get_meson_script():
  86. '''
  87. Guess the meson that corresponds to the `mesonbuild` that has been imported
  88. so we can run configure and other commands in-process, since mesonmain.run
  89. needs to know the meson_command to use.
  90. Also used by run_unittests.py to determine what meson to run when not
  91. running in-process (which is the default).
  92. '''
  93. # Is there a meson.py next to the mesonbuild currently in use?
  94. mesonbuild_dir = Path(mesonbuild.__file__).resolve().parent.parent
  95. meson_script = mesonbuild_dir / 'meson.py'
  96. if meson_script.is_file():
  97. return str(meson_script)
  98. # Then if mesonbuild is in PYTHONPATH, meson must be in PATH
  99. mlog.warning('Could not find meson.py next to the mesonbuild module. '
  100. 'Trying system meson...')
  101. meson_cmd = shutil.which('meson')
  102. if meson_cmd:
  103. return meson_cmd
  104. raise RuntimeError('Could not find {!r} or a meson in PATH'.format(meson_script))
  105. def get_backend_args_for_dir(backend, builddir):
  106. '''
  107. Visual Studio backend needs to be given the solution to build
  108. '''
  109. if backend is Backend.vs:
  110. sln_name = glob(os.path.join(builddir, '*.sln'))[0]
  111. return [os.path.split(sln_name)[-1]]
  112. return []
  113. def find_vcxproj_with_target(builddir, target):
  114. import re, fnmatch
  115. t, ext = os.path.splitext(target)
  116. if ext:
  117. p = r'<TargetName>{}</TargetName>\s*<TargetExt>\{}</TargetExt>'.format(t, ext)
  118. else:
  119. p = r'<TargetName>{}</TargetName>'.format(t)
  120. for root, dirs, files in os.walk(builddir):
  121. for f in fnmatch.filter(files, '*.vcxproj'):
  122. f = os.path.join(builddir, f)
  123. with open(f, 'r', encoding='utf-8') as o:
  124. if re.search(p, o.read(), flags=re.MULTILINE):
  125. return f
  126. raise RuntimeError('No vcxproj matching {!r} in {!r}'.format(p, builddir))
  127. def get_builddir_target_args(backend, builddir, target):
  128. dir_args = []
  129. if not target:
  130. dir_args = get_backend_args_for_dir(backend, builddir)
  131. if target is None:
  132. return dir_args
  133. if backend is Backend.vs:
  134. vcxproj = find_vcxproj_with_target(builddir, target)
  135. target_args = [vcxproj]
  136. elif backend is Backend.xcode:
  137. target_args = ['-target', target]
  138. elif backend is Backend.ninja:
  139. target_args = [target]
  140. else:
  141. raise AssertionError('Unknown backend: {!r}'.format(backend))
  142. return target_args + dir_args
  143. def get_backend_commands(backend, debug=False):
  144. install_cmd = []
  145. uninstall_cmd = []
  146. if backend is Backend.vs:
  147. cmd = ['msbuild']
  148. clean_cmd = cmd + ['/target:Clean']
  149. test_cmd = cmd + ['RUN_TESTS.vcxproj']
  150. elif backend is Backend.xcode:
  151. cmd = ['xcodebuild']
  152. # In Xcode9 new build system's clean command fails when using a custom build directory.
  153. # Maybe use it when CI uses Xcode10 we can remove '-UseNewBuildSystem=FALSE'
  154. clean_cmd = cmd + ['-alltargets', 'clean', '-UseNewBuildSystem=FALSE']
  155. test_cmd = cmd + ['-target', 'RUN_TESTS']
  156. elif backend is Backend.ninja:
  157. # We need at least 1.6 because of -w dupbuild=err
  158. cmd = [detect_ninja('1.6'), '-w', 'dupbuild=err', '-d', 'explain']
  159. if cmd[0] is None:
  160. raise RuntimeError('Could not find Ninja v1.6 or newer')
  161. if debug:
  162. cmd += ['-v']
  163. clean_cmd = cmd + ['clean']
  164. test_cmd = cmd + ['test', 'benchmark']
  165. install_cmd = cmd + ['install']
  166. uninstall_cmd = cmd + ['uninstall']
  167. else:
  168. raise AssertionError('Unknown backend: {!r}'.format(backend))
  169. return cmd, clean_cmd, test_cmd, install_cmd, uninstall_cmd
  170. def ensure_backend_detects_changes(backend):
  171. # We're using a ninja with QuLogic's patch for sub-1s resolution timestamps
  172. # and not running on HFS+ which only stores dates in seconds:
  173. # https://developer.apple.com/legacy/library/technotes/tn/tn1150.html#HFSPlusDates
  174. # FIXME: Upgrade Travis image to Apple FS when that becomes available
  175. if 'MESON_FIXED_NINJA' in os.environ and not mesonlib.is_osx():
  176. return
  177. # This is needed to increase the difference between build.ninja's
  178. # timestamp and the timestamp of whatever you changed due to a Ninja
  179. # bug: https://github.com/ninja-build/ninja/issues/371
  180. if backend is Backend.ninja:
  181. time.sleep(1)
  182. def run_mtest_inprocess(commandlist):
  183. old_stdout = sys.stdout
  184. sys.stdout = mystdout = StringIO()
  185. old_stderr = sys.stderr
  186. sys.stderr = mystderr = StringIO()
  187. try:
  188. returncode = mtest.run_with_args(commandlist)
  189. finally:
  190. sys.stdout = old_stdout
  191. sys.stderr = old_stderr
  192. return returncode, mystdout.getvalue(), mystderr.getvalue()
  193. def clear_meson_configure_class_caches():
  194. mesonbuild.compilers.CCompiler.library_dirs_cache = {}
  195. mesonbuild.compilers.CCompiler.program_dirs_cache = {}
  196. mesonbuild.compilers.CCompiler.find_library_cache = {}
  197. mesonbuild.compilers.CCompiler.find_framework_cache = {}
  198. mesonbuild.dependencies.PkgConfigDependency.pkgbin_cache = {}
  199. mesonbuild.dependencies.PkgConfigDependency.class_pkgbin = mesonlib.PerMachine(None, None, None)
  200. def run_configure_inprocess(commandlist):
  201. old_stdout = sys.stdout
  202. sys.stdout = mystdout = StringIO()
  203. old_stderr = sys.stderr
  204. sys.stderr = mystderr = StringIO()
  205. try:
  206. returncode = mesonmain.run(commandlist, get_meson_script())
  207. finally:
  208. sys.stdout = old_stdout
  209. sys.stderr = old_stderr
  210. clear_meson_configure_class_caches()
  211. return returncode, mystdout.getvalue(), mystderr.getvalue()
  212. def run_configure_external(full_command):
  213. pc, o, e = mesonlib.Popen_safe(full_command)
  214. return pc.returncode, o, e
  215. def run_configure(commandlist):
  216. global meson_exe
  217. if meson_exe:
  218. return run_configure_external(meson_exe + commandlist)
  219. return run_configure_inprocess(commandlist)
  220. def print_system_info():
  221. print(mlog.bold('System information.').get_text(mlog.colorize_console))
  222. print('Architecture:', platform.architecture())
  223. print('Machine:', platform.machine())
  224. print('Platform:', platform.system())
  225. print('Processor:', platform.processor())
  226. print('System:', platform.system())
  227. print('')
  228. def main():
  229. print_system_info()
  230. parser = argparse.ArgumentParser()
  231. parser.add_argument('--cov', action='store_true')
  232. parser.add_argument('--backend', default=None, dest='backend',
  233. choices=backendlist)
  234. parser.add_argument('--cross', default=False, dest='cross', action='store_true')
  235. parser.add_argument('--failfast', action='store_true')
  236. (options, _) = parser.parse_known_args()
  237. # Enable coverage early...
  238. enable_coverage = options.cov
  239. if enable_coverage:
  240. os.makedirs('.coverage', exist_ok=True)
  241. sys.argv.remove('--cov')
  242. import coverage
  243. coverage.process_startup()
  244. returncode = 0
  245. cross = options.cross
  246. backend, _ = guess_backend(options.backend, shutil.which('msbuild'))
  247. # Running on a developer machine? Be nice!
  248. if not mesonlib.is_windows() and not mesonlib.is_haiku() and 'CI' not in os.environ:
  249. os.nice(20)
  250. # Appveyor sets the `platform` environment variable which completely messes
  251. # up building with the vs2010 and vs2015 backends.
  252. #
  253. # Specifically, MSBuild reads the `platform` environment variable to set
  254. # the configured value for the platform (Win32/x64/arm), which breaks x86
  255. # builds.
  256. #
  257. # Appveyor setting this also breaks our 'native build arch' detection for
  258. # Windows in environment.py:detect_windows_arch() by overwriting the value
  259. # of `platform` set by vcvarsall.bat.
  260. #
  261. # While building for x86, `platform` should be unset.
  262. if 'APPVEYOR' in os.environ and os.environ['arch'] == 'x86':
  263. os.environ.pop('platform')
  264. # Run tests
  265. print(mlog.bold('Running unittests.').get_text(mlog.colorize_console))
  266. print()
  267. # Can't pass arguments to unit tests, so set the backend to use in the environment
  268. env = os.environ.copy()
  269. env['MESON_UNIT_TEST_BACKEND'] = backend.name
  270. with tempfile.TemporaryDirectory() as temp_dir:
  271. # Enable coverage on all subsequent processes.
  272. if enable_coverage:
  273. Path(temp_dir, 'usercustomize.py').open('w').write(
  274. 'import coverage\n'
  275. 'coverage.process_startup()\n')
  276. env['COVERAGE_PROCESS_START'] = '.coveragerc'
  277. if 'PYTHONPATH' in env:
  278. env['PYTHONPATH'] = os.pathsep.join([temp_dir, env.get('PYTHONPATH')])
  279. else:
  280. env['PYTHONPATH'] = temp_dir
  281. if not cross:
  282. cmd = mesonlib.python_command + ['run_meson_command_tests.py', '-v']
  283. if options.failfast:
  284. cmd += ['--failfast']
  285. returncode += subprocess.call(cmd, env=env)
  286. if options.failfast and returncode != 0:
  287. return returncode
  288. cmd = mesonlib.python_command + ['run_unittests.py', '-v']
  289. if options.failfast:
  290. cmd += ['--failfast']
  291. returncode += subprocess.call(cmd, env=env)
  292. if options.failfast and returncode != 0:
  293. return returncode
  294. cmd = mesonlib.python_command + ['run_project_tests.py'] + sys.argv[1:]
  295. returncode += subprocess.call(cmd, env=env)
  296. else:
  297. cross_test_args = mesonlib.python_command + ['run_cross_test.py']
  298. print(mlog.bold('Running armhf cross tests.').get_text(mlog.colorize_console))
  299. print()
  300. cmd = cross_test_args + ['cross/ubuntu-armhf.txt']
  301. if options.failfast:
  302. cmd += ['--failfast']
  303. returncode += subprocess.call(cmd, env=env)
  304. if options.failfast and returncode != 0:
  305. return returncode
  306. print(mlog.bold('Running mingw-w64 64-bit cross tests.')
  307. .get_text(mlog.colorize_console))
  308. print()
  309. cmd = cross_test_args + ['cross/linux-mingw-w64-64bit.txt']
  310. if options.failfast:
  311. cmd += ['--failfast']
  312. returncode += subprocess.call(cmd, env=env)
  313. return returncode
  314. if __name__ == '__main__':
  315. sys.exit(main())