Debian Codegraph @

unittests/baseplatformtests.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2016-2021 The Meson development team
3 # Copyright © 2024 Intel Corporation
4
5 from __future__ import annotations
6 from pathlib import PurePath
7 from unittest import mock, TestCase, SkipTest
8 import json
9 import io
10 import os
11 import re
12 import subprocess
13 import sys
14 import shutil
15 import tempfile
16 import typing as T
17
18 import mesonbuild.mlog
19 import mesonbuild.depfile
20 import mesonbuild.dependencies.base
21 import mesonbuild.dependencies.factory
22 import mesonbuild.compilers
23 import mesonbuild.envconfig
24 import mesonbuild.environment
25 import mesonbuild.coredata
26 import mesonbuild.modules.gnome
27 from mesonbuild.mesonlib import (
28 is_windows, is_cygwin, join_args, split_args, windows_proof_rmtree, python_command
29 )
30 import mesonbuild.modules.pkgconfig
31
32
33 from run_tests import (
34 Backend, get_backend_commands,
35 get_builddir_target_args, get_meson_script, run_configure_inprocess,
36 run_mtest_inprocess, handle_meson_skip_test,
37 )
38
39 if T.TYPE_CHECKING:
40 from typing_extensions import TypeAlias, TypedDict
41
42 class CompDbEntry(TypedDict):
43
44 # `output` is not strictly required, but Ninja always generates it
45 # `arguments` is allowed, but Ninja never generates it
46
47 directory: str
48 command: str
49 file: str
50 output: str
51
52 CompDB: TypeAlias = T.List[CompDbEntry]
53
54
55 # magic attribute used by unittest.result.TestResult._is_relevant_tb_level
56 # This causes tracebacks to hide these internal implementation details,
57 # e.g. for assertXXX helpers.
58 __unittest = True
59
60 class BasePlatformTests(TestCase):
61 prefix = '/usr'
62 libdir = 'lib'
63 _mktmpdir: T.Callable[[], str]
64
65 @classmethod
66 def setUpClass(cls) -> None:
67 super().setUpClass()
68 cls.maxDiff = None
69 src_root = str(PurePath(__file__).parents[1])
70 cls.src_root = src_root
71 # Get the backend
72 cls.backend_name = os.environ.get('MESON_UNIT_TEST_BACKEND', 'ninja')
73 backend_type = 'vs' if cls.backend_name.startswith('vs') else cls.backend_name
74 cls.backend = getattr(Backend, backend_type)
75 cls.meson_args = ['--backend=' + cls.backend_name]
76 cls.meson_command = python_command + [get_meson_script()]
77 cls.setup_command = cls.meson_command + ['setup'] + cls.meson_args
78 cls.mconf_command = cls.meson_command + ['configure']
79 cls.mintro_command = cls.meson_command + ['introspect']
80 cls.wrap_command = cls.meson_command + ['wrap']
81 cls.rewrite_command = cls.meson_command + ['rewrite']
82 # Backend-specific build commands
83 cls.build_command, cls.clean_command, cls.test_command, cls.install_command, \
84 cls.uninstall_command = get_backend_commands(cls.backend)
85 # Test directories
86 cls.common_test_dir = os.path.join(src_root, 'test cases/common')
87 cls.python_test_dir = os.path.join(src_root, 'test cases/python')
88 cls.rust_test_dir = os.path.join(src_root, 'test cases/rust')
89 cls.vala_test_dir = os.path.join(src_root, 'test cases/vala')
90 cls.framework_test_dir = os.path.join(src_root, 'test cases/frameworks')
91 cls.unit_test_dir = os.path.join(src_root, 'test cases/unit')
92 cls.rewrite_test_dir = os.path.join(src_root, 'test cases/rewrite')
93 cls.linuxlike_test_dir = os.path.join(src_root, 'test cases/linuxlike')
94 cls.objc_test_dir = os.path.join(src_root, 'test cases/objc')
95 cls.objcpp_test_dir = os.path.join(src_root, 'test cases/objcpp')
96 cls.darwin_test_dir = os.path.join(src_root, 'test cases/darwin')
97 cls.fortran_test_dir = os.path.join(src_root, 'test cases/fortran')
98
99 # Misc stuff
100 if cls.backend is Backend.ninja:
101 cls.no_rebuild_stdout = ['ninja: no work to do.', 'samu: nothing to do']
102 else:
103 # VS doesn't have a stable output when no changes are done
104 # XCode backend is untested with unit tests, help welcome!
105 cls.no_rebuild_stdout = [f'UNKNOWN BACKEND {cls.backend.name!r}']
106
107 cls.env_patch = mock.patch.dict(os.environ)
108 cls.env_patch.start()
109
110 os.environ['COLUMNS'] = '80'
111 os.environ['PYTHONIOENCODING'] = 'utf8'
112
113 # If set to 1, force unittests to put their working stuff in /tmp
114 # Many Windows virus scanners have issues with the files being in the
115 # tmp directory.
116 #
117 # Store as an attribute because this path is very hot.
118 # the use of `staticmethod()` here is required because of Python's
119 # Object model, which otherwise sees these as methods
120 if (is_windows() or is_cygwin()) and not os.environ.get('MESON_FORCE_UNITTEST_IN_TMP', '0') == '1':
121 def tmpdir() -> str:
122 return tempfile.mkdtemp(dir=os.getcwd())
123
124 cls._mktmpdir = staticmethod(tmpdir)
125 else:
126 cls._mktmpdir = staticmethod(tempfile.mkdtemp)
127
128 @classmethod
129 def tearDownClass(cls) -> None:
130 super().tearDownClass()
131 cls.env_patch.stop()
132
133 def setUp(self):
134 super().setUp()
135 self.meson_native_files = []
136 self.meson_cross_files = []
137 self.new_builddir()
138
139 def change_builddir(self, newdir: str) -> None:
140 self.builddir = newdir
141 self.privatedir = os.path.join(self.builddir, 'meson-private')
142 self.logdir = os.path.join(self.builddir, 'meson-logs')
143 self.installdir = os.path.join(self.builddir, 'install')
144 self.distdir = os.path.join(self.builddir, 'meson-dist')
145 self.mtest_command = self.meson_command + ['test', '-C', self.builddir]
146 if os.path.islink(newdir):
147 self.addCleanup(os.unlink, self.builddir)
148 else:
149 self.addCleanup(windows_proof_rmtree, self.builddir)
150
151 def new_builddir(self) -> None:
152 newdir = self._mktmpdir()
153 # In case the directory is inside a symlinked directory, find the real
154 # path otherwise we might not find the srcdir from inside the builddir.
155 newdir = os.path.realpath(newdir)
156 self.change_builddir(newdir)
157
158 def _open_meson_log(self) -> io.TextIOWrapper:
159 log = os.path.join(self.logdir, 'meson-log.txt')
160 return open(log, encoding='utf-8')
161
162 def _get_meson_log(self) -> T.Optional[str]:
163 try:
164 with self._open_meson_log() as f:
165 return f.read()
166 except FileNotFoundError as e:
167 print(f"{e.filename!r} doesn't exist", file=sys.stderr)
168 return None
169
170 def _print_meson_log(self) -> None:
171 log = self._get_meson_log()
172 if log:
173 print(log)
174
175 def _run(self, command, *, workdir=None, override_envvars: T.Optional[T.Mapping[str, str]] = None, stderr=True):
176 '''
177 Run a command while printing the stdout and stderr to stdout,
178 and also return a copy of it
179 '''
180 # If this call hangs CI will just abort. It is very hard to distinguish
181 # between CI issue and test bug in that case. Set timeout and fail loud
182 # instead.
183 if override_envvars is None:
184 env = None
185 else:
186 env = os.environ.copy()
187 env.update(override_envvars)
188
189 proc = subprocess.run(command, stdout=subprocess.PIPE,
190 stderr=subprocess.STDOUT if stderr else subprocess.PIPE,
191 env=env,
192 encoding='utf-8',
193 text=True, cwd=workdir, timeout=60 * 5)
194 print('$', join_args(command))
195 print('stdout:')
196 print(proc.stdout)
197 if not stderr:
198 print('stderr:')
199 print(proc.stderr)
200 if proc.returncode != 0:
201 skipped, reason = handle_meson_skip_test(proc.stdout)
202 if skipped:
203 raise SkipTest(f'Project requested skipping: {reason}')
204 raise subprocess.CalledProcessError(proc.returncode, command, output=proc.stdout)
205 return proc.stdout
206
207 def init(self, srcdir, *,
208 extra_args=None,
209 default_args=True,
210 inprocess=False,
211 override_envvars: T.Optional[T.Mapping[str, str]] = None,
212 workdir=None,
213 allow_fail: bool = False) -> str:
214 """Call `meson setup`
215
216 :param allow_fail: If set to true initialization is allowed to fail.
217 When it does the log will be returned instead of stdout.
218 :return: the value of stdout on success, or the meson log on failure
219 when :param allow_fail: is true
220 """
221 self.assertPathExists(srcdir)
222 if extra_args is None:
223 extra_args = []
224 if not isinstance(extra_args, list):
225 extra_args = [extra_args]
226 build_and_src_dir_args = [self.builddir, srcdir]
227 args = []
228 if default_args:
229 args += ['--prefix', self.prefix]
230 if self.libdir:
231 args += ['--libdir', self.libdir]
232 for f in self.meson_native_files:
233 args += ['--native-file', f]
234 for f in self.meson_cross_files:
235 args += ['--cross-file', f]
236 self.privatedir = os.path.join(self.builddir, 'meson-private')
237 if inprocess:
238 try:
239 returncode, out, err = run_configure_inprocess(['setup'] + self.meson_args + args + extra_args + build_and_src_dir_args, override_envvars)
240 except Exception as e:
241 if not allow_fail:
242 self._print_meson_log()
243 raise
244 out = self._get_meson_log() # Best we can do here
245 err = '' # type checkers can't figure out that on this path returncode will always be 0
246 returncode = 0
247 finally:
248 # Close log file to satisfy Windows file locking
249 mesonbuild.mlog.shutdown()
250 mesonbuild.mlog._logger.log_dir = None
251 mesonbuild.mlog._logger.log_file = None
252
253 skipped, reason = handle_meson_skip_test(out)
254 if skipped:
255 raise SkipTest(f'Project requested skipping: {reason}')
256 if returncode != 0:
257 self._print_meson_log()
258 print('Stdout:\n')
259 print(out)
260 print('Stderr:\n')
261 print(err)
262 if not allow_fail:
263 raise RuntimeError('Configure failed')
264 else:
265 try:
266 out = self._run(self.setup_command + args + extra_args + build_and_src_dir_args, override_envvars=override_envvars, workdir=workdir)
267 except Exception:
268 if not allow_fail:
269 self._print_meson_log()
270 raise
271 out = self._get_meson_log() # best we can do here
272 return out
273
274 def build(self, target=None, *, extra_args=None, override_envvars=None, stderr=True):
275 if extra_args is None:
276 extra_args = []
277 # Add arguments for building the target (if specified),
278 # and using the build dir (if required, with VS)
279 args = get_builddir_target_args(self.backend, self.builddir, target)
280 return self._run(self.build_command + args + extra_args, workdir=self.builddir, override_envvars=override_envvars, stderr=stderr)
281
282 def clean(self, *, override_envvars=None):
283 dir_args = get_builddir_target_args(self.backend, self.builddir, None)
284 self._run(self.clean_command + dir_args, workdir=self.builddir, override_envvars=override_envvars)
285
286 def run_tests(self, *, inprocess=False, override_envvars=None):
287 if not inprocess:
288 return self._run(self.test_command, workdir=self.builddir, override_envvars=override_envvars)
289 else:
290 with mock.patch.dict(os.environ, override_envvars):
291 return run_mtest_inprocess(['-C', self.builddir])[1]
292
293 def install(self, *, use_destdir=True, override_envvars=None):
294 if self.backend is not Backend.ninja:
295 raise SkipTest(f'{self.backend.name!r} backend can\'t install files')
296 if use_destdir:
297 destdir = {'DESTDIR': self.installdir}
298 if override_envvars is None:
299 override_envvars = destdir
300 else:
301 override_envvars.update(destdir)
302 return self._run(self.install_command, workdir=self.builddir, override_envvars=override_envvars)
303
304 def uninstall(self, *, override_envvars=None):
305 self._run(self.uninstall_command, workdir=self.builddir, override_envvars=override_envvars)
306
307 def run_target(self, target, *, override_envvars=None):
308 '''
309 Run a Ninja target while printing the stdout and stderr to stdout,
310 and also return a copy of it
311 '''
312 return self.build(target=target, override_envvars=override_envvars)
313
314 def setconf(self, arg: T.Sequence[str], will_build: bool = True) -> None:
315 if isinstance(arg, str):
316 arg = [arg]
317 else:
318 arg = list(arg)
319 self._run(self.mconf_command + arg + [self.builddir])
320 if will_build:
321 self.build()
322
323 def getconf(self, optname: str, opts=None):
324 if opts is None:
325 opts = self.introspect('--buildoptions')
326 for x in opts:
327 if x.get('name') == optname:
328 return x.get('value')
329 self.fail(f'Option {optname} not found')
330
331 def wipe(self):
332 windows_proof_rmtree(self.builddir)
333
334 def utime(self, f):
335 os.utime(f)
336
337 def get_compdb(self) -> CompDB:
338 if self.backend is not Backend.ninja:
339 raise SkipTest(f'Compiler db not available with {self.backend.name} backend')
340 try:
341 with open(os.path.join(self.builddir, 'compile_commands.json'), encoding='utf-8') as ifile:
342 contents = T.cast('CompDB', json.load(ifile))
343 except FileNotFoundError:
344 raise SkipTest('Compiler db not found')
345 # If Ninja is using .rsp files, generate them, read their contents, and
346 # replace it as the command for all compile commands in the parsed json.
347 if contents and contents[0]['command'].endswith('.rsp'):
348 # Pretend to build so that the rsp files are generated
349 self.build(extra_args=['-d', 'keeprsp', '-n'])
350 for each in contents:
351 # Extract the actual command from the rsp file
352 compiler, rsp = each['command'].split(' @')
353 rsp = os.path.join(self.builddir, rsp)
354 # Replace the command with its contents
355 with open(rsp, encoding='utf-8') as f:
356 each['command'] = compiler + ' ' + f.read()
357 return contents
358
359 def get_meson_log_raw(self):
360 with self._open_meson_log() as f:
361 return f.read()
362
363 def get_meson_log(self):
364 with self._open_meson_log() as f:
365 return f.readlines()
366
367 def get_meson_log_compiler_checks(self):
368 '''
369 Fetch a list command-lines run by meson for compiler checks.
370 Each command-line is returned as a list of arguments.
371 '''
372 prefix = 'Command line: `'
373 suffix = '` -> 0\n'
374 with self._open_meson_log() as log:
375 cmds = [split_args(l[len(prefix):-len(suffix)]) for l in log if l.startswith(prefix)]
376 return cmds
377
378 def get_meson_log_sanitychecks(self):
379 '''
380 Same as above, but for the sanity checks that were run
381 '''
382 prefix = 'Sanity check compiler command line:'
383 with self._open_meson_log() as log:
384 cmds = [l[len(prefix):].split() for l in log if l.startswith(prefix)]
385 return cmds
386
387 def introspect(self, args):
388 if isinstance(args, str):
389 args = [args]
390 out = subprocess.check_output(self.mintro_command + args + [self.builddir],
391 encoding='utf-8', universal_newlines=True)
392 return json.loads(out)
393
394 def introspect_directory(self, directory, args):
395 if isinstance(args, str):
396 args = [args]
397 out = subprocess.check_output(self.mintro_command + args + [directory],
398 encoding='utf-8', universal_newlines=True)
399 try:
400 obj = json.loads(out)
401 except Exception as e:
402 print(out)
403 raise e
404 return obj
405
406 def assertPathEqual(self, path1, path2):
407 '''
408 Handles a lot of platform-specific quirks related to paths such as
409 separator, case-sensitivity, etc.
410 '''
411 self.assertEqual(PurePath(path1), PurePath(path2))
412
413 def assertPathListEqual(self, pathlist1, pathlist2):
414 self.assertEqual(len(pathlist1), len(pathlist2))
415 worklist = list(zip(pathlist1, pathlist2))
416 for i in worklist:
417 if i[0] is None:
418 self.assertEqual(i[0], i[1])
419 else:
420 self.assertPathEqual(i[0], i[1])
421
422 def assertPathBasenameEqual(self, path, basename):
423 msg = f'{path!r} does not end with {basename!r}'
424 # We cannot use os.path.basename because it returns '' when the path
425 # ends with '/' for some silly reason. This is not how the UNIX utility
426 # `basename` works.
427 path_basename = PurePath(path).parts[-1]
428 self.assertEqual(PurePath(path_basename), PurePath(basename), msg)
429
430 def assertReconfiguredBuildIsNoop(self):
431 'Assert that we reconfigured and then there was nothing to do'
432 ret = self.build(stderr=False)
433 self.assertIn('The Meson build system', ret)
434 if self.backend is Backend.ninja:
435 for line in ret.split('\n'):
436 if line in self.no_rebuild_stdout:
437 break
438 else:
439 raise AssertionError('build was reconfigured, but was not no-op')
440 elif self.backend is Backend.vs:
441 # Ensure that some target said that no rebuild was done
442 # XXX: Note CustomBuild did indeed rebuild, because of the regen checker!
443 self.assertIn('ClCompile:\n All outputs are up-to-date.', ret)
444 self.assertIn('Link:\n All outputs are up-to-date.', ret)
445 # Ensure that no targets were built
446 self.assertNotRegex(ret, re.compile('ClCompile:\n [^\n]*cl', flags=re.IGNORECASE))
447 self.assertNotRegex(ret, re.compile('Link:\n [^\n]*link', flags=re.IGNORECASE))
448 elif self.backend is Backend.xcode:
449 raise SkipTest('Please help us fix this test on the xcode backend')
450 else:
451 raise RuntimeError(f'Invalid backend: {self.backend.name!r}')
452
453 def assertBuildIsNoop(self):
454 ret = self.build(stderr=False)
455 if self.backend is Backend.ninja:
456 self.assertIn(ret.split('\n')[-2], self.no_rebuild_stdout)
457 elif self.backend is Backend.vs:
458 # Ensure that some target of each type said that no rebuild was done
459 # We always have at least one CustomBuild target for the regen checker
460 self.assertIn('CustomBuild:\n All outputs are up-to-date.', ret)
461 self.assertIn('ClCompile:\n All outputs are up-to-date.', ret)
462 self.assertIn('Link:\n All outputs are up-to-date.', ret)
463 # Ensure that no targets were built
464 self.assertNotRegex(ret, re.compile('CustomBuild:\n [^\n]*cl', flags=re.IGNORECASE))
465 self.assertNotRegex(ret, re.compile('ClCompile:\n [^\n]*cl', flags=re.IGNORECASE))
466 self.assertNotRegex(ret, re.compile('Link:\n [^\n]*link', flags=re.IGNORECASE))
467 elif self.backend is Backend.xcode:
468 raise SkipTest('Please help us fix this test on the xcode backend')
469 else:
470 raise RuntimeError(f'Invalid backend: {self.backend.name!r}')
471
472 def assertRebuiltTarget(self, target):
473 ret = self.build()
474 if self.backend is Backend.ninja:
475 self.assertIn(f'Linking target {target}', ret)
476 elif self.backend is Backend.vs:
477 # Ensure that this target was rebuilt
478 linkre = re.compile('Link:\n [^\n]*link[^\n]*' + target, flags=re.IGNORECASE)
479 self.assertRegex(ret, linkre)
480 elif self.backend is Backend.xcode:
481 raise SkipTest('Please help us fix this test on the xcode backend')
482 else:
483 raise RuntimeError(f'Invalid backend: {self.backend.name!r}')
484
485 @staticmethod
486 def get_target_from_filename(filename):
487 base = os.path.splitext(filename)[0]
488 if base.startswith(('lib', 'cyg')):
489 return base[3:]
490 return base
491
492 def assertBuildRelinkedOnlyTarget(self, target):
493 ret = self.build()
494 if self.backend is Backend.ninja:
495 linked_targets = []
496 for line in ret.split('\n'):
497 if 'Linking target' in line:
498 fname = line.rsplit('target ')[-1]
499 linked_targets.append(self.get_target_from_filename(fname))
500 self.assertEqual(linked_targets, [target])
501 elif self.backend is Backend.vs:
502 # Ensure that this target was rebuilt
503 linkre = re.compile(r'Link:\n [^\n]*link.exe[^\n]*/OUT:".\\([^"]*)"', flags=re.IGNORECASE)
504 matches = linkre.findall(ret)
505 self.assertEqual(len(matches), 1, msg=matches)
506 self.assertEqual(self.get_target_from_filename(matches[0]), target)
507 elif self.backend is Backend.xcode:
508 raise SkipTest('Please help us fix this test on the xcode backend')
509 else:
510 raise RuntimeError(f'Invalid backend: {self.backend.name!r}')
511
512 def assertPathExists(self, path):
513 m = f'Path {path!r} should exist'
514 self.assertTrue(os.path.exists(path), msg=m)
515
516 def assertPathDoesNotExist(self, path):
517 m = f'Path {path!r} should not exist'
518 self.assertFalse(os.path.exists(path), msg=m)
519
520 def assertLength(self, val, length):
521 assert len(val) == length, f'{val} is not length {length}'
522
523 def copy_srcdir(self, srcdir: str) -> str:
524 """Copies a source tree and returns that copy.
525
526 ensures that the copied tree is deleted after running.
527
528 :param srcdir: The location of the source tree to copy
529 :return: The location of the copy
530 """
531 dest = tempfile.mkdtemp()
532 self.addCleanup(windows_proof_rmtree, dest)
533
534 # shutil.copytree expects the destination directory to not exist, Once
535 # python 3.8 is required the `dirs_exist_ok` parameter negates the need
536 # for this
537 dest = os.path.join(dest, 'subdir')
538
539 shutil.copytree(srcdir, dest)
540
541 return dest