Debian Codegraph @

unittests/allplatformstests.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2016-2021 The Meson development team
3 # Copyright © 2023-2026 Intel Corporation
4
5 from __future__ import annotations
6 import itertools
7 import subprocess
8 import re
9 import json
10 import tempfile
11 import textwrap
12 import os
13 import shutil
14 import platform
15 import pickle
16 import zipfile, tarfile
17 import sys
18 import sysconfig
19 from unittest import mock, SkipTest, skipIf, skipUnless, expectedFailure
20 from contextlib import contextmanager
21 from glob import glob
22 from pathlib import (PurePath, Path)
23 import typing as T
24
25 from mesonbuild.build import BuildProject
26 import mesonbuild.mlog
27 import mesonbuild.depfile
28 import mesonbuild.dependencies.base
29 import mesonbuild.dependencies.factory
30 import mesonbuild.envconfig
31 import mesonbuild.environment
32 import mesonbuild.coredata
33 import mesonbuild.machinefile
34 import mesonbuild.modules.gnome
35 import mesonbuild.tooldetect
36 from mesonbuild.mesonlib import (
37 DirectoryLock, DirectoryLockAction, MachineChoice, is_windows, is_osx, is_cygwin, is_dragonflybsd,
38 is_sunos, windows_proof_rmtree, python_command, version_compare, split_args, quote_arg,
39 relpath, is_linux, git, search_version, do_conf_file, do_conf_str, default_prefix,
40 SubProject, MesonException, EnvironmentException,
41 windows_proof_rm, first
42 )
43 from mesonbuild.options import OptionKey
44 from mesonbuild.programs import ExternalProgram
45
46 from mesonbuild.compilers.mixins.clang import ClangCompiler
47 from mesonbuild.compilers.mixins.elbrus import ElbrusCompiler
48 from mesonbuild.compilers.mixins.gnu import GnuCompiler
49 from mesonbuild.compilers.mixins.intel import IntelGnuLikeCompiler
50 from mesonbuild.compilers.c import VisualStudioCCompiler, ClangClCCompiler
51 from mesonbuild.compilers.cpp import VisualStudioCPPCompiler, ClangClCPPCompiler
52 from mesonbuild.compilers import (
53 detect_static_linker, detect_c_compiler, compiler_from_language,
54 detect_compiler_for
55 )
56 from mesonbuild.linkers import linkers
57
58 from mesonbuild.dependencies.pkgconfig import PkgConfigDependency
59 from mesonbuild.build import Target, ConfigurationData, Executable, SharedLibrary, StaticLibrary
60 from mesonbuild import mtest
61 import mesonbuild.modules.pkgconfig
62 from mesonbuild.scripts import destdir_join
63
64 from mesonbuild.wrap.wrap import PackageDefinition, WrapException
65
66 from run_tests import (
67 Backend, exe_suffix, get_fake_env, get_convincing_fake_env_and_cc
68 )
69
70 from .baseplatformtests import BasePlatformTests
71 from .helpers import *
72
73 if T.TYPE_CHECKING:
74 from mesonbuild.compilers.compilers import Language
75 from mesonbuild.environment import Environment
76
77 UNIT_MACHINEFILE_DIR = Path(__file__).parent / 'machinefiles'
78
79 @contextmanager
80 def temp_filename():
81 '''A context manager which provides a filename to an empty temporary file.
82
83 On exit the file will be deleted.
84 '''
85
86 fd, filename = tempfile.mkstemp()
87 os.close(fd)
88 try:
89 yield filename
90 finally:
91 try:
92 os.remove(filename)
93 except OSError:
94 pass
95
96 def git_init(project_dir):
97 # If a user has git configuration init.defaultBranch set we want to override that
98 with tempfile.TemporaryDirectory() as d:
99 out = git(['--version'], str(d))[1]
100 if version_compare(search_version(out), '>= 2.28'):
101 extra_cmd = ['--initial-branch', 'master']
102 else:
103 extra_cmd = []
104
105 subprocess.check_call(['git', 'init'] + extra_cmd, cwd=project_dir, stdout=subprocess.DEVNULL)
106 subprocess.check_call(['git', 'config',
107 'user.name', 'Author Person'], cwd=project_dir)
108 subprocess.check_call(['git', 'config',
109 'user.email', '[email protected]'], cwd=project_dir)
110 _git_add_all(project_dir)
111
112 def _git_add_all(project_dir):
113 subprocess.check_call('git add *', cwd=project_dir, shell=True,
114 stdout=subprocess.DEVNULL)
115 subprocess.check_call(['git', 'commit', '--no-gpg-sign', '-a', '-m', 'I am a project'], cwd=project_dir,
116 stdout=subprocess.DEVNULL)
117
118 class AllPlatformTests(BasePlatformTests):
119 '''
120 Tests that should run on all platforms
121 '''
122
123 def test_default_options_prefix(self):
124 '''
125 Tests that setting a prefix in default_options in project() works.
126 Can't be an ordinary test because we pass --prefix to meson there.
127 https://github.com/mesonbuild/meson/issues/1349
128 '''
129 testdir = os.path.join(self.common_test_dir, '87 default options')
130 self.init(testdir, default_args=False, inprocess=True)
131 opts = self.introspect('--buildoptions')
132 for opt in opts:
133 if opt['name'] == 'prefix':
134 prefix = opt['value']
135 break
136 else:
137 raise self.fail('Did not find option "prefix"')
138 self.assertEqual(prefix, '/absoluteprefix')
139
140 def test_do_conf_file_preserve_newlines(self):
141
142 def conf_file(in_data, confdata):
143 with temp_filename() as fin:
144 with open(fin, 'wb') as fobj:
145 fobj.write(in_data.encode('utf-8'))
146 with temp_filename() as fout:
147 do_conf_file(fin, fout, confdata, 'meson')
148 with open(fout, 'rb') as fobj:
149 return fobj.read().decode('utf-8')
150
151 confdata = {'VAR': ('foo', 'bar')}
152 self.assertEqual(conf_file('@VAR@\n@VAR@\n', confdata), 'foo\nfoo\n')
153 self.assertEqual(conf_file('@VAR@\r\n@VAR@\r\n', confdata), 'foo\r\nfoo\r\n')
154
155 def test_do_conf_file_by_format(self):
156 def conf_str(in_data, confdata, vformat):
157 (result, missing_variables, confdata_useless) = do_conf_str('configuration_file', in_data, confdata, variable_format = vformat)
158 return '\n'.join(result)
159
160 def check_meson_format(confdata, result):
161 self.assertEqual(conf_str(['#mesondefine VAR'], confdata, 'meson'), result)
162
163 def check_cmake_format_simple(confdata, result):
164 self.assertEqual(conf_str(['#cmakedefine VAR'], confdata, 'cmake'), result)
165
166 def check_cmake_formats_full(confdata, result):
167 self.assertEqual(conf_str(['#cmakedefine VAR ${VAR}'], confdata, 'cmake'), result)
168 self.assertEqual(conf_str(['#cmakedefine VAR @VAR@'], confdata, 'cmake@'), result)
169
170 def check_formats(confdata, result):
171 check_meson_format(confdata, result)
172 check_cmake_formats_full(confdata, result)
173
174 confdata = ConfigurationData()
175 # Key error as they do not exists
176 check_formats(confdata, '/* #undef VAR */\n')
177
178 # Check boolean
179 confdata.values = {'VAR': (False, 'description')}
180 check_meson_format(confdata, '#undef VAR\n')
181 check_cmake_formats_full(confdata, '/* #undef VAR */\n')
182
183 confdata.values = {'VAR': (True, 'description')}
184 check_meson_format(confdata, '#define VAR\n')
185 check_cmake_format_simple(confdata, '#define VAR\n')
186 check_cmake_formats_full(confdata, '#define VAR 1\n')
187
188 # Check string
189 confdata.values = {'VAR': ('value', 'description')}
190 check_formats(confdata, '#define VAR value\n')
191
192 # Check integer
193 confdata.values = {'VAR': (10, 'description')}
194 check_formats(confdata, '#define VAR 10\n')
195
196 # Checking if cmakedefine behaves as it does with cmake
197 confdata.values = {'VAR': ("var", 'description')}
198 self.assertEqual(conf_str(['#cmakedefine VAR @VAR@'], confdata, 'cmake@'), '#define VAR var\n')
199
200 confdata.values = {'VAR': (True, 'description')}
201 self.assertEqual(conf_str(['#cmakedefine01 VAR'], confdata, 'cmake'), '#define VAR 1\n')
202
203 confdata.values = {'VAR': (0, 'description')}
204 self.assertEqual(conf_str(['#cmakedefine01 VAR'], confdata, 'cmake'), '#define VAR 0\n')
205 confdata.values = {'VAR': (False, 'description')}
206 self.assertEqual(conf_str(['#cmakedefine01 VAR'], confdata, 'cmake'), '#define VAR 0\n')
207
208 confdata.values = {}
209 self.assertEqual(conf_str(['#cmakedefine01 VAR'], confdata, 'cmake'), '#define VAR 0\n')
210 self.assertEqual(conf_str(['#cmakedefine VAR @VAR@'], confdata, 'cmake@'), '/* #undef VAR */\n')
211
212 confdata.values = {'VAR': (5, 'description')}
213 self.assertEqual(conf_str(['#cmakedefine VAR'], confdata, 'cmake'), '#define VAR\n')
214
215 # Check multiple string with cmake formats
216 confdata.values = {'VAR': ('value', 'description')}
217 self.assertEqual(conf_str(['#cmakedefine VAR xxx @VAR@ yyy @VAR@'], confdata, 'cmake@'), '#define VAR xxx value yyy value\n')
218 self.assertEqual(conf_str(['#define VAR xxx @VAR@ yyy @VAR@'], confdata, 'cmake@'), '#define VAR xxx value yyy value')
219 self.assertEqual(conf_str(['#cmakedefine VAR xxx ${VAR} yyy ${VAR}'], confdata, 'cmake'), '#define VAR xxx value yyy value\n')
220 self.assertEqual(conf_str(['#define VAR xxx ${VAR} yyy ${VAR}'], confdata, 'cmake'), '#define VAR xxx value yyy value')
221
222 # Handles meson format exceptions
223 # Unknown format
224 self.assertRaises(MesonException, conf_str, ['#mesondefine VAR xxx'], confdata, 'unknown_format')
225 # More than 2 params in mesondefine
226 self.assertRaises(MesonException, conf_str, ['#mesondefine VAR xxx'], confdata, 'meson')
227 # Mismatched line with format
228 self.assertRaises(MesonException, conf_str, ['#cmakedefine VAR'], confdata, 'meson')
229 self.assertRaises(MesonException, conf_str, ['#mesondefine VAR'], confdata, 'cmake')
230 self.assertRaises(MesonException, conf_str, ['#mesondefine VAR'], confdata, 'cmake@')
231 # Dict value in confdata
232 confdata.values = {'VAR': (['value'], 'description')}
233 self.assertRaises(MesonException, conf_str, ['#mesondefine VAR'], confdata, 'meson')
234
235 def test_cmake_configuration(self):
236 if self.backend is not Backend.ninja:
237 raise SkipTest('ninja backend needed to configure with cmake')
238
239 cmake = ExternalProgram('cmake')
240 if not cmake.found():
241 raise SkipTest('cmake not available')
242
243 cmake_version = cmake.get_version()
244 if not version_compare(cmake_version, '>=3.13.5'):
245 raise SkipTest('cmake is too old')
246
247 with tempfile.TemporaryDirectory() as tmpdir:
248 srcdir = os.path.join(tmpdir, 'src')
249
250 shutil.copytree(os.path.join(self.src_root, 'test cases', 'common', '14 configure file'), srcdir)
251 self.init(srcdir)
252
253 cmake_builddir = os.path.join(srcdir, "cmake_builddir")
254 self.assertNotEqual(self.builddir, cmake_builddir)
255 self._run([cmake.path, '-G', 'Ninja', '-S', srcdir, '-B', cmake_builddir])
256
257 header_list = [
258 'config7.h',
259 'config10.h',
260 ]
261
262 for header in header_list:
263 meson_header = ""
264 cmake_header = ""
265
266 with open(os.path.join(self.builddir, header), encoding='utf-8') as f:
267 meson_header = f.read()
268
269 cmake_header_path = os.path.join(cmake_builddir, header)
270 with open(os.path.join(cmake_builddir, header), encoding='utf-8') as f:
271 cmake_header = f.read()
272
273 self.assertTrue(cmake_header, f'cmake generated header {header} is empty')
274 self.assertEqual(cmake_header, meson_header)
275
276 def test_absolute_prefix_libdir(self):
277 '''
278 Tests that setting absolute paths for --prefix and --libdir work. Can't
279 be an ordinary test because these are set via the command-line.
280 https://github.com/mesonbuild/meson/issues/1341
281 https://github.com/mesonbuild/meson/issues/1345
282 '''
283 testdir = os.path.join(self.common_test_dir, '87 default options')
284 # on Windows, /someabs is *not* an absolute path
285 prefix = 'x:/someabs' if is_windows() else '/someabs'
286 libdir = 'libdir'
287 extra_args = ['--prefix=' + prefix,
288 # This can just be a relative path, but we want to test
289 # that passing this as an absolute path also works
290 '--libdir=' + prefix + '/' + libdir]
291 self.init(testdir, extra_args=extra_args, default_args=False)
292 opts = self.introspect('--buildoptions')
293 for opt in opts:
294 if opt['name'] == 'prefix':
295 self.assertEqual(prefix, opt['value'])
296 elif opt['name'] == 'libdir':
297 self.assertEqual(libdir, opt['value'])
298
299 def test_libdir_can_be_outside_prefix(self):
300 '''
301 Tests that libdir is allowed to be outside prefix.
302 Must be a unit test for obvious reasons.
303 '''
304 testdir = os.path.join(self.common_test_dir, '1 trivial')
305 # libdir being inside prefix is ok
306 if is_windows():
307 args = ['--prefix', 'x:/opt', '--libdir', 'x:/opt/lib32']
308 else:
309 args = ['--prefix', '/opt', '--libdir', '/opt/lib32']
310 self.init(testdir, extra_args=args)
311 self.wipe()
312 # libdir not being inside prefix is ok too
313 if is_windows():
314 args = ['--prefix', 'x:/usr', '--libdir', 'x:/opt/lib32']
315 else:
316 args = ['--prefix', '/usr', '--libdir', '/opt/lib32']
317 self.init(testdir, extra_args=args)
318 self.wipe()
319 # libdir can be outside prefix even when set via mesonconf
320 self.init(testdir)
321 if is_windows():
322 self.setconf('-Dlibdir=x:/opt', will_build=False)
323 else:
324 self.setconf('-Dlibdir=/opt', will_build=False)
325
326 def test_prefix_dependent_defaults(self):
327 '''
328 Tests that configured directory paths are set to prefix dependent
329 defaults.
330 '''
331 testdir = os.path.join(self.common_test_dir, '1 trivial')
332 expected = {
333 '/opt': {'prefix': '/opt',
334 'bindir': 'bin',
335 'datadir': 'share',
336 'includedir': 'include',
337 'infodir': 'share/info',
338 'libexecdir': 'libexec',
339 'localedir': 'share/locale',
340 'localstatedir': 'var',
341 'mandir': 'share/man',
342 'sbindir': 'sbin',
343 'sharedstatedir': 'com',
344 'sysconfdir': 'etc',
345 },
346 '/usr': {'prefix': '/usr',
347 'bindir': 'bin',
348 'datadir': 'share',
349 'includedir': 'include',
350 'infodir': 'share/info',
351 'libexecdir': 'libexec',
352 'localedir': 'share/locale',
353 'localstatedir': '/var',
354 'mandir': 'share/man',
355 'sbindir': 'sbin',
356 'sharedstatedir': '/var/lib',
357 'sysconfdir': '/etc',
358 },
359 '/usr/local': {'prefix': '/usr/local',
360 'bindir': 'bin',
361 'datadir': 'share',
362 'includedir': 'include',
363 'infodir': 'share/info',
364 'libexecdir': 'libexec',
365 'localedir': 'share/locale',
366 'localstatedir': '/var/local',
367 'mandir': 'share/man',
368 'sbindir': 'sbin',
369 'sharedstatedir': '/var/local/lib',
370 'sysconfdir': 'etc',
371 },
372 # N.B. We don't check 'libdir' as it's platform dependent, see
373 # default_libdir():
374 }
375
376 if default_prefix() == '/usr/local':
377 expected[None] = expected['/usr/local']
378
379 for prefix in expected:
380 args = []
381 if prefix:
382 args += ['--prefix', prefix]
383 self.init(testdir, extra_args=args, default_args=False)
384 opts = self.introspect('--buildoptions')
385 for opt in opts:
386 name = opt['name']
387 value = opt['value']
388 if name in expected[prefix]:
389 with self.subTest(prefix=prefix, option=name):
390 self.assertEqual(value, expected[prefix][name], f'For option {name} and prefix {prefix}.')
391 self.wipe()
392
393 def test_default_options_prefix_dependent_defaults(self):
394 '''
395 Tests that setting a prefix in default_options in project() sets prefix
396 dependent defaults for other options, and that those defaults can
397 be overridden in default_options or by the command line.
398 '''
399 testdir = os.path.join(self.common_test_dir, '163 default options prefix dependent defaults')
400 expected = {
401 '':
402 {'prefix': '/usr',
403 'sysconfdir': '/etc',
404 'localstatedir': '/var',
405 'sharedstatedir': '/sharedstate'},
406 '--prefix=/usr':
407 {'prefix': '/usr',
408 'sysconfdir': '/etc',
409 'localstatedir': '/var',
410 'sharedstatedir': '/sharedstate'},
411
412 '--sharedstatedir=/var/state':
413 {'prefix': '/usr',
414 'sysconfdir': '/etc',
415 'localstatedir': '/var',
416 'sharedstatedir': '/var/state'},
417
418 '--sharedstatedir=/var/state --prefix=/usr --sysconfdir=sysconf':
419 {'prefix': '/usr',
420 'sysconfdir': 'sysconf',
421 'localstatedir': '/var',
422 'sharedstatedir': '/var/state'},
423 }
424 for argument_string, expected_values in expected.items():
425 self.init(testdir, extra_args=argument_string.split(), default_args=False)
426 opts = self.introspect('--buildoptions')
427 for opt in opts:
428 name = opt['name']
429 value = opt['value']
430 if name in expected_values:
431 self.assertEqual(value, expected_values[name], f'For option {name}, Meson arg: {argument_string}')
432 self.wipe()
433
434 def test_clike_get_library_dirs(self):
435 env = get_fake_env()
436 cc = detect_c_compiler(env, MachineChoice.HOST)
437 for d in cc.get_library_dirs(env):
438 self.assertTrue(os.path.exists(d))
439 self.assertTrue(os.path.isdir(d))
440 self.assertTrue(os.path.isabs(d))
441
442 def test_static_library_overwrite(self):
443 '''
444 Tests that static libraries are never appended to, always overwritten.
445 Has to be a unit test because this involves building a project,
446 reconfiguring, and building it again so that `ar` is run twice on the
447 same static library.
448 https://github.com/mesonbuild/meson/issues/1355
449 '''
450 testdir = os.path.join(self.common_test_dir, '3 static')
451 env = get_fake_env(testdir, self.builddir, self.prefix)
452 cc = detect_c_compiler(env, MachineChoice.HOST)
453 static_linker = detect_static_linker(env, cc)
454 if is_windows():
455 raise SkipTest('https://github.com/mesonbuild/meson/issues/1526')
456 if not isinstance(static_linker, linkers.ArLinker):
457 raise SkipTest('static linker is not `ar`')
458 # Configure
459 self.init(testdir)
460 # Get name of static library
461 targets = self.introspect('--targets')
462 self.assertGreaterEqual(len(targets), 1)
463 libname = targets[0]['filename'][0]
464 # Build and get contents of static library
465 self.build()
466 before = self._run(['ar', 't', os.path.join(self.builddir, libname)]).split()
467 # Filter out non-object-file contents
468 before = [f for f in before if f.endswith(('.o', '.obj'))]
469 # Static library should contain only one object
470 self.assertEqual(len(before), 1, msg=before)
471 # Change the source to be built into the static library
472 self.setconf('-Dsource=libfile2.c')
473 self.build()
474 after = self._run(['ar', 't', os.path.join(self.builddir, libname)]).split()
475 # Filter out non-object-file contents
476 after = [f for f in after if f.endswith(('.o', '.obj'))]
477 # Static library should contain only one object
478 self.assertEqual(len(after), 1, msg=after)
479 # and the object must have changed
480 self.assertNotEqual(before, after)
481
482 def test_static_compile_order(self):
483 '''
484 Test that the order of files in a compiler command-line while compiling
485 and linking statically is deterministic. This can't be an ordinary test
486 case because we need to inspect the compiler database.
487 https://github.com/mesonbuild/meson/pull/951
488 '''
489 testdir = os.path.join(self.common_test_dir, '5 linkstatic')
490 self.init(testdir)
491 compdb = self.get_compdb()
492 # Rules will get written out in this order
493 self.assertTrue(compdb[0]['file'].endswith("libfile.c"))
494 self.assertTrue(compdb[1]['file'].endswith("libfile2.c"))
495 self.assertTrue(compdb[2]['file'].endswith("libfile3.c"))
496 self.assertTrue(compdb[3]['file'].endswith("libfile4.c"))
497 # FIXME: We don't have access to the linker command
498
499 def test_replace_unencodable_xml_chars(self):
500 '''
501 Test that unencodable xml chars are replaced with their
502 printable representation
503 https://github.com/mesonbuild/meson/issues/9894
504 '''
505 # Create base string(\nHello Meson\n) to see valid chars are not replaced
506 base_string_invalid = '\n\x48\x65\x6c\x6c\x6f\x20\x4d\x65\x73\x6f\x6e\n'
507 base_string_valid = '\nHello Meson\n'
508 # Create invalid input from all known unencodable chars
509 invalid_string = (
510 '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0b\x0c\x0e\x0f\x10\x11'
511 '\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x7f'
512 '\x80\x81\x82\x83\x84\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f'
513 '\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e'
514 '\x9f\ufdd0\ufdd1\ufdd2\ufdd3\ufdd4\ufdd5\ufdd6\ufdd7\ufdd8'
515 '\ufdd9\ufdda\ufddb\ufddc\ufddd\ufdde\ufddf\ufde0\ufde1'
516 '\ufde2\ufde3\ufde4\ufde5\ufde6\ufde7\ufde8\ufde9\ufdea'
517 '\ufdeb\ufdec\ufded\ufdee\ufdef\ufffe\uffff')
518 if sys.maxunicode >= 0x10000:
519 invalid_string = invalid_string + (
520 '\U0001fffe\U0001ffff\U0002fffe\U0002ffff'
521 '\U0003fffe\U0003ffff\U0004fffe\U0004ffff'
522 '\U0005fffe\U0005ffff\U0006fffe\U0006ffff'
523 '\U0007fffe\U0007ffff\U0008fffe\U0008ffff'
524 '\U0009fffe\U0009ffff\U000afffe\U000affff'
525 '\U000bfffe\U000bffff\U000cfffe\U000cffff'
526 '\U000dfffe\U000dffff\U000efffe\U000effff'
527 '\U000ffffe\U000fffff\U0010fffe\U0010ffff')
528
529 valid_string = base_string_valid + repr(invalid_string)[1:-1] + base_string_valid
530 invalid_string = base_string_invalid + invalid_string + base_string_invalid
531 fixed_string = mtest.replace_unencodable_xml_chars(invalid_string)
532 self.assertEqual(fixed_string, valid_string)
533
534 @skipIfNoExecutable('xmllint')
535 def test_replace_unencodable_xml_chars_unit(self):
536 '''
537 Test that unencodable xml chars are replaced with their
538 printable representation
539 https://github.com/mesonbuild/meson/issues/9894
540 '''
541 testdir = os.path.join(self.unit_test_dir, '111 replace unencodable xml chars')
542 self.init(testdir)
543 tests_command_output = self.run_tests()
544 junit_xml_logs = Path(self.logdir, 'testlog.junit.xml')
545 subprocess.run(['xmllint', junit_xml_logs], check=True)
546 # Ensure command output and JSON / text logs are not mangled.
547 raw_output_sample = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0b'
548 assert raw_output_sample in tests_command_output
549 text_log = Path(self.logdir, 'testlog.txt').read_text(encoding='utf-8')
550 assert raw_output_sample in text_log
551 json_log = json.loads(Path(self.logdir, 'testlog.json').read_bytes())
552 assert raw_output_sample in json_log['stdout']
553
554 def test_run_target_files_path(self):
555 '''
556 Test that run_targets are run from the correct directory
557 https://github.com/mesonbuild/meson/issues/957
558 '''
559 testdir = os.path.join(self.common_test_dir, '51 run target')
560 self.init(testdir)
561 self.run_target('check_exists')
562 self.run_target('check-env')
563 self.run_target('check-env-ct')
564
565 def test_run_target_subdir(self):
566 '''
567 Test that run_targets are run from the correct directory
568 https://github.com/mesonbuild/meson/issues/957
569 '''
570 testdir = os.path.join(self.common_test_dir, '51 run target')
571 self.init(testdir)
572 self.run_target('textprinter')
573
574 def test_install_introspection(self):
575 '''
576 Tests that the Meson introspection API exposes install filenames correctly
577 https://github.com/mesonbuild/meson/issues/829
578 '''
579 if self.backend is not Backend.ninja:
580 raise SkipTest(f'{self.backend.name!r} backend can\'t install files')
581 testdir = os.path.join(self.common_test_dir, '8 install')
582 # sneak in a test that covers backend options...
583 self.init(testdir, extra_args=['-Dbackend_max_links=4'])
584 intro = self.introspect('--targets')
585 if intro[0]['type'] == 'executable':
586 intro = intro[::-1]
587 self.assertPathListEqual(intro[0]['install_filename'], ['/usr/lib/libstat.a'])
588 self.assertPathListEqual(intro[1]['install_filename'], ['/usr/bin/prog' + exe_suffix])
589
590 def test_install_subdir_introspection(self):
591 '''
592 Test that the Meson introspection API also contains subdir install information
593 https://github.com/mesonbuild/meson/issues/5556
594 '''
595 testdir = os.path.join(self.common_test_dir, '59 install subdir')
596 self.init(testdir)
597 intro = self.introspect('--installed')
598 expected = {
599 'nested_elided/sub': 'share',
600 'new_directory': 'share/new_directory',
601 'sub/sub1': 'share/sub1',
602 'sub1': 'share/sub1',
603 'sub2': 'share/sub2',
604 'sub3': '/usr/share/sub3',
605 'sub_elided': 'share',
606 'subdir/sub1': 'share/sub1',
607 'subdir/sub_elided': 'share',
608 }
609
610 self.assertEqual(len(intro), len(expected))
611
612 # Convert expected to PurePath
613 expected_converted = {PurePath(os.path.join(testdir, key)): PurePath(os.path.join(self.prefix, val)) for key, val in expected.items()}
614 intro_converted = {PurePath(key): PurePath(val) for key, val in intro.items()}
615
616 for src, dst in expected_converted.items():
617 self.assertIn(src, intro_converted)
618 self.assertEqual(dst, intro_converted[src])
619
620 def test_install_introspection_multiple_outputs(self):
621 '''
622 Tests that the Meson introspection API exposes multiple install filenames correctly without crashing
623 https://github.com/mesonbuild/meson/pull/4555
624
625 Reverted to the first file only because of https://github.com/mesonbuild/meson/pull/4547#discussion_r244173438
626 TODO Change the format to a list officially in a followup PR
627 '''
628 if self.backend is not Backend.ninja:
629 raise SkipTest(f'{self.backend.name!r} backend can\'t install files')
630 testdir = os.path.join(self.common_test_dir, '140 custom target multiple outputs')
631 self.init(testdir)
632 intro = self.introspect('--targets')
633 if intro[0]['type'] == 'executable':
634 intro = intro[::-1]
635 self.assertPathListEqual(intro[0]['install_filename'], ['/usr/include/diff.h', '/usr/bin/diff.sh'])
636 self.assertPathListEqual(intro[1]['install_filename'], ['/opt/same.h', '/opt/same.sh'])
637 self.assertPathListEqual(intro[2]['install_filename'], ['/usr/include/first.h', None])
638 self.assertPathListEqual(intro[3]['install_filename'], [None, '/usr/bin/second.sh'])
639
640 def read_install_logs(self):
641 # Find logged files and directories
642 with Path(self.builddir, 'meson-logs', 'install-log.txt').open(encoding='utf-8') as f:
643 return list(map(lambda l: Path(l.strip()),
644 filter(lambda l: not l.startswith('#'),
645 f.readlines())))
646
647 def test_install_log_content(self):
648 '''
649 Tests that the install-log.txt is consistent with the installed files and directories.
650 Specifically checks that the log file only contains one entry per file/directory.
651 https://github.com/mesonbuild/meson/issues/4499
652 '''
653 testdir = os.path.join(self.common_test_dir, '59 install subdir')
654 self.init(testdir)
655 self.install()
656 installpath = Path(self.installdir)
657 # Find installed files and directories
658 expected = {installpath: 0}
659 for name in installpath.rglob('*'):
660 expected[name] = 0
661 logged = self.read_install_logs()
662 for name in logged:
663 self.assertTrue(name in expected, f'Log contains extra entry {name}')
664 expected[name] += 1
665
666 for name, count in expected.items():
667 self.assertGreater(count, 0, f'Log is missing entry for {name}')
668 self.assertLess(count, 2, f'Log has multiple entries for {name}')
669
670 # Verify that with --dry-run we obtain the same logs but with nothing
671 # actually installed
672 windows_proof_rmtree(self.installdir)
673 self._run(self.meson_command + ['install', '--dry-run', '--destdir', self.installdir], workdir=self.builddir)
674 self.assertEqual(logged, self.read_install_logs())
675 self.assertFalse(os.path.exists(self.installdir))
676
677 # If destdir is relative to build directory it should install
678 # exactly the same files.
679 rel_installpath = os.path.relpath(self.installdir, self.builddir)
680 self._run(self.meson_command + ['install', '--dry-run', '--destdir', rel_installpath, '-C', self.builddir])
681 self.assertEqual(logged, self.read_install_logs())
682
683 def test_uninstall(self):
684 exename = os.path.join(self.installdir, 'usr/bin/prog' + exe_suffix)
685 dirname = os.path.join(self.installdir, 'usr/share/dir')
686 testdir = os.path.join(self.common_test_dir, '8 install')
687 self.init(testdir)
688 self.assertPathDoesNotExist(exename)
689 self.install()
690 self.assertPathExists(exename)
691 self.uninstall()
692 self.assertPathDoesNotExist(exename)
693 self.assertPathDoesNotExist(dirname)
694
695 def test_forcefallback(self):
696 testdir = os.path.join(self.unit_test_dir, '31 forcefallback')
697 self.init(testdir, extra_args=['--wrap-mode=forcefallback'])
698 self.build()
699 self.run_tests()
700
701 def test_implicit_forcefallback(self):
702 testdir = os.path.join(self.unit_test_dir, '95 implicit force fallback')
703 with self.assertRaises(subprocess.CalledProcessError):
704 self.init(testdir)
705 self.init(testdir, extra_args=['--wrap-mode=forcefallback'])
706 self.new_builddir()
707 self.init(testdir, extra_args=['--force-fallback-for=something'])
708
709 def test_nopromote(self):
710 testdir = os.path.join(self.common_test_dir, '98 subproject subdir')
711 with self.assertRaises(subprocess.CalledProcessError) as cm:
712 self.init(testdir, extra_args=['--wrap-mode=nopromote'])
713 self.assertIn('dependency subsub found: NO', cm.exception.stdout)
714
715 def test_force_fallback_for(self):
716 testdir = os.path.join(self.unit_test_dir, '31 forcefallback')
717 self.init(testdir, extra_args=['--force-fallback-for=zlib,foo,notfalse'])
718 self.build()
719 self.run_tests()
720
721 def test_force_fallback_for_nofallback(self):
722 testdir = os.path.join(self.unit_test_dir, '31 forcefallback')
723 self.init(testdir, extra_args=['--force-fallback-for=zlib,foo,notfalse', '--wrap-mode=nofallback'])
724 self.build()
725 self.run_tests()
726
727 def test_testrepeat(self):
728 testdir = os.path.join(self.common_test_dir, '206 tap tests')
729 self.init(testdir)
730 self.build()
731 self._run(self.mtest_command + ['--repeat=2'])
732
733 def test_verbose(self):
734 testdir = os.path.join(self.common_test_dir, '206 tap tests')
735 self.init(testdir)
736 self.build()
737 out = self._run(self.mtest_command + ['--suite', 'verbose'])
738 self.assertIn('1/1 subtest 1', out)
739
740 def test_long_output(self):
741 testdir = os.path.join(self.common_test_dir, '254 long output')
742 self.init(testdir)
743 self.build()
744 self.run_tests()
745
746 # Ensure lines are found from testlog.txt when not being verbose.
747
748 i = 1
749 with open(os.path.join(self.logdir, 'testlog.txt'), encoding='utf-8') as f:
750 line = f.readline()
751 while line and i < 100001:
752 if f'# Iteration {i} to stdout' in line:
753 i += 1
754 line = f.readline()
755 self.assertEqual(i, 100001)
756
757 i = 1
758 while line:
759 if f'# Iteration {i} to stderr' in line:
760 i += 1
761 line = f.readline()
762 self.assertEqual(i, 100001)
763
764 # Ensure lines are found from both testlog.txt and console when being verbose.
765
766 out = self._run(self.mtest_command + ['-v'])
767 i = 1
768 with open(os.path.join(self.logdir, 'testlog.txt'), encoding='utf-8') as f:
769 line = f.readline()
770 while line and i < 100001:
771 if f'# Iteration {i} to stdout' in line:
772 i += 1
773 line = f.readline()
774 self.assertEqual(i, 100001)
775
776 i = 1
777 while line:
778 if f'# Iteration {i} to stderr' in line:
779 i += 1
780 line = f.readline()
781 self.assertEqual(i, 100001)
782
783 lines = out.split('\n')
784 line_number = 0
785 i = 1
786 while line_number < len(lines) and i < 100001:
787 print('---> %s' % lines[line_number])
788 if f'# Iteration {i} to stdout' in lines[line_number]:
789 i += 1
790 line_number += 1
791 self.assertEqual(i, 100001)
792
793 line_number = 0
794 i = 1
795 while line_number < len(lines):
796 if f'# Iteration {i} to stderr' in lines[line_number]:
797 i += 1
798 line_number += 1
799 self.assertEqual(i, 100001)
800
801 @skipIfNoExecutable('valgrind')
802 def test_testsetups(self):
803 testdir = os.path.join(self.unit_test_dir, '2 testsetups')
804 self.init(testdir)
805 self.build()
806 # Run tests without setup
807 self.run_tests()
808 with open(os.path.join(self.logdir, 'testlog.txt'), encoding='utf-8') as f:
809 basic_log = f.read()
810 # Run buggy test with setup that has env that will make it fail
811 self.assertRaises(subprocess.CalledProcessError,
812 self._run, self.mtest_command + ['--setup=valgrind'])
813 with open(os.path.join(self.logdir, 'testlog-valgrind.txt'), encoding='utf-8') as f:
814 vg_log = f.read()
815 self.assertNotIn('TEST_ENV is set', basic_log)
816 self.assertNotIn('Memcheck', basic_log)
817 self.assertIn('TEST_ENV is set', vg_log)
818 self.assertIn('Memcheck', vg_log)
819 # Run buggy test with setup without env that will pass
820 self._run(self.mtest_command + ['--setup=wrapper'])
821 # Setup with no properties works
822 self._run(self.mtest_command + ['--setup=empty'])
823 # Setup with only env works
824 self._run(self.mtest_command + ['--setup=onlyenv'])
825 self._run(self.mtest_command + ['--setup=onlyenv2'])
826 self._run(self.mtest_command + ['--setup=onlyenv3'])
827 # Setup with only a timeout works
828 self._run(self.mtest_command + ['--setup=timeout'])
829 # Setup that does not define a wrapper works with --wrapper
830 self._run(self.mtest_command + ['--setup=timeout', '--wrapper', shutil.which('valgrind')])
831 # Setup that skips test works
832 self._run(self.mtest_command + ['--setup=good'])
833 with open(os.path.join(self.logdir, 'testlog-good.txt'), encoding='utf-8') as f:
834 exclude_suites_log = f.read()
835 self.assertNotIn('buggy', exclude_suites_log)
836 # --suite overrides add_test_setup(exclude_suites)
837 self._run(self.mtest_command + ['--setup=good', '--suite', 'buggy'])
838 with open(os.path.join(self.logdir, 'testlog-good.txt'), encoding='utf-8') as f:
839 include_suites_log = f.read()
840 self.assertIn('buggy', include_suites_log)
841
842 def test_testsetup_selection(self):
843 testdir = os.path.join(self.unit_test_dir, '14 testsetup selection')
844 self.init(testdir)
845 self.build()
846
847 # Run tests without setup
848 self.run_tests()
849
850 self.assertRaises(subprocess.CalledProcessError, self._run, self.mtest_command + ['--setup=missingfromfoo'])
851 self._run(self.mtest_command + ['--setup=missingfromfoo', '--no-suite=foo:'])
852
853 self._run(self.mtest_command + ['--setup=worksforall'])
854 self._run(self.mtest_command + ['--setup=main:worksforall'])
855
856 self.assertRaises(subprocess.CalledProcessError, self._run,
857 self.mtest_command + ['--setup=onlyinbar'])
858 self.assertRaises(subprocess.CalledProcessError, self._run,
859 self.mtest_command + ['--setup=onlyinbar', '--no-suite=main:'])
860 self._run(self.mtest_command + ['--setup=onlyinbar', '--no-suite=main:', '--no-suite=foo:'])
861 self._run(self.mtest_command + ['--setup=bar:onlyinbar'])
862 self.assertRaises(subprocess.CalledProcessError, self._run,
863 self.mtest_command + ['--setup=foo:onlyinbar'])
864 self.assertRaises(subprocess.CalledProcessError, self._run,
865 self.mtest_command + ['--setup=main:onlyinbar'])
866
867 def test_testsetup_default(self):
868 testdir = os.path.join(self.unit_test_dir, '48 testsetup default')
869 self.init(testdir)
870 self.build()
871
872 # Run tests without --setup will cause the default setup to be used
873 self.run_tests()
874 with open(os.path.join(self.logdir, 'testlog.txt'), encoding='utf-8') as f:
875 default_log = f.read()
876
877 # Run tests with explicitly using the same setup that is set as default
878 self._run(self.mtest_command + ['--setup=mydefault'])
879 with open(os.path.join(self.logdir, 'testlog-mydefault.txt'), encoding='utf-8') as f:
880 mydefault_log = f.read()
881
882 # Run tests with another setup
883 self._run(self.mtest_command + ['--setup=other'])
884 with open(os.path.join(self.logdir, 'testlog-other.txt'), encoding='utf-8') as f:
885 other_log = f.read()
886
887 self.assertIn('ENV_A is 1', default_log)
888 self.assertIn('ENV_B is 2', default_log)
889 self.assertIn('ENV_C is 2', default_log)
890
891 self.assertIn('ENV_A is 1', mydefault_log)
892 self.assertIn('ENV_B is 2', mydefault_log)
893 self.assertIn('ENV_C is 2', mydefault_log)
894
895 self.assertIn('ENV_A is 1', other_log)
896 self.assertIn('ENV_B is 3', other_log)
897 self.assertIn('ENV_C is 2', other_log)
898
899 def assertFailedTestCount(self, failure_count, command):
900 try:
901 self._run(command)
902 self.assertEqual(0, failure_count, 'Expected %d tests to fail.' % failure_count)
903 except subprocess.CalledProcessError as e:
904 actual_fails = 0
905 with open(os.path.join(self.logdir, 'testlog.json'), encoding='utf-8') as f:
906 for line in f:
907 res = json.loads(line)
908 if res['is_fail']:
909 actual_fails += 1
910 self.assertEqual(actual_fails, failure_count)
911
912 def test_suite_selection(self):
913 testdir = os.path.join(self.unit_test_dir, '4 suite selection')
914 self.init(testdir)
915 self.build()
916
917 self.assertFailedTestCount(6, self.mtest_command)
918 self.assertFailedTestCount(4, self.mtest_command + ['--exclude', 'mainprj-failing_test',
919 '--exclude', 'subprjfail:subprjfail-failing_test_no_suite'])
920 self.assertFailedTestCount(5, self.mtest_command + ['--exclude', 'buggy'])
921 self.assertFailedTestCount(5, self.mtest_command + ['--exclude', 'mainprj:buggy'])
922
923 self.assertFailedTestCount(0, self.mtest_command + ['--suite', ':success'])
924 self.assertFailedTestCount(5, self.mtest_command + ['--suite', ':fail'])
925 self.assertFailedTestCount(6, self.mtest_command + ['--no-suite', ':success'])
926 self.assertFailedTestCount(1, self.mtest_command + ['--no-suite', ':fail'])
927
928 self.assertFailedTestCount(2, self.mtest_command + ['--suite', 'mainprj'])
929 self.assertFailedTestCount(0, self.mtest_command + ['--suite', 'subprjsucc'])
930 self.assertFailedTestCount(3, self.mtest_command + ['--suite', 'subprjfail'])
931 self.assertFailedTestCount(1, self.mtest_command + ['--suite', 'subprjmix'])
932 self.assertFailedTestCount(4, self.mtest_command + ['--no-suite', 'mainprj'])
933 self.assertFailedTestCount(6, self.mtest_command + ['--no-suite', 'subprjsucc'])
934 self.assertFailedTestCount(3, self.mtest_command + ['--no-suite', 'subprjfail'])
935 self.assertFailedTestCount(5, self.mtest_command + ['--no-suite', 'subprjmix'])
936
937 self.assertFailedTestCount(2, self.mtest_command + ['--suite', 'mainprj:fail'])
938 self.assertFailedTestCount(0, self.mtest_command + ['--suite', 'mainprj:success'])
939 self.assertFailedTestCount(4, self.mtest_command + ['--no-suite', 'mainprj:fail'])
940 self.assertFailedTestCount(6, self.mtest_command + ['--no-suite', 'mainprj:success'])
941
942 self.assertFailedTestCount(2, self.mtest_command + ['--suite', 'subprjfail:fail'])
943 self.assertFailedTestCount(0, self.mtest_command + ['--suite', 'subprjfail:success'])
944 self.assertFailedTestCount(4, self.mtest_command + ['--no-suite', 'subprjfail:fail'])
945 self.assertFailedTestCount(6, self.mtest_command + ['--no-suite', 'subprjfail:success'])
946
947 self.assertFailedTestCount(0, self.mtest_command + ['--suite', 'subprjsucc:fail'])
948 self.assertFailedTestCount(0, self.mtest_command + ['--suite', 'subprjsucc:success'])
949 self.assertFailedTestCount(6, self.mtest_command + ['--no-suite', 'subprjsucc:fail'])
950 self.assertFailedTestCount(6, self.mtest_command + ['--no-suite', 'subprjsucc:success'])
951
952 self.assertFailedTestCount(1, self.mtest_command + ['--suite', 'subprjmix:fail'])
953 self.assertFailedTestCount(0, self.mtest_command + ['--suite', 'subprjmix:success'])
954 self.assertFailedTestCount(5, self.mtest_command + ['--no-suite', 'subprjmix:fail'])
955 self.assertFailedTestCount(6, self.mtest_command + ['--no-suite', 'subprjmix:success'])
956
957 self.assertFailedTestCount(4, self.mtest_command + ['--suite', 'subprjfail', '--suite', 'subprjmix:fail'])
958 self.assertFailedTestCount(6, self.mtest_command + ['--suite', 'subprjfail', '--suite', 'subprjmix', '--suite', 'mainprj'])
959 self.assertFailedTestCount(5, self.mtest_command + ['--suite', 'subprjfail', '--suite', 'subprjmix', '--suite', 'mainprj', '--no-suite', 'subprjmix:fail'])
960 self.assertFailedTestCount(1, self.mtest_command + ['--suite', 'subprjfail', '--suite', 'subprjmix', '--suite', 'mainprj', '--no-suite', 'subprjmix:fail', 'mainprj-failing_test'])
961
962 self.assertFailedTestCount(3, self.mtest_command + ['--no-suite', 'subprjfail:fail', '--no-suite', 'subprjmix:fail'])
963
964 def test_mtest_reconfigure(self):
965 if self.backend is not Backend.ninja:
966 raise SkipTest(f'mtest can\'t rebuild with {self.backend.name!r}')
967
968 testdir = os.path.join(self.common_test_dir, '206 tap tests')
969 self.init(testdir)
970 self.utime(os.path.join(testdir, 'meson.build'))
971 o = self._run(self.mtest_command + ['--list'])
972 self.assertIn('Regenerating build files', o)
973 self.assertIn('test_features:xfail', o)
974 o = self._run(self.mtest_command + ['--list'])
975 self.assertNotIn('Regenerating build files', o)
976 # no real targets should have been built
977 tester = os.path.join(self.builddir, 'tester' + exe_suffix)
978 self.assertPathDoesNotExist(tester)
979 # check that we don't reconfigure if --no-rebuild is passed
980 self.utime(os.path.join(testdir, 'meson.build'))
981 o = self._run(self.mtest_command + ['--list', '--no-rebuild'])
982 self.assertNotIn('Regenerating build files', o)
983
984 def test_unexisting_test_name(self):
985 testdir = os.path.join(self.unit_test_dir, '4 suite selection')
986 self.init(testdir)
987 self.build()
988
989 self.assertRaises(subprocess.CalledProcessError, self._run, self.mtest_command + ['notatest'])
990
991 def test_select_test_using_wildcards(self):
992 testdir = os.path.join(self.unit_test_dir, '4 suite selection')
993 self.init(testdir)
994 self.build()
995
996 o = self._run(self.mtest_command + ['--list', 'mainprj*'])
997 self.assertIn('mainprj-failing_test', o)
998 self.assertIn('mainprj-successful_test_no_suite', o)
999 self.assertNotIn('subprj', o)
1000
1001 o = self._run(self.mtest_command + ['--list', '*succ*', 'subprjm*:'])
1002 self.assertIn('mainprj-successful_test_no_suite', o)
1003 self.assertIn('subprjmix-failing_test', o)
1004 self.assertIn('subprjmix-successful_test', o)
1005 self.assertIn('subprjsucc-successful_test_no_suite', o)
1006 self.assertNotIn('subprjfail-failing_test', o)
1007
1008 def test_build_by_default(self):
1009 testdir = os.path.join(self.common_test_dir, '129 build by default')
1010 self.init(testdir)
1011 self.build()
1012 genfile1 = os.path.join(self.builddir, 'generated1.dat')
1013 genfile2 = os.path.join(self.builddir, 'generated2.dat')
1014 exe1 = os.path.join(self.builddir, 'fooprog' + exe_suffix)
1015 exe2 = os.path.join(self.builddir, 'barprog' + exe_suffix)
1016 self.assertPathExists(genfile1)
1017 self.assertPathExists(genfile2)
1018 self.assertPathDoesNotExist(exe1)
1019 self.assertPathDoesNotExist(exe2)
1020 self.build(target=('fooprog' + exe_suffix))
1021 self.assertPathExists(exe1)
1022 self.build(target=('barprog' + exe_suffix))
1023 self.assertPathExists(exe2)
1024
1025 @skip_if_not_language('cython')
1026 def test_build_generated_pyx_directly(self):
1027 # Check that the transpile stage also includes
1028 # dependencies for the compilation stage as dependencies
1029 testdir = os.path.join("test cases/cython", '2 generated sources')
1030 self.init(testdir)
1031 # Need to get the full target name of the pyx.c target
1032 # (which is unfortunately not provided by introspection :( )
1033 # We'll need to dig into the generated sources
1034 targets = self.introspect('--targets')
1035 name = None
1036 for target in targets:
1037 for target_sources in target["target_sources"]:
1038 for generated_source in target_sources.get("generated_sources", []):
1039 if "includestuff.pyx.c" in generated_source:
1040 name = generated_source
1041 break
1042 # Split the path (we only want the includestuff.cpython-blahblah.so.p/includestuff.pyx.c)
1043 name = os.path.normpath(name).split(os.sep)[-2:]
1044 name = os.sep.join(name) # Glue list into a string
1045 self.build(target=name)
1046
1047 def test_build_pyx_depfiles(self):
1048 # building regularly and then touching a depfile dependency should rebuild
1049 testdir = os.path.join("test cases/cython", '2 generated sources')
1050 env = get_fake_env(testdir, self.builddir, self.prefix)
1051 try:
1052 cython = detect_compiler_for(env, "cython", MachineChoice.HOST, True, '')
1053 if not version_compare(cython.version, '>=0.29.33'):
1054 raise SkipTest('Cython is too old')
1055 except EnvironmentException:
1056 raise SkipTest("Cython is not installed")
1057 self.init(testdir)
1058
1059 targets = self.introspect('--targets')
1060 for target in targets:
1061 if target['name'].startswith('simpleinclude'):
1062 name = target['name']
1063 self.build()
1064 self.utime(os.path.join(testdir, 'simplestuff.pxi'))
1065 self.assertBuildRelinkedOnlyTarget(name)
1066
1067
1068 def test_cython_avoid_nested_generated_paths(self):
1069 # Ensure that cython transpiled outputs are not in a too deeply nested folder
1070 testdir = os.path.join("test cases/cython", "5 nested folders")
1071 env = get_fake_env(testdir, self.builddir, self.prefix)
1072 try:
1073 detect_compiler_for(env, "cython", MachineChoice.HOST, True, "")
1074 except EnvironmentException:
1075 raise SkipTest("Cython is not installed")
1076 self.init(testdir)
1077
1078 targets = self.introspect("--targets")
1079
1080 found = False
1081 for target in targets:
1082 for target_sources in target["target_sources"]:
1083 for generated_source in target_sources.get("generated_sources", []):
1084 if generated_source.endswith(".pyx.c") or generated_source.endswith("pyx.cpp"):
1085 found = True
1086 parts = os.path.normpath(generated_source).split(os.sep)
1087 parent = parts[-2]
1088 # We want the pyx.c files to be directly under the .p folder,
1089 # for example:
1090 # libdir/foo.cpython-313-x86_64-linux-gnu.so.p/foo.pyx.c
1091 # rather than (additional libdir folder):
1092 # libdir/foo.cpython-313-x86_64-linux-gnu.so.p/libdir/foo.pyx.c
1093 self.assertTrue(
1094 parent.endswith(".p"),
1095 "pyx.c file should be directly under the .p folder,"
1096 f" got {generated_source!r}"
1097 )
1098 self.assertTrue(found, "No cython transpiled outputs found")
1099
1100 def test_internal_include_order(self):
1101 if mesonbuild.envconfig.detect_msys2_arch() and ('MESON_RSP_THRESHOLD' in os.environ):
1102 raise SkipTest('Test does not yet support gcc rsp files on msys2')
1103
1104 testdir = os.path.join(self.common_test_dir, '130 include order')
1105 self.init(testdir)
1106 execmd = fxecmd = None
1107 for cmd in self.get_compdb():
1108 if 'someexe' in cmd['command']:
1109 execmd = cmd['command']
1110 continue
1111 if 'somefxe' in cmd['command']:
1112 fxecmd = cmd['command']
1113 continue
1114 if not execmd or not fxecmd:
1115 raise Exception('Could not find someexe and somfxe commands')
1116 # Check include order for 'someexe'
1117 incs = [a for a in split_args(execmd) if a.startswith("-I")]
1118 self.assertEqual(len(incs), 9)
1119 # Need to run the build so the private dir is created.
1120 self.build()
1121 pdirs = glob(os.path.join(self.builddir, 'sub4/someexe*.p'))
1122 self.assertEqual(len(pdirs), 1)
1123 privdir = pdirs[0][len(self.builddir)+1:]
1124 self.assertPathEqual(incs[0], "-I" + privdir)
1125 # target build subdir
1126 self.assertPathEqual(incs[1], "-Isub4")
1127 # target source subdir
1128 self.assertPathBasenameEqual(incs[2], 'sub4')
1129 # include paths added via per-target c_args: ['-I'...]
1130 self.assertPathBasenameEqual(incs[3], 'sub3')
1131 # target include_directories: build dir
1132 self.assertPathEqual(incs[4], "-Isub2")
1133 # target include_directories: source dir
1134 self.assertPathBasenameEqual(incs[5], 'sub2')
1135 # target internal dependency include_directories: build dir
1136 self.assertPathEqual(incs[6], "-Isub1")
1137 # target internal dependency include_directories: source dir
1138 self.assertPathBasenameEqual(incs[7], 'sub1')
1139 # custom target include dir
1140 self.assertPathEqual(incs[8], '-Ictsub')
1141 # Check include order for 'somefxe'
1142 incs = [a for a in split_args(fxecmd) if a.startswith('-I')]
1143 self.assertEqual(len(incs), 9)
1144 # target private dir
1145 pdirs = glob(os.path.join(self.builddir, 'somefxe*.p'))
1146 self.assertEqual(len(pdirs), 1)
1147 privdir = pdirs[0][len(self.builddir)+1:]
1148 self.assertPathEqual(incs[0], '-I' + privdir)
1149 # target build dir
1150 self.assertPathEqual(incs[1], '-I.')
1151 # target source dir
1152 self.assertPathBasenameEqual(incs[2], os.path.basename(testdir))
1153 # target internal dependency correct include_directories: build dir
1154 self.assertPathEqual(incs[3], "-Isub4")
1155 # target internal dependency correct include_directories: source dir
1156 self.assertPathBasenameEqual(incs[4], 'sub4')
1157 # target internal dependency dep include_directories: build dir
1158 self.assertPathEqual(incs[5], "-Isub1")
1159 # target internal dependency dep include_directories: source dir
1160 self.assertPathBasenameEqual(incs[6], 'sub1')
1161 # target internal dependency wrong include_directories: build dir
1162 self.assertPathEqual(incs[7], "-Isub2")
1163 # target internal dependency wrong include_directories: source dir
1164 self.assertPathBasenameEqual(incs[8], 'sub2')
1165
1166 @mock.patch.dict(os.environ)
1167 def test_compiler_detection(self):
1168 '''
1169 Test that automatic compiler detection and setting from the environment
1170 both work just fine. This is needed because while running project tests
1171 and other unit tests, we always read CC/CXX/etc from the environment.
1172 '''
1173 gnu = GnuCompiler
1174 clang = ClangCompiler
1175 intel = IntelGnuLikeCompiler
1176 msvc = (VisualStudioCCompiler, VisualStudioCPPCompiler)
1177 clangcl = (ClangClCCompiler, ClangClCPPCompiler)
1178 ar = linkers.ArLinker
1179 lib = linkers.VisualStudioLinker
1180 langs = [('c', 'CC'), ('cpp', 'CXX')]
1181 if not is_windows() and platform.machine().lower() != 'e2k':
1182 langs += [('objc', 'OBJC'), ('objcpp', 'OBJCXX')]
1183 testdir = os.path.join(self.unit_test_dir, '5 compiler detection')
1184 env = get_fake_env(testdir, self.builddir, self.prefix)
1185 for lang, evar in langs:
1186 # Detect with evar and do sanity checks on that
1187 if evar in os.environ:
1188 with self.subTest(lang=lang, evar=evar):
1189 try:
1190 ecc = compiler_from_language(env, lang, MachineChoice.HOST)
1191 except EnvironmentException:
1192 # always raise in ci, we expect to have a valid ObjC and ObjC++ compiler of some kind
1193 if IS_CI:
1194 self.fail(f'Could not find a compiler for {lang}')
1195 if sys.version_info < (3, 11):
1196 continue
1197 self.skipTest(f'No valid compiler for {lang}.')
1198 finally:
1199 # Pop it so we don't use it for the next detection
1200 evalue = os.environ.pop(evar)
1201 assert ecc is not None, "Something went really wrong"
1202 self.assertTrue(ecc.version)
1203 elinker = detect_static_linker(env, ecc)
1204 # Very rough/strict heuristics. Would never work for actual
1205 # compiler detection, but should be ok for the tests.
1206 ebase = os.path.basename(evalue)
1207 if ecc.id == 'lcc':
1208 # lcc ships the gcc symlink, but it isn't a GnuCompiler,
1209 # but a GnuLikeCompiler
1210 self.assertIsInstance(ecc, ElbrusCompiler)
1211 elif ebase.startswith('g') or ebase.endswith(('-gcc', '-g++')):
1212 self.assertIsInstance(ecc, gnu)
1213 self.assertIsInstance(elinker, ar)
1214 elif 'clang-cl' in ebase:
1215 self.assertIsInstance(ecc, clangcl)
1216 self.assertIsInstance(elinker, lib)
1217 elif 'clang' in ebase:
1218 self.assertIsInstance(ecc, clang)
1219 self.assertIsInstance(elinker, ar)
1220 elif ebase.startswith('ic'):
1221 self.assertIsInstance(ecc, intel)
1222 self.assertIsInstance(elinker, ar)
1223 elif ebase.startswith('cl'):
1224 self.assertIsInstance(ecc, msvc)
1225 self.assertIsInstance(elinker, lib)
1226 else:
1227 self.fail(f'Unknown compiler {evalue!r}')
1228 # Check that we actually used the evalue correctly as the compiler
1229 self.assertEqual(ecc.get_exelist(), split_args(evalue))
1230
1231 # Do auto-detection of compiler based on platform, PATH, etc.
1232 with self.subTest(lang=lang):
1233 try:
1234 cc = compiler_from_language(env, lang, MachineChoice.HOST)
1235 except EnvironmentException:
1236 # always raise in ci, we expect to have a valid ObjC and ObjC++ compiler of some kind
1237 if IS_CI:
1238 self.fail(f'Could not find a compiler for {lang}')
1239 if sys.version_info < (3, 11):
1240 continue
1241 self.skipTest(f'No valid compiler for {lang}.')
1242 assert cc is not None, "Something went really wrong"
1243 self.assertTrue(cc.version)
1244 linker = detect_static_linker(env, cc)
1245 # Check compiler type
1246 if isinstance(cc, gnu):
1247 self.assertIsInstance(linker, ar)
1248 if is_osx():
1249 self.assertIsInstance(cc.linker, linkers.AppleDynamicLinker)
1250 elif is_sunos():
1251 self.assertIsInstance(cc.linker, (linkers.SolarisDynamicLinker, linkers.GnuLikeDynamicLinkerMixin))
1252 else:
1253 self.assertIsInstance(cc.linker, linkers.GnuLikeDynamicLinkerMixin)
1254 if isinstance(cc, clangcl):
1255 self.assertIsInstance(linker, lib)
1256 self.assertIsInstance(cc.linker, linkers.ClangClDynamicLinker)
1257 if isinstance(cc, clang):
1258 self.assertIsInstance(linker, ar)
1259 if is_osx():
1260 self.assertIsInstance(cc.linker, linkers.AppleDynamicLinker)
1261 elif is_windows():
1262 # This is clang, not clang-cl. This can be either an
1263 # ld-like linker of link.exe-like linker (usually the
1264 # former for msys2, the latter otherwise)
1265 self.assertIsInstance(cc.linker, (linkers.MSVCDynamicLinker, linkers.GnuLikeDynamicLinkerMixin))
1266 elif is_sunos():
1267 self.assertIsInstance(cc.linker, (linkers.SolarisDynamicLinker, linkers.GnuLikeDynamicLinkerMixin))
1268 else:
1269 self.assertIsInstance(cc.linker, linkers.GnuLikeDynamicLinkerMixin)
1270 if isinstance(cc, intel):
1271 self.assertIsInstance(linker, ar)
1272 if is_osx():
1273 self.assertIsInstance(cc.linker, linkers.AppleDynamicLinker)
1274 elif is_windows():
1275 self.assertIsInstance(cc.linker, linkers.XilinkDynamicLinker)
1276 else:
1277 self.assertIsInstance(cc.linker, linkers.GnuDynamicLinker)
1278 if isinstance(cc, msvc):
1279 self.assertTrue(is_windows())
1280 self.assertIsInstance(linker, lib)
1281 self.assertEqual(cc.id, 'msvc')
1282 self.assertTrue(hasattr(cc, 'is_64'))
1283 self.assertIsInstance(cc.linker, linkers.MSVCDynamicLinker)
1284 # If we're on Windows CI, we know what the compiler will be
1285 if 'arch' in os.environ:
1286 if os.environ['arch'] == 'x64':
1287 self.assertTrue(cc.is_64)
1288 else:
1289 self.assertFalse(cc.is_64)
1290
1291 # Set evar ourselves to a wrapper script that just calls the same
1292 # exelist + some argument. This is meant to test that setting
1293 # something like `ccache gcc -pipe` or `distcc ccache gcc` works.
1294 with self.subTest('wrapper script', lang=lang):
1295 wrapper = os.path.join(testdir, 'compiler wrapper.py')
1296 wrappercc = python_command + [wrapper] + cc.get_exelist() + ['-DSOME_ARG']
1297 os.environ[evar] = ' '.join(quote_arg(w) for w in wrappercc)
1298
1299 # Check static linker too
1300 wrapperlinker = python_command + [wrapper] + linker.get_exelist() + linker.get_always_args()
1301 os.environ['AR'] = ' '.join(quote_arg(w) for w in wrapperlinker)
1302
1303 # Need a new env to re-run environment loading
1304 env = get_fake_env(testdir, self.builddir, self.prefix)
1305
1306 try:
1307 wcc = compiler_from_language(env, lang, MachineChoice.HOST)
1308 except EnvironmentException:
1309 # always raise in ci, we expect to have a valid ObjC and ObjC++ compiler of some kind
1310 if IS_CI:
1311 self.fail(f'Could not find a compiler for {lang}')
1312 if sys.version_info < (3, 11):
1313 continue
1314 self.skipTest(f'No valid compiler for {lang}.')
1315 wlinker = detect_static_linker(env, wcc)
1316 del os.environ['AR']
1317
1318 # Must be the same type since it's a wrapper around the same exelist
1319 self.assertIs(type(cc), type(wcc))
1320 self.assertIs(type(linker), type(wlinker))
1321
1322 # Ensure that the exelist is correct
1323 self.assertEqual(wcc.get_exelist(), wrappercc)
1324 self.assertEqual(wlinker.get_exelist(), wrapperlinker)
1325
1326 # Ensure that the version detection worked correctly
1327 self.assertEqual(cc.version, wcc.version)
1328 if hasattr(cc, 'is_64'):
1329 self.assertEqual(cc.is_64, wcc.is_64)
1330
1331 def test_always_prefer_c_compiler_for_asm(self):
1332 testdir = os.path.join(self.common_test_dir, '133 c cpp and asm')
1333 # Skip if building with MSVC
1334 env = get_fake_env(testdir, self.builddir, self.prefix)
1335 if detect_c_compiler(env, MachineChoice.HOST).get_id() == 'msvc':
1336 raise SkipTest('MSVC can\'t compile assembly')
1337 self.init(testdir)
1338 commands = {'c-asm': {}, 'cpp-asm': {}, 'cpp-c-asm': {}, 'c-cpp-asm': {}}
1339 for cmd in self.get_compdb():
1340 # Get compiler
1341 split = split_args(cmd['command'])
1342 if split[0] in ('ccache', 'sccache'):
1343 compiler = split[1]
1344 else:
1345 compiler = split[0]
1346 # Classify commands
1347 if 'Ic-asm' in cmd['command']:
1348 if cmd['file'].endswith('.S'):
1349 commands['c-asm']['asm'] = compiler
1350 elif cmd['file'].endswith('.c'):
1351 commands['c-asm']['c'] = compiler
1352 else:
1353 raise AssertionError('{!r} found in cpp-asm?'.format(cmd['command']))
1354 elif 'Icpp-asm' in cmd['command']:
1355 if cmd['file'].endswith('.S'):
1356 commands['cpp-asm']['asm'] = compiler
1357 elif cmd['file'].endswith('.cpp'):
1358 commands['cpp-asm']['cpp'] = compiler
1359 else:
1360 raise AssertionError('{!r} found in cpp-asm?'.format(cmd['command']))
1361 elif 'Ic-cpp-asm' in cmd['command']:
1362 if cmd['file'].endswith('.S'):
1363 commands['c-cpp-asm']['asm'] = compiler
1364 elif cmd['file'].endswith('.c'):
1365 commands['c-cpp-asm']['c'] = compiler
1366 elif cmd['file'].endswith('.cpp'):
1367 commands['c-cpp-asm']['cpp'] = compiler
1368 else:
1369 raise AssertionError('{!r} found in c-cpp-asm?'.format(cmd['command']))
1370 elif 'Icpp-c-asm' in cmd['command']:
1371 if cmd['file'].endswith('.S'):
1372 commands['cpp-c-asm']['asm'] = compiler
1373 elif cmd['file'].endswith('.c'):
1374 commands['cpp-c-asm']['c'] = compiler
1375 elif cmd['file'].endswith('.cpp'):
1376 commands['cpp-c-asm']['cpp'] = compiler
1377 else:
1378 raise AssertionError('{!r} found in cpp-c-asm?'.format(cmd['command']))
1379 else:
1380 raise AssertionError('Unknown command {!r} found'.format(cmd['command']))
1381 # Check that .S files are always built with the C compiler
1382 self.assertEqual(commands['c-asm']['asm'], commands['c-asm']['c'])
1383 self.assertEqual(commands['c-asm']['asm'], commands['cpp-asm']['asm'])
1384 self.assertEqual(commands['cpp-asm']['asm'], commands['c-cpp-asm']['c'])
1385 self.assertEqual(commands['c-cpp-asm']['asm'], commands['c-cpp-asm']['c'])
1386 self.assertEqual(commands['cpp-c-asm']['asm'], commands['cpp-c-asm']['c'])
1387 self.assertNotEqual(commands['cpp-asm']['asm'], commands['cpp-asm']['cpp'])
1388 self.assertNotEqual(commands['c-cpp-asm']['c'], commands['c-cpp-asm']['cpp'])
1389 self.assertNotEqual(commands['cpp-c-asm']['c'], commands['cpp-c-asm']['cpp'])
1390 # Check that the c-asm target is always linked with the C linker
1391 build_ninja = os.path.join(self.builddir, 'build.ninja')
1392 with open(build_ninja, encoding='utf-8') as f:
1393 contents = f.read()
1394 m = re.search('build c-asm.*: c_LINKER', contents)
1395 self.assertIsNotNone(m, msg=contents)
1396
1397 def test_preprocessor_checks_CPPFLAGS(self):
1398 '''
1399 Test that preprocessor compiler checks read CPPFLAGS and also CFLAGS/CXXFLAGS but
1400 not LDFLAGS.
1401 '''
1402 testdir = os.path.join(self.common_test_dir, '132 get define')
1403 define = 'MESON_TEST_DEFINE_VALUE'
1404 # NOTE: this list can't have \n, ' or "
1405 # \n is never substituted by the GNU pre-processor via a -D define
1406 # ' and " confuse split_args() even when they are escaped
1407 # % and # confuse the MSVC preprocessor
1408 # !, ^, *, and < confuse lcc preprocessor
1409 value = 'spaces and fun@$&()-=_+{}[]:;>?,./~`'
1410 for env_var in [{'CPPFLAGS'}, {'CFLAGS', 'CXXFLAGS'}]:
1411 env = {}
1412 for i in env_var:
1413 env[i] = f'-D{define}="{value}"'
1414 env['LDFLAGS'] = '-DMESON_FAIL_VALUE=cflags-read'
1415 self.init(testdir, extra_args=[f'-D{define}={value}'], override_envvars=env)
1416 self.new_builddir()
1417
1418 def test_custom_target_exe_data_deterministic(self):
1419 testdir = os.path.join(self.common_test_dir, '109 custom target capture')
1420 self.init(testdir)
1421 meson_exe_dat1 = glob(os.path.join(self.privatedir, 'meson_exe*.dat'))
1422 self.wipe()
1423 self.init(testdir)
1424 meson_exe_dat2 = glob(os.path.join(self.privatedir, 'meson_exe*.dat'))
1425 self.assertListEqual(meson_exe_dat1, meson_exe_dat2)
1426
1427 def test_noop_changes_cause_no_rebuilds(self):
1428 '''
1429 Test that no-op changes to the build files such as mtime do not cause
1430 a rebuild of anything.
1431 '''
1432 testdir = os.path.join(self.common_test_dir, '6 linkshared')
1433 self.init(testdir)
1434 self.build()
1435 # Immediately rebuilding should not do anything
1436 self.assertBuildIsNoop()
1437 # Changing mtime of meson.build should not rebuild anything
1438 self.utime(os.path.join(testdir, 'meson.build'))
1439 self.assertReconfiguredBuildIsNoop()
1440 # Changing mtime of libefile.c should rebuild the library, but not relink the executable
1441 self.utime(os.path.join(testdir, 'libfile.c'))
1442 self.assertBuildRelinkedOnlyTarget('mylib')
1443
1444 def test_source_changes_cause_rebuild(self):
1445 '''
1446 Test that changes to sources and headers cause rebuilds, but not
1447 changes to unused files (as determined by the dependency file) in the
1448 input files list.
1449 '''
1450 testdir = os.path.join(self.common_test_dir, '19 header in file list')
1451 self.init(testdir)
1452 self.build()
1453 # Immediately rebuilding should not do anything
1454 self.assertBuildIsNoop()
1455 # Changing mtime of header.h should rebuild everything
1456 self.utime(os.path.join(testdir, 'header.h'))
1457 self.assertBuildRelinkedOnlyTarget('prog')
1458
1459 def test_custom_target_changes_cause_rebuild(self):
1460 '''
1461 Test that in a custom target, changes to the input files, the
1462 ExternalProgram, and any File objects on the command-line cause
1463 a rebuild.
1464 '''
1465 testdir = os.path.join(self.common_test_dir, '57 custom header generator')
1466 self.init(testdir)
1467 self.build()
1468 # Immediately rebuilding should not do anything
1469 self.assertBuildIsNoop()
1470 # Changing mtime of these should rebuild everything
1471 for f in ('input.def', 'makeheader.py', 'somefile.txt'):
1472 self.utime(os.path.join(testdir, f))
1473 self.assertBuildRelinkedOnlyTarget('prog')
1474
1475 def test_source_generator_program_cause_rebuild(self):
1476 '''
1477 Test that changes to generator programs in the source tree cause
1478 a rebuild.
1479 '''
1480 testdir = os.path.join(self.common_test_dir, '90 gen extra')
1481 self.init(testdir)
1482 self.build()
1483 # Immediately rebuilding should not do anything
1484 self.assertBuildIsNoop()
1485 # Changing mtime of generator should rebuild the executable
1486 self.utime(os.path.join(testdir, 'srcgen.py'))
1487 self.assertRebuiltTarget('basic')
1488
1489 def test_long_opt_vs_D(self):
1490 '''
1491 Test that conflicts between -D for builtin options and the corresponding
1492 long option are detected without false positives or negatives.
1493 '''
1494 testdir = os.path.join(self.unit_test_dir, '130 long opt vs D')
1495
1496 for opt in ['-Dsysconfdir=/etc', '-Dsysconfdir2=/etc']:
1497 exception_raised = False
1498 try:
1499 self.init(testdir, extra_args=[opt, '--sysconfdir=/etc'])
1500 except subprocess.CalledProcessError:
1501 exception_raised = True
1502 if 'sysconfdir2' in opt:
1503 self.assertFalse(exception_raised, f'{opt} --sysconfdir raised an exception')
1504 else:
1505 self.assertTrue(exception_raised, f'{opt} --sysconfdir did not raise an exception')
1506
1507 exception_raised = False
1508 try:
1509 self.init(testdir, extra_args=['--sysconfdir=/etc', opt])
1510 except subprocess.CalledProcessError:
1511 exception_raised = True
1512 if 'sysconfdir2' in opt:
1513 self.assertFalse(exception_raised, f'--sysconfdir {opt} raised an exception')
1514 else:
1515 self.assertTrue(exception_raised, f'--sysconfdir {opt} did not raise an exception')
1516
1517 self.wipe()
1518
1519 def test_static_library_lto(self):
1520 '''
1521 Test that static libraries can be built with LTO and linked to
1522 executables. On Linux, this requires the use of gcc-ar.
1523 https://github.com/mesonbuild/meson/issues/1646
1524 '''
1525 testdir = os.path.join(self.common_test_dir, '5 linkstatic')
1526
1527 env = get_fake_env(testdir, self.builddir, self.prefix)
1528 if detect_c_compiler(env, MachineChoice.HOST).get_id() == 'clang' and is_windows():
1529 raise SkipTest('LTO not (yet) supported by windows clang')
1530
1531 self.init(testdir, extra_args='-Db_lto=true')
1532 self.build()
1533 self.run_tests()
1534
1535 @skip_if_not_base_option('b_lto_threads')
1536 def test_lto_threads(self):
1537 testdir = os.path.join(self.common_test_dir, '6 linkshared')
1538
1539 env = get_fake_env(testdir, self.builddir, self.prefix)
1540 cc = detect_c_compiler(env, MachineChoice.HOST)
1541 extra_args: T.List[str] = []
1542 if cc.get_id() == 'clang':
1543 if is_windows():
1544 raise SkipTest('LTO not (yet) supported by windows clang')
1545
1546 self.init(testdir, extra_args=['-Db_lto=true', '-Db_lto_threads=8'] + extra_args)
1547 self.build()
1548 self.run_tests()
1549
1550 expected = set(cc.get_lto_compile_args(threads=8))
1551 targets = self.introspect('--targets')
1552 # This assumes all of the targets support lto
1553 for t in targets:
1554 for s in t['target_sources']:
1555 if 'linker' in s:
1556 continue
1557 for e in expected:
1558 self.assertIn(e, s['parameters'])
1559
1560 @skip_if_not_base_option('b_lto_mode')
1561 @skip_if_not_base_option('b_lto_threads')
1562 def test_lto_mode(self):
1563 testdir = os.path.join(self.common_test_dir, '6 linkshared')
1564
1565 env = get_fake_env(testdir, self.builddir, self.prefix)
1566 cc = detect_c_compiler(env, MachineChoice.HOST)
1567 if cc.get_id() != 'clang':
1568 raise SkipTest('Only clang currently supports thinLTO')
1569 if cc.linker.id not in {'ld.lld', 'ld.gold', 'ld64', 'lld-link'}:
1570 raise SkipTest('thinLTO requires ld.lld, ld.gold, ld64, or lld-link')
1571 elif is_windows():
1572 raise SkipTest('LTO not (yet) supported by windows clang')
1573
1574 self.init(testdir, extra_args=['-Db_lto=true', '-Db_lto_mode=thin', '-Db_lto_threads=8', '-Dc_args=-Werror=unused-command-line-argument'])
1575 self.build()
1576 self.run_tests()
1577
1578 expected = set(cc.get_lto_compile_args(threads=8, mode='thin'))
1579 targets = self.introspect('--targets')
1580 # This assumes all of the targets support lto
1581 for t in targets:
1582 for src in t['target_sources']:
1583 self.assertTrue(expected.issubset(set(src['parameters'])), f'Incorrect values for {t["name"]}')
1584
1585 @skipIfNoExecutable('git')
1586 def test_dist_git(self):
1587 if self.backend is not Backend.ninja:
1588 raise SkipTest('Dist is only supported with Ninja')
1589
1590 try:
1591 self.dist_impl(git_init, _git_add_all)
1592 except PermissionError:
1593 # When run under Windows CI, something (virus scanner?)
1594 # holds on to the git files so cleaning up the dir
1595 # fails sometimes.
1596 pass
1597
1598 def has_working_hg(self):
1599 if not shutil.which('hg'):
1600 return False
1601 try:
1602 # This check should not be necessary, but
1603 # CI under macOS passes the above test even
1604 # though Mercurial is not installed.
1605 if subprocess.call(['hg', '--version'],
1606 stdout=subprocess.DEVNULL,
1607 stderr=subprocess.DEVNULL) != 0:
1608 return False
1609 return True
1610 except FileNotFoundError:
1611 return False
1612
1613 def test_dist_hg(self):
1614 if not self.has_working_hg():
1615 raise SkipTest('Mercurial not found or broken.')
1616 if self.backend is not Backend.ninja:
1617 raise SkipTest('Dist is only supported with Ninja')
1618
1619 def hg_init(project_dir):
1620 subprocess.check_call(['hg', 'init'], cwd=project_dir)
1621 with open(os.path.join(project_dir, '.hg', 'hgrc'), 'w', encoding='utf-8') as f:
1622 print('[ui]', file=f)
1623 print('username=Author Person <[email protected]>', file=f)
1624 subprocess.check_call(['hg', 'add', 'meson.build', 'distexe.c'], cwd=project_dir)
1625 subprocess.check_call(['hg', 'commit', '-m', 'I am a project'], cwd=project_dir)
1626
1627 try:
1628 self.dist_impl(hg_init, include_subprojects=False)
1629 except PermissionError:
1630 # When run under Windows CI, something (virus scanner?)
1631 # holds on to the hg files so cleaning up the dir
1632 # fails sometimes.
1633 pass
1634
1635 @skipIfNoExecutable('git')
1636 def test_dist_git_script(self):
1637 if self.backend is not Backend.ninja:
1638 raise SkipTest('Dist is only supported with Ninja')
1639
1640 try:
1641 with tempfile.TemporaryDirectory() as tmpdir:
1642 project_dir = os.path.join(tmpdir, 'a')
1643 shutil.copytree(os.path.join(self.unit_test_dir, '35 dist script'),
1644 project_dir)
1645 git_init(project_dir)
1646 self.init(project_dir)
1647 self.build('dist')
1648
1649 self.new_builddir()
1650 self.init(project_dir, extra_args=['-Dsub:broken_dist_script=false'])
1651 self._run(self.meson_command + ['dist', '--include-subprojects'], workdir=self.builddir)
1652 except PermissionError:
1653 # When run under Windows CI, something (virus scanner?)
1654 # holds on to the git files so cleaning up the dir
1655 # fails sometimes.
1656 pass
1657
1658 @skipIfNoExecutable('git')
1659 @skip_if_not_language('rust')
1660 def test_dist_subprojects_cargo(self):
1661 if self.backend is not Backend.ninja:
1662 raise SkipTest('Dist is only supported with Ninja')
1663
1664 try:
1665 with tempfile.TemporaryDirectory() as tmpdir:
1666 project_dir = os.path.join(tmpdir, 'a')
1667 shutil.copytree(os.path.join(self.rust_test_dir, '25 cargo lock'),
1668 project_dir)
1669 git_init(project_dir)
1670 self.init(project_dir)
1671 self._run(self.meson_command + ['dist', '--include-subprojects'], workdir=self.builddir)
1672 except PermissionError:
1673 # When run under Windows CI, something (virus scanner?)
1674 # holds on to the git files so cleaning up the dir
1675 # fails sometimes.
1676 pass
1677
1678 @skipIfNoExecutable('git')
1679 def test_dist_nested_promoted_subproject(self):
1680 '''
1681 https://github.com/mesonbuild/meson/issues/12489
1682
1683 A subproject (e.g. glib) can itself depend on a nested subproject
1684 (e.g. gvdb) whose sources are bundled inside the outer subproject's
1685 own "subprojects" directory rather than the main project's. Meson
1686 promotes the wrap file for such a nested subproject to the main
1687 project's subprojects directory (writing a [wrap-redirect] wrap
1688 there), but the actual source directory stays nested. `meson dist
1689 --include-subprojects` used to look for the nested subproject
1690 directly under the main project's subprojects directory (following
1691 the promoted wrap file naively) and crashed with a FileNotFoundError
1692 because that directory did not exist there.
1693 '''
1694 if self.backend is not Backend.ninja:
1695 raise SkipTest('Dist is only supported with Ninja')
1696
1697 with tempfile.TemporaryDirectory() as project_dir:
1698 with open(os.path.join(project_dir, 'meson.build'), 'w', encoding='utf-8') as f:
1699 f.write(textwrap.dedent('''\
1700 project('gtk', version : '1.0')
1701 subproject('glib')
1702 '''))
1703
1704 glib_dir = os.path.join(project_dir, 'subprojects', 'glib')
1705 gvdb_dir = os.path.join(glib_dir, 'subprojects', 'gvdb')
1706 os.makedirs(gvdb_dir)
1707
1708 # glib is a normal subproject with its own wrap file
1709 with open(os.path.join(project_dir, 'subprojects', 'glib.wrap'), 'w', encoding='utf-8') as f:
1710 f.write(textwrap.dedent('''\
1711 [wrap-file]
1712 directory = glib
1713 '''))
1714
1715 # Only the main project and glib's wrap file are tracked by git;
1716 # glib itself is *not* a git repository, mimicking a subproject
1717 # fetched/extracted from a tarball
1718 git_init(project_dir)
1719
1720 with open(os.path.join(glib_dir, 'meson.build'), 'w', encoding='utf-8') as f:
1721 f.write(textwrap.dedent('''\
1722 project('glib', version : '1.0')
1723 subproject('gvdb')
1724 '''))
1725
1726 # gvdb is bundled inside glib's own subprojects directory, with
1727 # its sources already extracted there
1728 with open(os.path.join(glib_dir, 'subprojects', 'gvdb.wrap'), 'w', encoding='utf-8') as f:
1729 f.write(textwrap.dedent('''\
1730 [wrap-file]
1731 directory = gvdb
1732 '''))
1733 with open(os.path.join(gvdb_dir, 'meson.build'), 'w', encoding='utf-8') as f:
1734 f.write(textwrap.dedent('''\
1735 project('gvdb', version : '1.0')
1736 '''))
1737
1738 self.init(project_dir)
1739 # Configuring writes the promoted [wrap-redirect] wrap file
1740 redirect_wrap = os.path.join(project_dir, 'subprojects', 'gvdb.wrap')
1741 self.assertPathExists(redirect_wrap)
1742 with open(redirect_wrap, encoding='utf-8') as f:
1743 self.assertIn('[wrap-redirect]', f.read())
1744
1745 self._run(self.meson_command + ['dist', '--include-subprojects', '--no-tests',
1746 '--formats', 'zip'],
1747 workdir=self.builddir)
1748
1749 zip_distfile = os.path.join(self.distdir, 'gtk-1.0.zip')
1750 self.assertPathExists(zip_distfile)
1751 z = zipfile.ZipFile(zip_distfile)
1752 names = set(z.namelist())
1753 # gvdb must end up nested inside glib, where it really lives...
1754 self.assertIn('gtk-1.0/subprojects/glib/subprojects/gvdb/meson.build', names)
1755 # ... and must not be duplicated (or looked up) directly under the
1756 # main project's subprojects directory.
1757 self.assertNotIn('gtk-1.0/subprojects/gvdb/meson.build', names)
1758 self.assertNotIn('gtk-1.0/subprojects/gvdb.wrap', names)
1759
1760 def create_dummy_subproject(self, project_dir, name):
1761 path = os.path.join(project_dir, 'subprojects', name)
1762 os.makedirs(path)
1763 with open(os.path.join(path, 'meson.build'), 'w', encoding='utf-8') as ofile:
1764 ofile.write(f"project('{name}', version: '1.0')")
1765 return path
1766
1767 def dist_impl(self, vcs_init, vcs_add_all=None, include_subprojects=True):
1768 # Create this on the fly because having rogue .git directories inside
1769 # the source tree leads to all kinds of trouble.
1770 with tempfile.TemporaryDirectory() as project_dir:
1771 with open(os.path.join(project_dir, 'meson.build'), 'w', encoding='utf-8') as ofile:
1772 ofile.write(textwrap.dedent('''\
1773 project('disttest', 'c', version : '1.4.3')
1774 e = executable('distexe', 'distexe.c')
1775 test('dist test', e)
1776 subproject('vcssub', required : false)
1777 subproject('tarballsub', required : false)
1778 subproject('samerepo', required : false)
1779 '''))
1780 distexe_c = os.path.join(project_dir, 'distexe.c')
1781 with open(distexe_c, 'w', encoding='utf-8') as ofile:
1782 ofile.write(textwrap.dedent('''\
1783 #include<stdio.h>
1784
1785 int main(int argc, char **argv) {
1786 printf("I am a distribution test.\\n");
1787 return 0;
1788 }
1789 '''))
1790 xz_distfile = os.path.join(self.distdir, 'disttest-1.4.3.tar.xz')
1791 xz_checksumfile = xz_distfile + '.sha256sum'
1792 bz_distfile = os.path.join(self.distdir, 'disttest-1.4.3.tar.bz2')
1793 bz_checksumfile = bz_distfile + '.sha256sum'
1794 gz_distfile = os.path.join(self.distdir, 'disttest-1.4.3.tar.gz')
1795 gz_checksumfile = gz_distfile + '.sha256sum'
1796 zip_distfile = os.path.join(self.distdir, 'disttest-1.4.3.zip')
1797 zip_checksumfile = zip_distfile + '.sha256sum'
1798 vcs_init(project_dir)
1799 if include_subprojects:
1800 vcs_init(self.create_dummy_subproject(project_dir, 'vcssub'))
1801 self.create_dummy_subproject(project_dir, 'tarballsub')
1802 self.create_dummy_subproject(project_dir, 'unusedsub')
1803 if vcs_add_all:
1804 vcs_add_all(self.create_dummy_subproject(project_dir, 'samerepo'))
1805 self.init(project_dir)
1806 self.build('dist')
1807 self.assertPathExists(xz_distfile)
1808 self.assertPathExists(xz_checksumfile)
1809 self.assertPathDoesNotExist(bz_distfile)
1810 self.assertPathDoesNotExist(bz_checksumfile)
1811 self.assertPathDoesNotExist(gz_distfile)
1812 self.assertPathDoesNotExist(gz_checksumfile)
1813 self.assertPathDoesNotExist(zip_distfile)
1814 self.assertPathDoesNotExist(zip_checksumfile)
1815 # update a source file timestamp; dist should succeed anyway
1816 os.utime(distexe_c)
1817 self._run(self.meson_command + ['dist', '--formats', 'bztar'],
1818 workdir=self.builddir)
1819 self.assertPathExists(bz_distfile)
1820 self.assertPathExists(bz_checksumfile)
1821 self._run(self.meson_command + ['dist', '--formats', 'gztar'],
1822 workdir=self.builddir)
1823 self.assertPathExists(gz_distfile)
1824 self.assertPathExists(gz_checksumfile)
1825 self._run(self.meson_command + ['dist', '--formats', 'zip'],
1826 workdir=self.builddir)
1827 self.assertPathExists(zip_distfile)
1828 self.assertPathExists(zip_checksumfile)
1829 os.remove(xz_distfile)
1830 os.remove(xz_checksumfile)
1831 os.remove(bz_distfile)
1832 os.remove(bz_checksumfile)
1833 os.remove(gz_distfile)
1834 os.remove(gz_checksumfile)
1835 os.remove(zip_distfile)
1836 os.remove(zip_checksumfile)
1837 self._run(self.meson_command + ['dist', '--formats', 'xztar,bztar,gztar,zip'],
1838 workdir=self.builddir)
1839 self.assertPathExists(xz_distfile)
1840 self.assertPathExists(xz_checksumfile)
1841 self.assertPathExists(bz_distfile)
1842 self.assertPathExists(bz_checksumfile)
1843 self.assertPathExists(gz_distfile)
1844 self.assertPathExists(gz_checksumfile)
1845 self.assertPathExists(zip_distfile)
1846 self.assertPathExists(zip_checksumfile)
1847
1848 if include_subprojects:
1849 # Verify that without --include-subprojects we have files from
1850 # the main project and also files from subprojects part of the
1851 # main vcs repository.
1852 z = zipfile.ZipFile(zip_distfile)
1853 expected = ['disttest-1.4.3/',
1854 'disttest-1.4.3/meson.build',
1855 'disttest-1.4.3/distexe.c']
1856 if vcs_add_all:
1857 expected += ['disttest-1.4.3/subprojects/',
1858 'disttest-1.4.3/subprojects/samerepo/',
1859 'disttest-1.4.3/subprojects/samerepo/meson.build']
1860 self.assertEqual(sorted(expected),
1861 sorted(z.namelist()))
1862 # Verify that with --include-subprojects we now also have files
1863 # from tarball and separate vcs subprojects. But not files from
1864 # unused subprojects.
1865 self._run(self.meson_command + ['dist', '--formats', 'zip', '--include-subprojects'],
1866 workdir=self.builddir)
1867 z = zipfile.ZipFile(zip_distfile)
1868 expected += ['disttest-1.4.3/subprojects/tarballsub/',
1869 'disttest-1.4.3/subprojects/tarballsub/meson.build',
1870 'disttest-1.4.3/subprojects/vcssub/',
1871 'disttest-1.4.3/subprojects/vcssub/meson.build']
1872 self.assertEqual(sorted(expected),
1873 sorted(z.namelist()))
1874 if vcs_add_all:
1875 # Verify we can distribute separately subprojects in the same vcs
1876 # repository as the main project.
1877 subproject_dir = os.path.join(project_dir, 'subprojects', 'samerepo')
1878 self.new_builddir()
1879 self.init(subproject_dir)
1880 self.build('dist')
1881 xz_distfile = os.path.join(self.distdir, 'samerepo-1.0.tar.xz')
1882 xz_checksumfile = xz_distfile + '.sha256sum'
1883 self.assertPathExists(xz_distfile)
1884 self.assertPathExists(xz_checksumfile)
1885 tar = tarfile.open(xz_distfile, "r:xz") # [ignore encoding]
1886 self.assertEqual(sorted(['samerepo-1.0',
1887 'samerepo-1.0/meson.build']),
1888 sorted(i.name for i in tar))
1889
1890 def test_rpath_uses_ORIGIN(self):
1891 '''
1892 Test that built targets use $ORIGIN in rpath, which ensures that they
1893 are relocatable and ensures that builds are reproducible since the
1894 build directory won't get embedded into the built binaries.
1895 '''
1896 if is_windows() or is_cygwin():
1897 raise SkipTest('Windows PE/COFF binaries do not use RPATH')
1898 testdir = os.path.join(self.common_test_dir, '39 library chain')
1899 self.init(testdir)
1900 self.build()
1901 for each in ('prog', 'subdir/liblib1.so', ):
1902 rpath = get_rpath(os.path.join(self.builddir, each))
1903 self.assertTrue(rpath, f'Rpath could not be determined for {each}.')
1904 if is_dragonflybsd():
1905 # DragonFly BSD will prepend /usr/lib/gccVERSION to the rpath,
1906 # so ignore that.
1907 self.assertTrue(rpath.startswith('/usr/lib/gcc'))
1908 rpaths = rpath.split(':')[1:]
1909 else:
1910 rpaths = rpath.split(':')
1911 for path in rpaths:
1912 self.assertTrue(path.startswith('$ORIGIN'), msg=(each, path))
1913 # These two don't link to anything else, so they do not need an rpath entry.
1914 for each in ('subdir/subdir2/liblib2.so', 'subdir/subdir3/liblib3.so'):
1915 rpath = get_rpath(os.path.join(self.builddir, each))
1916 if is_dragonflybsd():
1917 # The rpath should be equal to /usr/lib/gccVERSION
1918 self.assertTrue(rpath.startswith('/usr/lib/gcc'))
1919 self.assertEqual(len(rpath.split(':')), 1)
1920 else:
1921 self.assertIsNone(rpath)
1922
1923 def test_dash_d_dedup(self):
1924 testdir = os.path.join(self.unit_test_dir, '9 d dedup')
1925 self.init(testdir)
1926 cmd = self.get_compdb()[0]['command']
1927 self.assertTrue('-D FOO -D BAR' in cmd or
1928 '"-D" "FOO" "-D" "BAR"' in cmd or
1929 '/D FOO /D BAR' in cmd or
1930 '"/D" "FOO" "/D" "BAR"' in cmd)
1931
1932 def test_all_forbidden_targets_tested(self):
1933 '''
1934 Test that all forbidden targets are tested in the '150 reserved targets'
1935 test. Needs to be a unit test because it accesses Meson internals.
1936 '''
1937 testdir = os.path.join(self.common_test_dir, '150 reserved targets')
1938 targets = set(mesonbuild.coredata.FORBIDDEN_TARGET_NAMES)
1939 # We don't actually define a target with this name
1940 targets.remove('build.ninja')
1941 # Remove this to avoid multiple entries with the same name
1942 # but different case.
1943 targets.remove('PHONY')
1944 for i in targets:
1945 self.assertPathExists(os.path.join(testdir, i))
1946
1947 def detect_prebuild_env(self):
1948 env = get_fake_env()
1949 cc = detect_c_compiler(env, MachineChoice.HOST)
1950 stlinker = detect_static_linker(env, cc)
1951 if is_windows():
1952 object_suffix = 'obj'
1953 shared_suffix = 'dll'
1954 elif is_cygwin():
1955 object_suffix = 'o'
1956 shared_suffix = 'dll'
1957 elif is_osx():
1958 object_suffix = 'o'
1959 shared_suffix = 'dylib'
1960 else:
1961 object_suffix = 'o'
1962 shared_suffix = 'so'
1963 return (cc, stlinker, object_suffix, shared_suffix)
1964
1965 def detect_prebuild_env_versioned(self):
1966 (cc, stlinker, object_suffix, shared_suffix) = self.detect_prebuild_env()
1967 shared_suffixes = [shared_suffix]
1968 if shared_suffix == 'so':
1969 # .so may have version information integrated into the filename
1970 shared_suffixes += ['so.1', 'so.1.2.3', '1.so', '1.so.2.3']
1971 return (cc, stlinker, object_suffix, shared_suffixes)
1972
1973 def pbcompile(self, compiler, source, objectfile, extra_args=None):
1974 cmd = compiler.get_exelist()
1975 extra_args = extra_args or []
1976 if compiler.get_argument_syntax() == 'msvc':
1977 cmd += ['/nologo', '/Fo' + objectfile, '/c', source] + extra_args
1978 else:
1979 cmd += ['-c', source, '-o', objectfile] + extra_args
1980 subprocess.check_call(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
1981
1982 def test_prebuilt_object(self):
1983 (compiler, _, object_suffix, _) = self.detect_prebuild_env()
1984 tdir = os.path.join(self.unit_test_dir, '15 prebuilt object')
1985 source = os.path.join(tdir, 'source.c')
1986 objectfile = os.path.join(tdir, 'prebuilt.' + object_suffix)
1987 self.pbcompile(compiler, source, objectfile)
1988 try:
1989 self.init(tdir)
1990 self.build()
1991 self.run_tests()
1992 finally:
1993 os.unlink(objectfile)
1994
1995 def build_static_lib(self, compiler, linker, source, objectfile, outfile, extra_args=None):
1996 if extra_args is None:
1997 extra_args = []
1998 link_cmd = linker.get_exelist()
1999 link_cmd += linker.get_always_args()
2000 link_cmd += linker.get_std_link_args(get_fake_env(), False)
2001 link_cmd += linker.get_output_args(outfile)
2002 link_cmd += [objectfile]
2003 self.pbcompile(compiler, source, objectfile, extra_args=extra_args)
2004 try:
2005 subprocess.check_call(link_cmd)
2006 finally:
2007 os.unlink(objectfile)
2008
2009 def test_prebuilt_static_lib(self):
2010 (cc, stlinker, object_suffix, _) = self.detect_prebuild_env()
2011 tdir = os.path.join(self.unit_test_dir, '16 prebuilt static')
2012 source = os.path.join(tdir, 'libdir/best.c')
2013 objectfile = os.path.join(tdir, 'libdir/best.' + object_suffix)
2014 stlibfile = os.path.join(tdir, 'libdir/libbest.a')
2015 self.build_static_lib(cc, stlinker, source, objectfile, stlibfile)
2016 # Run the test
2017 try:
2018 self.init(tdir)
2019 self.build()
2020 self.run_tests()
2021 finally:
2022 os.unlink(stlibfile)
2023
2024 def build_shared_lib(self, compiler, source, objectfile, outfile, impfile, extra_args=None):
2025 if extra_args is None:
2026 extra_args = []
2027 if compiler.get_argument_syntax() == 'msvc':
2028 link_cmd = compiler.get_linker_exelist() + [
2029 '/NOLOGO', '/DLL', '/DEBUG', '/IMPLIB:' + impfile,
2030 '/OUT:' + outfile, objectfile]
2031 else:
2032 if not (compiler.info.is_windows() or compiler.info.is_cygwin() or compiler.info.is_darwin()):
2033 extra_args += ['-fPIC']
2034 link_cmd = compiler.get_exelist() + ['-shared', '-o', outfile, objectfile]
2035 if not is_osx():
2036 link_cmd += ['-Wl,-soname=' + os.path.basename(outfile)]
2037 self.pbcompile(compiler, source, objectfile, extra_args=extra_args)
2038 try:
2039 subprocess.check_call(link_cmd)
2040 finally:
2041 os.unlink(objectfile)
2042
2043 def test_prebuilt_shared_lib(self):
2044 (cc, _, object_suffix, shared_suffix) = self.detect_prebuild_env()
2045 tdir = self.copy_srcdir(os.path.join(self.unit_test_dir, '17 prebuilt shared'))
2046 source = os.path.join(tdir, 'alexandria.c')
2047 objectfile = os.path.join(tdir, 'alexandria.' + object_suffix)
2048 impfile = os.path.join(tdir, 'alexandria.lib')
2049 if cc.get_argument_syntax() == 'msvc':
2050 shlibfile = os.path.join(tdir, 'alexandria.' + shared_suffix)
2051 elif is_cygwin():
2052 shlibfile = os.path.join(tdir, 'cygalexandria.' + shared_suffix)
2053 else:
2054 shlibfile = os.path.join(tdir, 'libalexandria.' + shared_suffix)
2055 self.build_shared_lib(cc, source, objectfile, shlibfile, impfile)
2056
2057 if is_windows():
2058 def cleanup() -> None:
2059 """Clean up all the garbage MSVC writes in the source tree."""
2060
2061 for fname in glob(os.path.join(tdir, 'alexandria.*')):
2062 if os.path.splitext(fname)[1] not in {'.c', '.h'}:
2063 os.unlink(fname)
2064 self.addCleanup(cleanup)
2065 else:
2066 self.addCleanup(os.unlink, shlibfile)
2067
2068 # Run the test
2069 self.init(tdir)
2070 self.build()
2071 self.run_tests()
2072
2073 def test_prebuilt_shared_lib_rpath(self) -> None:
2074 (cc, _, object_suffix, shared_suffix) = self.detect_prebuild_env()
2075 tdir = os.path.join(self.unit_test_dir, '17 prebuilt shared')
2076 with tempfile.TemporaryDirectory() as d:
2077 source = os.path.join(tdir, 'alexandria.c')
2078 objectfile = os.path.join(d, 'alexandria.' + object_suffix)
2079 impfile = os.path.join(d, 'alexandria.lib')
2080 if cc.get_argument_syntax() == 'msvc':
2081 shlibfile = os.path.join(d, 'alexandria.' + shared_suffix)
2082 elif is_cygwin():
2083 shlibfile = os.path.join(d, 'cygalexandria.' + shared_suffix)
2084 else:
2085 shlibfile = os.path.join(d, 'libalexandria.' + shared_suffix)
2086 # Ensure MSVC extra files end up in the directory that gets deleted
2087 # at the end
2088 with chdir(d):
2089 self.build_shared_lib(cc, source, objectfile, shlibfile, impfile)
2090
2091 # Run the test
2092 self.init(tdir, extra_args=[f'-Dsearch_dir={d}'])
2093 self.build()
2094 self.run_tests()
2095
2096 @skipIfNoPkgconfig
2097 def test_prebuilt_shared_lib_pkg_config(self) -> None:
2098 (cc, _, object_suffix, shared_suffixes) = self.detect_prebuild_env_versioned()
2099 tdir = os.path.join(self.unit_test_dir, '17 prebuilt shared')
2100 for shared_suffix in shared_suffixes:
2101 with tempfile.TemporaryDirectory() as d:
2102 source = os.path.join(tdir, 'alexandria.c')
2103 objectfile = os.path.join(d, 'alexandria.' + object_suffix)
2104 impfile = os.path.join(d, 'alexandria.lib')
2105 if cc.get_argument_syntax() == 'msvc':
2106 shlibfile = os.path.join(d, 'alexandria.' + shared_suffix)
2107 linkfile = impfile # MSVC links against the *.lib instead of the *.dll
2108 elif is_cygwin():
2109 shlibfile = os.path.join(d, 'cygalexandria.' + shared_suffix)
2110 linkfile = shlibfile
2111 else:
2112 shlibfile = os.path.join(d, 'libalexandria.' + shared_suffix)
2113 linkfile = shlibfile
2114 # Ensure MSVC extra files end up in the directory that gets deleted
2115 # at the end
2116 with chdir(d):
2117 self.build_shared_lib(cc, source, objectfile, shlibfile, impfile)
2118
2119 with open(os.path.join(d, 'alexandria.pc'), 'w',
2120 encoding='utf-8') as f:
2121 f.write(textwrap.dedent('''
2122 Name: alexandria
2123 Description: alexandria
2124 Version: 1.0.0
2125 Libs: {}
2126 ''').format(
2127 Path(linkfile).as_posix().replace(' ', r'\ '),
2128 ))
2129
2130 # Run the test
2131 self.init(tdir, override_envvars={'PKG_CONFIG_PATH': d},
2132 extra_args=['-Dmethod=pkg-config'])
2133 self.build()
2134 self.run_tests()
2135
2136 self.wipe()
2137
2138 @skip_if_no_cmake
2139 def test_prebuilt_shared_lib_cmake(self) -> None:
2140 (cc, _, object_suffix, shared_suffixes) = self.detect_prebuild_env_versioned()
2141 tdir = os.path.join(self.unit_test_dir, '17 prebuilt shared')
2142 for shared_suffix in shared_suffixes:
2143 with tempfile.TemporaryDirectory() as d:
2144 source = os.path.join(tdir, 'alexandria.c')
2145 objectfile = os.path.join(d, 'alexandria.' + object_suffix)
2146 impfile = os.path.join(d, 'alexandria.lib')
2147 if cc.get_argument_syntax() == 'msvc':
2148 shlibfile = os.path.join(d, 'alexandria.' + shared_suffix)
2149 linkfile = impfile # MSVC links against the *.lib instead of the *.dll
2150 elif is_cygwin():
2151 shlibfile = os.path.join(d, 'cygalexandria.' + shared_suffix)
2152 linkfile = shlibfile
2153 else:
2154 shlibfile = os.path.join(d, 'libalexandria.' + shared_suffix)
2155 linkfile = shlibfile
2156 # Ensure MSVC extra files end up in the directory that gets deleted
2157 # at the end
2158 with chdir(d):
2159 self.build_shared_lib(cc, source, objectfile, shlibfile, impfile)
2160
2161 with open(os.path.join(d, 'alexandriaConfig.cmake'), 'w',
2162 encoding='utf-8') as f:
2163 f.write(textwrap.dedent('''
2164 set(alexandria_FOUND ON)
2165 set(alexandria_LIBRARIES "{}")
2166 set(alexandria_INCLUDE_DIRS "{}")
2167 ''').format(
2168 re.sub(r'([\\"])', r'\\\1', linkfile),
2169 re.sub(r'([\\"])', r'\\\1', tdir),
2170 ))
2171
2172 # Run the test
2173 self.init(tdir, override_envvars={'CMAKE_PREFIX_PATH': d},
2174 extra_args=['-Dmethod=cmake'])
2175 self.build()
2176 self.run_tests()
2177
2178 self.wipe()
2179
2180 def test_prebuilt_shared_lib_rpath_same_prefix(self) -> None:
2181 (cc, _, object_suffix, shared_suffix) = self.detect_prebuild_env()
2182 orig_tdir = os.path.join(self.unit_test_dir, '17 prebuilt shared')
2183
2184 # Put the shared library in a location that shares a common prefix with
2185 # the source directory:
2186 #
2187 # .../
2188 # foo-lib/
2189 # libalexandria.so
2190 # foo/
2191 # meson.build
2192 # ...
2193 #
2194 # This allows us to check that the .../foo-lib/libalexandria.so path is
2195 # preserved correctly when meson processes it.
2196 with tempfile.TemporaryDirectory() as d:
2197 libdir = os.path.join(d, 'foo-lib')
2198 os.mkdir(libdir)
2199
2200 source = os.path.join(orig_tdir, 'alexandria.c')
2201 objectfile = os.path.join(libdir, 'alexandria.' + object_suffix)
2202 impfile = os.path.join(libdir, 'alexandria.lib')
2203 if cc.get_argument_syntax() == 'msvc':
2204 shlibfile = os.path.join(libdir, 'alexandria.' + shared_suffix)
2205 elif is_cygwin():
2206 shlibfile = os.path.join(libdir, 'cygalexandria.' + shared_suffix)
2207 else:
2208 shlibfile = os.path.join(libdir, 'libalexandria.' + shared_suffix)
2209 # Ensure MSVC extra files end up in the directory that gets deleted
2210 # at the end
2211 with chdir(libdir):
2212 self.build_shared_lib(cc, source, objectfile, shlibfile, impfile)
2213
2214 tdir = os.path.join(d, 'foo')
2215 shutil.copytree(orig_tdir, tdir)
2216
2217 # Run the test
2218 self.init(tdir, extra_args=[f'-Dsearch_dir={libdir}'])
2219 self.build()
2220 self.run_tests()
2221
2222 def test_underscore_prefix_detection_list(self) -> None:
2223 '''
2224 Test the underscore detection hardcoded lookup list
2225 against what was detected in the binary.
2226 '''
2227 env, cc = get_convincing_fake_env_and_cc(self.builddir, self.prefix)
2228 expected_uscore = cc._symbols_have_underscore_prefix_searchbin()
2229 list_uscore = cc._symbols_have_underscore_prefix_list()
2230 if list_uscore is not None:
2231 self.assertEqual(list_uscore, expected_uscore)
2232 else:
2233 raise SkipTest('No match in underscore prefix list for this platform.')
2234
2235 def test_underscore_prefix_detection_define(self) -> None:
2236 '''
2237 Test the underscore detection based on compiler-defined preprocessor macro
2238 against what was detected in the binary.
2239 '''
2240 env, cc = get_convincing_fake_env_and_cc(self.builddir, self.prefix)
2241 expected_uscore = cc._symbols_have_underscore_prefix_searchbin()
2242 define_uscore = cc._symbols_have_underscore_prefix_define()
2243 if define_uscore is not None:
2244 self.assertEqual(define_uscore, expected_uscore)
2245 else:
2246 raise SkipTest('Did not find the underscore prefix define __USER_LABEL_PREFIX__')
2247
2248 @skipIfNoPkgconfig
2249 def test_pkgconfig_static(self):
2250 '''
2251 Test that the we prefer static libraries when `static: true` is
2252 passed to dependency() with pkg-config. Can't be an ordinary test
2253 because we need to build libs and try to find them from meson.build
2254
2255 Also test that it's not a hard error to have unsatisfiable library deps
2256 since system libraries -lm will never be found statically.
2257 https://github.com/mesonbuild/meson/issues/2785
2258 '''
2259 (cc, stlinker, objext, shext) = self.detect_prebuild_env()
2260 testdir = os.path.join(self.unit_test_dir, '18 pkgconfig static')
2261 source = os.path.join(testdir, 'foo.c')
2262 objectfile = os.path.join(testdir, 'foo.' + objext)
2263 stlibfile = os.path.join(testdir, 'libfoo.a')
2264 impfile = os.path.join(testdir, 'foo.lib')
2265 if cc.get_argument_syntax() == 'msvc':
2266 shlibfile = os.path.join(testdir, 'foo.' + shext)
2267 elif is_cygwin():
2268 shlibfile = os.path.join(testdir, 'cygfoo.' + shext)
2269 else:
2270 shlibfile = os.path.join(testdir, 'libfoo.' + shext)
2271 # Build libs
2272 self.build_static_lib(cc, stlinker, source, objectfile, stlibfile, extra_args=['-DFOO_STATIC'])
2273 self.build_shared_lib(cc, source, objectfile, shlibfile, impfile)
2274 # Run test
2275 try:
2276 self.init(testdir, override_envvars={'PKG_CONFIG_LIBDIR': self.builddir})
2277 self.build()
2278 self.run_tests()
2279 finally:
2280 os.unlink(stlibfile)
2281 os.unlink(shlibfile)
2282 if is_windows():
2283 # Clean up all the garbage MSVC writes in the
2284 # source tree.
2285 for fname in glob(os.path.join(testdir, 'foo.*')):
2286 if os.path.splitext(fname)[1] not in ['.c', '.h', '.in']:
2287 os.unlink(fname)
2288
2289 @skipIfNoPkgconfig
2290 @mock.patch.dict(os.environ)
2291 def test_pkgconfig_gen_escaping(self):
2292 testdir = os.path.join(self.common_test_dir, '44 pkgconfig-gen')
2293 prefix = '/usr/with spaces'
2294 libdir = 'lib'
2295 self.init(testdir, extra_args=['--prefix=' + prefix,
2296 '--libdir=' + libdir])
2297 # Find foo dependency
2298 os.environ['PKG_CONFIG_LIBDIR'] = self.privatedir
2299 env = get_fake_env(testdir, self.builddir, self.prefix)
2300 kwargs = {'required': True, 'silent': True, 'native': MachineChoice.HOST}
2301 foo_dep = PkgConfigDependency('libanswer', env, kwargs)
2302 # Ensure link_args are properly quoted
2303 libdir = PurePath(prefix) / PurePath(libdir)
2304 link_args = ['-L' + libdir.as_posix(), '-lanswer']
2305 self.assertEqual(foo_dep.get_link_args(), link_args)
2306 # Ensure include args are properly quoted
2307 incdir = PurePath(prefix) / PurePath('include')
2308 cargs = ['-I' + incdir.as_posix(), '-DLIBFOO']
2309 # pkg-config and pkgconf does not respect the same order
2310 self.assertEqual(sorted(foo_dep.get_compile_args()), sorted(cargs))
2311
2312 @skipIfNoPkgconfig
2313 def test_pkgconfig_relocatable(self):
2314 '''
2315 Test that it generates relocatable pkgconfig when module
2316 option pkgconfig.relocatable=true.
2317 '''
2318 testdir_rel = os.path.join(self.common_test_dir, '44 pkgconfig-gen')
2319 self.init(testdir_rel, extra_args=['-Dpkgconfig.relocatable=true'])
2320
2321 def check_pcfile(name, *, relocatable, levels=2):
2322 with open(os.path.join(self.privatedir, name), encoding='utf-8') as f:
2323 pcfile = f.read()
2324 # The pkgconfig module always uses posix path regardless of platform
2325 prefix_rel = PurePath('${pcfiledir}', *(['..'] * levels)).as_posix()
2326 (self.assertIn if relocatable else self.assertNotIn)(
2327 f'prefix={prefix_rel}\n',
2328 pcfile)
2329
2330 check_pcfile('libvartest.pc', relocatable=True)
2331 check_pcfile('libvartest2.pc', relocatable=True)
2332
2333 self.wipe()
2334 self.init(testdir_rel, extra_args=['-Dpkgconfig.relocatable=false'])
2335
2336 check_pcfile('libvartest.pc', relocatable=False)
2337 check_pcfile('libvartest2.pc', relocatable=False)
2338
2339 self.wipe()
2340 testdir_abs = os.path.join(self.unit_test_dir, '105 pkgconfig relocatable with absolute path')
2341 self.init(testdir_abs)
2342
2343 check_pcfile('libsimple.pc', relocatable=True, levels=3)
2344
2345 def test_array_option_change(self):
2346 def get_opt():
2347 opts = self.introspect('--buildoptions')
2348 for x in opts:
2349 if x.get('name') == 'list':
2350 return x
2351 raise Exception(opts)
2352
2353 expected = {
2354 'name': 'list',
2355 'description': 'list',
2356 'section': 'user',
2357 'type': 'array',
2358 'value': ['foo', 'bar'],
2359 'choices': ['foo', 'bar', 'oink', 'boink'],
2360 'machine': 'any',
2361 }
2362 tdir = os.path.join(self.unit_test_dir, '19 array option')
2363 self.init(tdir)
2364 original = get_opt()
2365 self.assertDictEqual(original, expected)
2366
2367 expected['value'] = ['oink', 'boink']
2368 self.setconf('-Dlist=oink,boink')
2369 changed = get_opt()
2370 self.assertEqual(changed, expected)
2371
2372 def test_array_option_bad_change(self):
2373 def get_opt():
2374 opts = self.introspect('--buildoptions')
2375 for x in opts:
2376 if x.get('name') == 'list':
2377 return x
2378 raise Exception(opts)
2379
2380 expected = {
2381 'name': 'list',
2382 'description': 'list',
2383 'section': 'user',
2384 'type': 'array',
2385 'value': ['foo', 'bar'],
2386 'choices': ['foo', 'bar', 'oink', 'boink'],
2387 'machine': 'any',
2388 }
2389 tdir = os.path.join(self.unit_test_dir, '19 array option')
2390 self.init(tdir)
2391 original = get_opt()
2392 self.assertDictEqual(original, expected)
2393 with self.assertRaises(subprocess.CalledProcessError):
2394 self.setconf('-Dlist=bad')
2395 changed = get_opt()
2396 self.assertDictEqual(changed, expected)
2397
2398 def test_array_option_empty_equivalents(self):
2399 """Array options treat -Dopt=[] and -Dopt= as equivalent."""
2400 def get_opt():
2401 opts = self.introspect('--buildoptions')
2402 for x in opts:
2403 if x.get('name') == 'list':
2404 return x
2405 raise Exception(opts)
2406
2407 expected = {
2408 'name': 'list',
2409 'description': 'list',
2410 'section': 'user',
2411 'type': 'array',
2412 'value': [],
2413 'choices': ['foo', 'bar', 'oink', 'boink'],
2414 'machine': 'any',
2415 }
2416 tdir = os.path.join(self.unit_test_dir, '19 array option')
2417 self.init(tdir, extra_args='-Dlist=')
2418 original = get_opt()
2419 self.assertDictEqual(original, expected)
2420
2421 def test_executable_names(self):
2422 testdir = os.path.join(self.unit_test_dir, '121 executable suffix')
2423 self.init(testdir)
2424 self.build()
2425 exe1 = os.path.join(self.builddir, 'foo' + exe_suffix)
2426 exe2 = os.path.join(self.builddir, 'foo.bin')
2427 self.assertPathExists(exe1)
2428 self.assertPathExists(exe2)
2429 self.assertNotEqual(exe1, exe2)
2430
2431 # Wipe and run the compile command against the target names
2432 self.init(testdir, extra_args=['--wipe'])
2433 self._run([*self.meson_command, 'compile', '-C', self.builddir, './foo'])
2434 self._run([*self.meson_command, 'compile', '-C', self.builddir, './foo.bin'])
2435 self.assertPathExists(exe1)
2436 self.assertPathExists(exe2)
2437 self.assertNotEqual(exe1, exe2)
2438
2439
2440 def opt_has(self, name, value):
2441 res = self.introspect('--buildoptions')
2442 found = False
2443 for i in res:
2444 if i['name'] == name:
2445 self.assertEqual(i['value'], value)
2446 found = True
2447 break
2448 self.assertTrue(found, "Array option not found in introspect data.")
2449
2450 def test_free_stringarray_setting(self):
2451 testdir = os.path.join(self.common_test_dir, '40 options')
2452 self.init(testdir)
2453 self.opt_has('free_array_opt', [])
2454 self.setconf('-Dfree_array_opt=foo,bar', will_build=False)
2455 self.opt_has('free_array_opt', ['foo', 'bar'])
2456 self.setconf("-Dfree_array_opt=['a,b', 'c,d']", will_build=False)
2457 self.opt_has('free_array_opt', ['a,b', 'c,d'])
2458
2459 # When running under Travis Mac CI, the file updates seem to happen
2460 # too fast so the timestamps do not get properly updated.
2461 # Call this method before file operations in appropriate places
2462 # to make things work.
2463 def mac_ci_delay(self):
2464 if IS_CI and is_osx():
2465 import time
2466 time.sleep(1)
2467
2468 def test_options_with_choices_changing(self) -> None:
2469 """Detect when options like arrays or combos have their choices change."""
2470 testdir = Path(os.path.join(self.unit_test_dir, '83 change option choices'))
2471 options1 = str(testdir / 'meson_options.1.txt')
2472 options2 = str(testdir / 'meson_options.2.txt')
2473
2474 # Test that old options are changed to the new defaults if they are not valid
2475 real_options = str(testdir / 'meson_options.txt')
2476 self.addCleanup(os.unlink, real_options)
2477
2478 shutil.copy(options1, real_options)
2479 self.init(str(testdir))
2480 self.mac_ci_delay()
2481 shutil.copy(options2, real_options)
2482
2483 self.build()
2484 opts = self.introspect('--buildoptions')
2485 for item in opts:
2486 if item['name'] == 'combo':
2487 self.assertEqual(item['value'], 'b')
2488 self.assertEqual(item['choices'], ['b', 'c', 'd'])
2489 elif item['name'] == 'array':
2490 self.assertEqual(item['value'], ['b'])
2491 self.assertEqual(item['choices'], ['b', 'c', 'd'])
2492
2493 self.wipe()
2494 self.mac_ci_delay()
2495
2496 # When the old options are valid they should remain
2497 shutil.copy(options1, real_options)
2498 self.init(str(testdir), extra_args=['-Dcombo=c', '-Darray=b,c'])
2499 self.mac_ci_delay()
2500 shutil.copy(options2, real_options)
2501 self.build()
2502 opts = self.introspect('--buildoptions')
2503 for item in opts:
2504 if item['name'] == 'combo':
2505 self.assertEqual(item['value'], 'c')
2506 self.assertEqual(item['choices'], ['b', 'c', 'd'])
2507 elif item['name'] == 'array':
2508 self.assertEqual(item['value'], ['b', 'c'])
2509 self.assertEqual(item['choices'], ['b', 'c', 'd'])
2510
2511 def test_options_listed_in_build_options(self) -> None:
2512 """Detect when changed options become listed in build options."""
2513 testdir = os.path.join(self.unit_test_dir, '113 list build options')
2514
2515 out = self.init(testdir)
2516 for line in out.splitlines():
2517 if line.startswith('Message: Build options:'):
2518 self.assertNotIn('-Dauto_features=auto', line)
2519 self.assertNotIn('-Doptional=auto', line)
2520
2521 self.wipe()
2522 self.mac_ci_delay()
2523
2524 out = self.init(testdir, extra_args=['-Dauto_features=disabled', '-Doptional=enabled'])
2525 for line in out.splitlines():
2526 if line.startswith('Message: Build options:'):
2527 self.assertIn('-Dauto_features=disabled', line)
2528 self.assertIn('-Doptional=enabled', line)
2529
2530 self.setconf('-Doptional=disabled')
2531 out = self.build()
2532 for line in out.splitlines():
2533 if line.startswith('Message: Build options:'):
2534 self.assertIn('-Dauto_features=disabled', line)
2535 self.assertNotIn('-Doptional=enabled', line)
2536 self.assertIn('-Doptional=disabled', line)
2537
2538 def test_subproject_promotion(self):
2539 testdir = os.path.join(self.unit_test_dir, '12 promote')
2540 workdir = os.path.join(self.builddir, 'work')
2541 shutil.copytree(testdir, workdir)
2542 spdir = os.path.join(workdir, 'subprojects')
2543 s3dir = os.path.join(spdir, 's3')
2544 scommondir = os.path.join(spdir, 'scommon')
2545 self.assertFalse(os.path.isdir(s3dir))
2546 subprocess.check_call(self.wrap_command + ['promote', 's3'],
2547 cwd=workdir,
2548 stdout=subprocess.DEVNULL)
2549 self.assertTrue(os.path.isdir(s3dir))
2550 self.assertFalse(os.path.isdir(scommondir))
2551 self.assertNotEqual(subprocess.call(self.wrap_command + ['promote', 'scommon'],
2552 cwd=workdir,
2553 stderr=subprocess.DEVNULL), 0)
2554 self.assertNotEqual(subprocess.call(self.wrap_command + ['promote', 'invalid/path/to/scommon'],
2555 cwd=workdir,
2556 stderr=subprocess.DEVNULL), 0)
2557 self.assertFalse(os.path.isdir(scommondir))
2558 subprocess.check_call(self.wrap_command + ['promote', 'subprojects/s2/subprojects/scommon'], cwd=workdir)
2559 self.assertTrue(os.path.isdir(scommondir))
2560 promoted_wrap = os.path.join(spdir, 'athing.wrap')
2561 self.assertFalse(os.path.isfile(promoted_wrap))
2562 subprocess.check_call(self.wrap_command + ['promote', 'athing'], cwd=workdir)
2563 self.assertTrue(os.path.isfile(promoted_wrap))
2564 self.new_builddir() # Ensure builddir is not parent or workdir
2565 self.init(workdir)
2566 self.build()
2567
2568 def test_subproject_promotion_wrap(self):
2569 testdir = os.path.join(self.unit_test_dir, '43 promote wrap')
2570 workdir = os.path.join(self.builddir, 'work')
2571 shutil.copytree(testdir, workdir)
2572 spdir = os.path.join(workdir, 'subprojects')
2573
2574 ambiguous_wrap = os.path.join(spdir, 'ambiguous.wrap')
2575 self.assertNotEqual(subprocess.call(self.wrap_command + ['promote', 'ambiguous'],
2576 cwd=workdir,
2577 stderr=subprocess.DEVNULL), 0)
2578 self.assertFalse(os.path.isfile(ambiguous_wrap))
2579 subprocess.check_call(self.wrap_command + ['promote', 'subprojects/s2/subprojects/ambiguous.wrap'], cwd=workdir)
2580 self.assertTrue(os.path.isfile(ambiguous_wrap))
2581
2582 def test_warning_location(self):
2583 tdir = os.path.join(self.unit_test_dir, '22 warning location')
2584 out = self.init(tdir)
2585 for expected in [
2586 r'meson.build:4: WARNING: Keyword argument "link_with" defined multiple times.',
2587 r'sub' + os.path.sep + r'meson.build:3: WARNING: Keyword argument "link_with" defined multiple times.',
2588 r'meson.build:6: WARNING: a warning of some sort',
2589 r'sub' + os.path.sep + r'meson.build:4: WARNING: subdir warning',
2590 r'meson.build:7: WARNING: Module SIMD has no backwards or forwards compatibility and might not exist in future releases.',
2591 r"meson.build:11: WARNING: The variable(s) 'MISSING' in the input file 'conf.in' are not present in the given configuration data.",
2592 ]:
2593 with self.subTest(expected):
2594 self.assertRegex(out, re.escape(expected))
2595
2596 for wd in [
2597 self.src_root,
2598 self.builddir,
2599 os.getcwd(),
2600 ]:
2601 with self.subTest(wd):
2602 self.new_builddir()
2603 out = self.init(tdir, workdir=wd)
2604 expected = os.path.join(relpath(tdir, self.src_root), 'meson.build')
2605 relwd = relpath(self.src_root, wd)
2606 if relwd != '.':
2607 expected = os.path.join(relwd, expected)
2608 expected = '\n' + expected + ':'
2609 self.assertIn(expected, out)
2610
2611 def test_error_location_path(self):
2612 '''Test locations in meson errors contain correct paths'''
2613 # this list contains errors from all the different steps in the
2614 # lexer/parser/interpreter we have tests for.
2615 for (t, f) in [
2616 ('10 out of bounds', 'meson.build'),
2617 ('17 wrong plusassign', 'meson.build'),
2618 ('55 bad option argument', 'meson_options.txt'),
2619 ('93 subdir parse error', os.path.join('subdir', 'meson.build')),
2620 ('94 invalid option file', 'meson_options.txt'),
2621 ]:
2622 tdir = os.path.join(self.src_root, 'test cases', 'failing', t)
2623
2624 for wd in [
2625 self.src_root,
2626 self.builddir,
2627 os.getcwd(),
2628 ]:
2629 try:
2630 self.init(tdir, workdir=wd)
2631 except subprocess.CalledProcessError as e:
2632 expected = os.path.join('test cases', 'failing', t, f)
2633 relwd = relpath(self.src_root, wd)
2634 if relwd != '.':
2635 expected = os.path.join(relwd, expected)
2636 expected = '\n' + expected + ':'
2637 self.assertIn(expected, e.output)
2638 else:
2639 self.fail('configure unexpectedly succeeded')
2640
2641 def test_permitted_method_kwargs(self):
2642 tdir = os.path.join(self.unit_test_dir, '25 non-permitted kwargs')
2643 with self.assertRaises(subprocess.CalledProcessError) as cm:
2644 self.init(tdir)
2645 self.assertIn('ERROR: compiler.has_header_symbol got unknown keyword arguments "prefixxx"', cm.exception.output)
2646
2647 def _template_test_fresh(self, lang: Language, target_type: str, env: Environment, ninja: list[str]) -> None:
2648 if is_windows() and lang == 'fortran' and target_type == 'library':
2649 # non-Gfortran Windows Fortran compilers do not do shared libraries in a Fortran standard way
2650 # see "test cases/fortran/6 dynamic"
2651 fc = detect_compiler_for(env, 'fortran', MachineChoice.HOST, True, '')
2652 if fc.get_id() in {'intel-cl', 'pgi'}:
2653 raise SkipTest('The Intel (classic) and PGI fortran compilers do not support standard shared libraries')
2654
2655 # test empty directory
2656 with tempfile.TemporaryDirectory() as tmpdir:
2657 self._run(self.meson_command + ['init', '--language', lang, '--type', target_type],
2658 workdir=tmpdir)
2659 self._run(self.setup_command + ['--backend=ninja', 'builddir'], workdir=tmpdir)
2660 self._run(ninja, workdir=os.path.join(tmpdir, 'builddir'))
2661
2662 # custom executable name
2663 if target_type == 'executable':
2664 with tempfile.TemporaryDirectory() as tmpdir:
2665 self._run(self.meson_command + ['init', '--language', lang, '--type', target_type,
2666 '--executable', 'foobar'],
2667 workdir=tmpdir)
2668 self._run(self.setup_command + ['--backend=ninja', 'builddir'], workdir=tmpdir)
2669 self._run(ninja, workdir=os.path.join(tmpdir, 'builddir'))
2670
2671 if lang not in {'cs', 'java'}:
2672 exe = os.path.join(tmpdir, 'builddir', 'foobar' + exe_suffix)
2673 self.assertTrue(os.path.exists(exe))
2674
2675 def _template_test_dirty(self, lang: Language, target_type: str, env: Environment, ninja: list[str]) -> None:
2676 if is_windows() and lang == 'fortran' and target_type == 'library':
2677 # non-Gfortran Windows Fortran compilers do not do shared libraries in a Fortran standard way
2678 # see "test cases/fortran/6 dynamic"
2679 fc = detect_compiler_for(env, 'fortran', MachineChoice.HOST, True, '')
2680 if fc.get_id() in {'intel-cl', 'pgi'}:
2681 raise SkipTest('The Intel (classic) and PGI fortran compilers do not support standard shared libraries')
2682
2683 # test empty directory
2684 with tempfile.TemporaryDirectory() as tmpdir:
2685 self._run(self.meson_command + ['init', '--language', lang, '--type', target_type],
2686 workdir=tmpdir)
2687 self._run(self.setup_command + ['--backend=ninja', 'builddir'], workdir=tmpdir)
2688 self._run(ninja, workdir=os.path.join(tmpdir, 'builddir'))
2689
2690 # test directory with existing code file
2691 if lang in {'c', 'cpp', 'd'}:
2692 with tempfile.TemporaryDirectory() as tmpdir:
2693 with open(os.path.join(tmpdir, 'foo.' + lang), 'w', encoding='utf-8') as f:
2694 f.write('int main(void) {}')
2695 self._run(self.meson_command + ['init', '-b'], workdir=tmpdir)
2696
2697 elif lang in {'java'}:
2698 with tempfile.TemporaryDirectory() as tmpdir:
2699 with open(os.path.join(tmpdir, 'Foo.' + lang), 'w', encoding='utf-8') as f:
2700 f.write('public class Foo { public static void main() {} }')
2701 self._run(self.meson_command + ['init', '-b'], workdir=tmpdir)
2702
2703 def _test_template(self, lang: Language) -> None:
2704 ninja = mesonbuild.tooldetect.detect_ninja()
2705 if ninja is None:
2706 raise SkipTest('This test currently requires ninja. Fix this once "meson build" works.')
2707
2708 env = get_fake_env(bdir=self.builddir)
2709
2710 extra_lang: Language | None
2711 match lang:
2712 case 'cuda':
2713 extra_lang = 'cpp'
2714 case 'vala':
2715 extra_lang = 'c'
2716 case _:
2717 extra_lang = None
2718
2719 if extra_lang is not None:
2720 try:
2721 comp = detect_compiler_for(env, extra_lang, MachineChoice.HOST, True, '')
2722 except EnvironmentException:
2723 comp = None
2724 if comp is None:
2725 raise SkipTest(f'Could not find compiler for {extra_lang}, which is required for {lang}')
2726
2727 with tempfile.TemporaryDirectory() as d:
2728 try:
2729 comp = detect_compiler_for(env, lang, MachineChoice.HOST, True, '')
2730 if comp is None:
2731 raise SkipTest(f'Could not find compiler for language: {lang}')
2732 comp.sanity_check(d)
2733 except EnvironmentException:
2734 raise SkipTest(f'Compiler for language {lang} failed to sanity check')
2735
2736 for target_type, fresh in itertools.product(('executable', 'library'), (True, False)):
2737 with self.subTest(type=target_type, fresh=fresh):
2738 func = self._template_test_fresh if fresh else self._template_test_dirty
2739 try:
2740 func(lang, target_type, env, ninja)
2741 except subprocess.CalledProcessError as e:
2742 self.fail(e.stdout)
2743
2744 def test_template_c(self) -> None:
2745 self._test_template('c')
2746
2747 def test_template_cpp(self) -> None:
2748 self._test_template('cpp')
2749
2750 def test_template_cs(self) -> None:
2751 self._test_template('cs')
2752
2753 def test_template_cuda(self) -> None:
2754 self._test_template('cuda')
2755
2756 def test_template_d(self) -> None:
2757 if is_osx():
2758 raise SkipTest('The D template fails under MacOS CI, we are unsure why. Patches welcome.')
2759 self._test_template('d')
2760
2761 def test_template_fortran(self) -> None:
2762 self._test_template('fortran')
2763
2764 def test_template_java(self) -> None:
2765 self._test_template('java')
2766
2767 def test_template_objc(self) -> None:
2768 self._test_template('objc')
2769
2770 def test_template_objcpp(self) -> None:
2771 self._test_template('objcpp')
2772
2773 def test_template_rust(self) -> None:
2774 self._test_template('rust')
2775
2776 def test_template_vala(self) -> None:
2777 self._test_template('vala')
2778
2779 def test_compiler_run_command(self):
2780 '''
2781 The test checks that the compiler object can be passed to
2782 run_command().
2783 '''
2784 testdir = os.path.join(self.unit_test_dir, '24 compiler run_command')
2785 self.init(testdir)
2786
2787 def test_identical_target_name_in_subproject_flat_layout(self):
2788 '''
2789 Test that identical targets in different subprojects do not collide
2790 if layout is flat.
2791 '''
2792 testdir = os.path.join(self.common_test_dir, '172 identical target name in subproject flat layout')
2793 self.init(testdir, extra_args=['--layout=flat'])
2794 self.build()
2795
2796 def test_identical_target_name_in_subdir_flat_layout(self):
2797 '''
2798 Test that identical targets in different subdirs do not collide
2799 if layout is flat.
2800 '''
2801 testdir = os.path.join(self.common_test_dir, '181 same target name flat layout')
2802 self.init(testdir, extra_args=['--layout=flat'])
2803 self.build()
2804
2805 def test_flock(self):
2806 exception_raised = False
2807 with tempfile.TemporaryDirectory() as tdir:
2808 with DirectoryLock(tdir, 'lock', DirectoryLockAction.FAIL, 'failed to lock directory'):
2809 try:
2810 with DirectoryLock(tdir, 'lock', DirectoryLockAction.FAIL, 'expected failure'):
2811 pass
2812 except MesonException:
2813 exception_raised = True
2814 self.assertTrue(exception_raised, 'Double locking did not raise exception.')
2815
2816 @skipIf(is_osx(), 'Test not applicable to OSX')
2817 def test_check_module_linking(self):
2818 """
2819 Test that link_with: a shared module issues a warning
2820 https://github.com/mesonbuild/meson/issues/2865
2821 (That an error is raised on OSX is exercised by test failing/78)
2822 """
2823 tdir = os.path.join(self.unit_test_dir, '30 shared_mod linking')
2824 out = self.init(tdir)
2825 msg = ('''DEPRECATION: target prog links against shared module mymod, which is incorrect.
2826 This will be an error in meson 2.0, so please use shared_library() for mymod instead.
2827 If shared_module() was used for mymod because it has references to undefined symbols,
2828 use shared_library() with `override_options: ['b_lundef=false']` instead.''')
2829 self.assertIn(msg, out)
2830
2831 def test_mixed_language_linker_check(self):
2832 testdir = os.path.join(self.unit_test_dir, '96 compiler.links file arg')
2833 self.init(testdir)
2834 cmds = self.get_meson_log_compiler_checks()
2835 self.assertEqual(len(cmds), 5)
2836 # Path to the compilers, gleaned from cc.compiles tests
2837 cc = cmds[0][0]
2838 cxx = cmds[1][0]
2839 # cc.links
2840 self.assertEqual(cmds[2][0], cc)
2841 # cxx.links with C source
2842 self.assertEqual(cmds[3][0], cc)
2843 self.assertEqual(cmds[4][0], cxx)
2844 if self.backend is Backend.ninja:
2845 # updating the file to check causes a reconfigure
2846 #
2847 # only the ninja backend is competent enough to detect reconfigured
2848 # no-op builds without build targets
2849 self.utime(os.path.join(testdir, 'test.c'))
2850 self.assertReconfiguredBuildIsNoop()
2851
2852 def test_ndebug_if_release_disabled(self):
2853 testdir = os.path.join(self.unit_test_dir, '28 ndebug if-release')
2854 self.init(testdir, extra_args=['--buildtype=release', '-Db_ndebug=if-release'])
2855 self.build()
2856 exe = os.path.join(self.builddir, 'main')
2857 self.assertEqual(b'NDEBUG=1', subprocess.check_output(exe).strip())
2858
2859 def test_ndebug_if_release_enabled(self):
2860 testdir = os.path.join(self.unit_test_dir, '28 ndebug if-release')
2861 self.init(testdir, extra_args=['--buildtype=debugoptimized', '-Db_ndebug=if-release'])
2862 self.build()
2863 exe = os.path.join(self.builddir, 'main')
2864 self.assertEqual(b'NDEBUG=0', subprocess.check_output(exe).strip())
2865
2866 def test_guessed_linker_dependencies(self):
2867 '''
2868 Test that meson adds dependencies for libraries based on the final
2869 linker command line.
2870 '''
2871 testdirbase = os.path.join(self.unit_test_dir, '29 guessed linker dependencies')
2872 testdirlib = os.path.join(testdirbase, 'lib')
2873
2874 extra_args = None
2875 libdir_flags = ['-L']
2876 env = get_fake_env(testdirlib, self.builddir, self.prefix)
2877 if detect_c_compiler(env, MachineChoice.HOST).get_id() in {'msvc', 'clang-cl', 'intel-cl'}:
2878 # msvc-like compiler, also test it with msvc-specific flags
2879 libdir_flags += ['/LIBPATH:', '-LIBPATH:']
2880 else:
2881 # static libraries are not linkable with -l with msvc because meson installs them
2882 # as .a files which unix_args_to_native will not know as it expects libraries to use
2883 # .lib as extension. For a DLL the import library is installed as .lib. Thus for msvc
2884 # this tests needs to use shared libraries to test the path resolving logic in the
2885 # dependency generation code path.
2886 extra_args = ['--default-library', 'static']
2887
2888 initial_builddir = self.builddir
2889 initial_installdir = self.installdir
2890
2891 for libdir_flag in libdir_flags:
2892 # build library
2893 self.new_builddir()
2894 self.init(testdirlib, extra_args=extra_args)
2895 self.build()
2896 self.install()
2897 libbuilddir = self.builddir
2898 installdir = self.installdir
2899 libdir = os.path.join(self.installdir, self.prefix.lstrip('/').lstrip('\\'), 'lib')
2900
2901 # build user of library
2902 self.new_builddir()
2903 # replace is needed because meson mangles platform paths passed via LDFLAGS
2904 self.init(os.path.join(testdirbase, 'exe'),
2905 override_envvars={"LDFLAGS": '{}{}'.format(libdir_flag, libdir.replace('\\', '/'))})
2906 self.build()
2907 self.assertBuildIsNoop()
2908
2909 # rebuild library
2910 exebuilddir = self.builddir
2911 self.installdir = installdir
2912 self.builddir = libbuilddir
2913 # Microsoft's compiler is quite smart about touching import libs on changes,
2914 # so ensure that there is actually a change in symbols.
2915 self.setconf('-Dmore_exports=true')
2916 self.build()
2917 self.install()
2918 # no ensure_backend_detects_changes needed because self.setconf did that already
2919
2920 # assert user of library will be rebuild
2921 self.builddir = exebuilddir
2922 self.assertRebuiltTarget('app')
2923
2924 # restore dirs for the next test case
2925 self.installdir = initial_builddir
2926 self.builddir = initial_installdir
2927
2928 def test_conflicting_d_dash_option(self):
2929 testdir = os.path.join(self.unit_test_dir, '37 mixed command line args')
2930 with self.assertRaises((subprocess.CalledProcessError, RuntimeError)) as e:
2931 self.init(testdir, extra_args=['-Dbindir=foo', '--bindir=bar'])
2932 # Just to ensure that we caught the correct error
2933 self.assertIn('as both', e.stderr)
2934
2935 def _test_same_option_twice(self, arg, args):
2936 testdir = os.path.join(self.unit_test_dir, '37 mixed command line args')
2937 self.init(testdir, extra_args=args)
2938 opts = self.introspect('--buildoptions')
2939 for item in opts:
2940 if item['name'] == arg:
2941 self.assertEqual(item['value'], 'bar')
2942 return
2943 raise Exception(f'Missing {arg} value?')
2944
2945 def test_same_dash_option_twice(self):
2946 self._test_same_option_twice('bindir', ['--bindir=foo', '--bindir=bar'])
2947
2948 def test_same_d_option_twice(self):
2949 self._test_same_option_twice('bindir', ['-Dbindir=foo', '-Dbindir=bar'])
2950
2951 def test_same_project_d_option_twice(self):
2952 self._test_same_option_twice('one', ['-Done=foo', '-Done=bar'])
2953
2954 def _test_same_option_twice_configure(self, arg, args):
2955 testdir = os.path.join(self.unit_test_dir, '37 mixed command line args')
2956 self.init(testdir)
2957 self.setconf(args)
2958 opts = self.introspect('--buildoptions')
2959 for item in opts:
2960 if item['name'] == arg:
2961 self.assertEqual(item['value'], 'bar')
2962 return
2963 raise Exception(f'Missing {arg} value?')
2964
2965 def test_same_dash_option_twice_configure(self):
2966 self._test_same_option_twice_configure(
2967 'bindir', ['--bindir=foo', '--bindir=bar'])
2968
2969 def test_same_d_option_twice_configure(self):
2970 self._test_same_option_twice_configure(
2971 'bindir', ['-Dbindir=foo', '-Dbindir=bar'])
2972
2973 def test_same_project_d_option_twice_configure(self):
2974 self._test_same_option_twice_configure(
2975 'one', ['-Done=foo', '-Done=bar'])
2976
2977 def test_command_line(self):
2978 testdir = os.path.join(self.unit_test_dir, '34 command line')
2979
2980 # Verify default values when passing no args that affect the
2981 # configuration, and as a bonus, test that --profile-self works.
2982 out = self.init(testdir, extra_args=['--profile-self', '--fatal-meson-warnings'])
2983 self.assertNotIn('[default: true]', out)
2984 obj = mesonbuild.coredata.load(self.builddir)
2985 self.assertEqual(obj.optstore.get_value_for('default_library'), 'static')
2986 self.assertEqual(obj.optstore.get_value_for('warning_level'), '1')
2987 self.assertEqual(obj.optstore.get_value_for(OptionKey('set_sub_opt', '')), True)
2988 self.assertEqual(obj.optstore.get_value_for(OptionKey('subp_opt', 'subp')), 'default3')
2989 self.wipe()
2990
2991 # warning_level is special, it's --warnlevel instead of --warning-level
2992 # for historical reasons
2993 self.init(testdir, extra_args=['--warnlevel=2', '--fatal-meson-warnings'])
2994 obj = mesonbuild.coredata.load(self.builddir)
2995 self.assertEqual(obj.optstore.get_value_for('warning_level'), '2')
2996 self.setconf('--warnlevel=3')
2997 obj = mesonbuild.coredata.load(self.builddir)
2998 self.assertEqual(obj.optstore.get_value_for('warning_level'), '3')
2999 self.setconf('--warnlevel=everything')
3000 obj = mesonbuild.coredata.load(self.builddir)
3001 self.assertEqual(obj.optstore.get_value_for('warning_level'), 'everything')
3002 self.wipe()
3003
3004 # But when using -D syntax, it should be 'warning_level'
3005 self.init(testdir, extra_args=['-Dwarning_level=2', '--fatal-meson-warnings'])
3006 obj = mesonbuild.coredata.load(self.builddir)
3007 self.assertEqual(obj.optstore.get_value_for('warning_level'), '2')
3008 self.setconf('-Dwarning_level=3')
3009 obj = mesonbuild.coredata.load(self.builddir)
3010 self.assertEqual(obj.optstore.get_value_for('warning_level'), '3')
3011 self.setconf('-Dwarning_level=everything')
3012 obj = mesonbuild.coredata.load(self.builddir)
3013 self.assertEqual(obj.optstore.get_value_for('warning_level'), 'everything')
3014 self.wipe()
3015
3016 # Mixing --option and -Doption is forbidden
3017 with self.assertRaises((subprocess.CalledProcessError, RuntimeError)) as cm:
3018 self.init(testdir, extra_args=['--warnlevel=1', '-Dwarning_level=3'])
3019 if isinstance(cm.exception, subprocess.CalledProcessError):
3020 self.assertNotEqual(0, cm.exception.returncode)
3021 self.assertIn('as both', cm.exception.output)
3022 else:
3023 self.assertIn('as both', str(cm.exception))
3024 self.init(testdir)
3025 with self.assertRaises((subprocess.CalledProcessError, RuntimeError)) as cm:
3026 self.setconf(['--warnlevel=1', '-Dwarning_level=3'])
3027 if isinstance(cm.exception, subprocess.CalledProcessError):
3028 self.assertNotEqual(0, cm.exception.returncode)
3029 self.assertIn('as both', cm.exception.output)
3030 else:
3031 self.assertIn('as both', str(cm.exception))
3032 self.wipe()
3033
3034 # --default-library should override default value from project()
3035 self.init(testdir, extra_args=['--default-library=both', '--fatal-meson-warnings'])
3036 obj = mesonbuild.coredata.load(self.builddir)
3037 self.assertEqual(obj.optstore.get_value_for('default_library'), 'both')
3038 self.setconf('--default-library=shared')
3039 obj = mesonbuild.coredata.load(self.builddir)
3040 self.assertEqual(obj.optstore.get_value_for('default_library'), 'shared')
3041 if self.backend is Backend.ninja:
3042 # reconfigure target works only with ninja backend
3043 self.build('reconfigure')
3044 obj = mesonbuild.coredata.load(self.builddir)
3045 self.assertEqual(obj.optstore.get_value_for('default_library'), 'shared')
3046 self.wipe()
3047
3048 # Should fail on unknown options
3049 with self.assertRaises((subprocess.CalledProcessError, RuntimeError)) as cm:
3050 self.init(testdir, extra_args=['-Dbad=1', '-Dfoo=2', '-Dwrong_link_args=foo'])
3051 self.assertNotEqual(0, cm.exception.returncode)
3052 self.assertIn(msg, cm.exception.output)
3053 self.wipe()
3054
3055 # Should fail on malformed option
3056 msg = "Option 'foo' must have a value separated by equals sign."
3057 with self.assertRaises((subprocess.CalledProcessError, RuntimeError)) as cm:
3058 self.init(testdir, extra_args=['-Dfoo'])
3059 if isinstance(cm.exception, subprocess.CalledProcessError):
3060 self.assertNotEqual(0, cm.exception.returncode)
3061 self.assertIn(msg, cm.exception.output)
3062 else:
3063 self.assertIn(msg, str(cm.exception))
3064 self.init(testdir)
3065 with self.assertRaises((subprocess.CalledProcessError, RuntimeError)) as cm:
3066 self.setconf('-Dfoo')
3067 if isinstance(cm.exception, subprocess.CalledProcessError):
3068 self.assertNotEqual(0, cm.exception.returncode)
3069 self.assertIn(msg, cm.exception.output)
3070 else:
3071 self.assertIn(msg, str(cm.exception))
3072 self.wipe()
3073
3074 # It is not an error to set wrong option for unknown subprojects or
3075 # language because we don't have control on which one will be selected.
3076 self.init(testdir, extra_args=['-Dc_wrong=1', '-Dwrong:bad=1'])
3077 self.wipe()
3078
3079 # Test we can set subproject option
3080 self.init(testdir, extra_args=['-Dsubp:subp_opt=foo', '--fatal-meson-warnings'])
3081 obj = mesonbuild.coredata.load(self.builddir)
3082 self.assertEqual(obj.optstore.get_value_for(OptionKey('subp_opt', 'subp')), 'foo')
3083 self.wipe()
3084
3085 # c_args value should be parsed with split_args
3086 self.init(testdir, extra_args=['-Dc_args=-Dfoo -Dbar "-Dthird=one two"', '--fatal-meson-warnings'])
3087 obj = mesonbuild.coredata.load(self.builddir)
3088 self.assertEqual(obj.optstore.get_value_for(OptionKey('c_args')), ['-Dfoo', '-Dbar', '-Dthird=one two'])
3089
3090 self.setconf('-Dc_args="foo bar" one two')
3091 obj = mesonbuild.coredata.load(self.builddir)
3092 self.assertEqual(obj.optstore.get_value_for(OptionKey('c_args')), ['foo bar', 'one', 'two'])
3093 self.wipe()
3094
3095 self.init(testdir, extra_args=['-Dset_percent_opt=myoption%', '--fatal-meson-warnings'])
3096 obj = mesonbuild.coredata.load(self.builddir)
3097 self.assertEqual(obj.optstore.get_value_for(OptionKey('set_percent_opt', '')), 'myoption%')
3098 self.wipe()
3099
3100 # Setting a 2nd time the same option should override the first value
3101 try:
3102 self.init(testdir, extra_args=['--bindir=foo', '--bindir=bar',
3103 '-Dbuildtype=plain', '-Dbuildtype=release',
3104 '-Db_sanitize=address', '-Db_sanitize=thread',
3105 '-Dc_args=-Dfoo', '-Dc_args=-Dbar',
3106 '-Db_lundef=false', '--fatal-meson-warnings'])
3107 obj = mesonbuild.coredata.load(self.builddir)
3108 self.assertEqual(obj.optstore.get_value_for('bindir'), 'bar')
3109 self.assertEqual(obj.optstore.get_value_for('buildtype'), 'release')
3110 self.assertEqual(obj.optstore.get_value_for('b_sanitize'), ['thread'])
3111 self.assertEqual(obj.optstore.get_value_for(OptionKey('c_args')), ['-Dbar'])
3112 self.setconf(['--bindir=bar', '--bindir=foo',
3113 '-Dbuildtype=release', '-Dbuildtype=plain',
3114 '-Db_sanitize=thread', '-Db_sanitize=address',
3115 '-Dc_args=-Dbar', '-Dc_args=-Dfoo'])
3116 obj = mesonbuild.coredata.load(self.builddir)
3117 self.assertEqual(obj.optstore.get_value_for('bindir'), 'foo')
3118 self.assertEqual(obj.optstore.get_value_for('buildtype'), 'plain')
3119 self.assertEqual(obj.optstore.get_value_for('b_sanitize'), ['address'])
3120 self.assertEqual(obj.optstore.get_value_for(OptionKey('c_args')), ['-Dfoo'])
3121 self.wipe()
3122 except KeyError:
3123 # Ignore KeyError, it happens on CI for compilers that does not
3124 # support b_sanitize. We have to test with a base option because
3125 # they used to fail this test with Meson 0.46 an earlier versions.
3126 pass
3127
3128 def test_warning_level_0(self):
3129 testdir = os.path.join(self.common_test_dir, '207 warning level 0')
3130
3131 # Verify default values when passing no args
3132 self.init(testdir)
3133 obj = mesonbuild.coredata.load(self.builddir)
3134 self.assertEqual(obj.optstore.get_value_for('warning_level'), '0')
3135 self.wipe()
3136
3137 # verify we can override w/ --warnlevel
3138 self.init(testdir, extra_args=['--warnlevel=1'])
3139 obj = mesonbuild.coredata.load(self.builddir)
3140 self.assertEqual(obj.optstore.get_value_for('warning_level'), '1')
3141 self.setconf('--warnlevel=0')
3142 obj = mesonbuild.coredata.load(self.builddir)
3143 self.assertEqual(obj.optstore.get_value_for('warning_level'), '0')
3144 self.wipe()
3145
3146 # verify we can override w/ -Dwarning_level
3147 self.init(testdir, extra_args=['-Dwarning_level=1'])
3148 obj = mesonbuild.coredata.load(self.builddir)
3149 self.assertEqual(obj.optstore.get_value_for('warning_level'), '1')
3150 self.setconf('-Dwarning_level=0')
3151 obj = mesonbuild.coredata.load(self.builddir)
3152 self.assertEqual(obj.optstore.get_value_for('warning_level'), '0')
3153 self.wipe()
3154
3155 def test_feature_check_usage_subprojects(self):
3156 testdir = os.path.join(self.unit_test_dir, '40 featurenew subprojects')
3157 out = self.init(testdir)
3158 # Parent project warns correctly
3159 self.assertRegex(out, "WARNING: Project targets '>= 0.45'.*'0.47.0': dict")
3160 # Subprojects warn correctly
3161 self.assertRegex(out, r"foo\| .*WARNING: Project targets '>= 0.40'.*'0.44.0': disabler")
3162 self.assertRegex(out, r"baz\| .*WARNING: Project does not target a minimum version.*'0.44.0': disabler")
3163 # Subproject has a new-enough meson_version, no warning
3164 self.assertNotRegex(out, "WARNING: Project targets.*Python")
3165 # Ensure a summary is printed in the subproject and the outer project
3166 self.assertRegex(out, r"\| WARNING: Project specifies a minimum meson_version '>= 0.40'")
3167 self.assertRegex(out, r"\| \* 0.44.0: {'disabler'}")
3168 self.assertRegex(out, "WARNING: Project specifies a minimum meson_version '>= 0.45'")
3169 self.assertRegex(out, " * 0.47.0: {'dict'}")
3170
3171 def test_configure_file_warnings(self):
3172 testdir = os.path.join(self.common_test_dir, "14 configure file")
3173 out = self.init(testdir)
3174 self.assertRegex(out, "WARNING:.*'empty'.*config.h.in.*not present.*")
3175 self.assertRegex(out, "WARNING:.*'FOO_BAR'.*nosubst-nocopy2.txt.in.*not present.*")
3176 self.assertRegex(out, "WARNING:.*'empty'.*config.h.in.*not present.*")
3177 self.assertRegex(out, "WARNING:.*empty configuration_data.*test.py.in")
3178 # Warnings for configuration files that are overwritten.
3179 self.assertRegex(out, "WARNING:.*\"double_output.txt\".*overwrites")
3180 self.assertRegex(out, "WARNING:.*\"subdir.double_output2.txt\".*overwrites")
3181 self.assertNotRegex(out, "WARNING:.*no_write_conflict.txt.*overwrites")
3182 self.assertNotRegex(out, "WARNING:.*@BASENAME@.*overwrites")
3183 self.assertRegex(out, "WARNING:.*\"sameafterbasename\".*overwrites")
3184 # No warnings about empty configuration data objects passed to files with substitutions
3185 self.assertNotRegex(out, "WARNING:.*empty configuration_data.*nosubst-nocopy1.txt.in")
3186 self.assertNotRegex(out, "WARNING:.*empty configuration_data.*nosubst-nocopy2.txt.in")
3187 with open(os.path.join(self.builddir, 'nosubst-nocopy1.txt'), 'rb') as f:
3188 self.assertEqual(f.read().strip(), b'/* #undef FOO_BAR */')
3189 with open(os.path.join(self.builddir, 'nosubst-nocopy2.txt'), 'rb') as f:
3190 self.assertEqual(f.read().strip(), b'')
3191
3192 def test_dirs(self):
3193 with tempfile.TemporaryDirectory() as containing:
3194 with tempfile.TemporaryDirectory(dir=containing) as srcdir:
3195 mfile = os.path.join(srcdir, 'meson.build')
3196 of = open(mfile, 'w', encoding='utf-8')
3197 of.write("project('foobar', 'c')\n")
3198 of.close()
3199 pc = subprocess.run(self.setup_command,
3200 cwd=srcdir,
3201 stdout=subprocess.PIPE,
3202 stderr=subprocess.DEVNULL)
3203 self.assertIn(b'Must specify at least one directory name', pc.stdout)
3204 with tempfile.TemporaryDirectory(dir=srcdir) as builddir:
3205 subprocess.run(self.setup_command,
3206 check=True,
3207 cwd=builddir,
3208 stdout=subprocess.DEVNULL,
3209 stderr=subprocess.DEVNULL)
3210
3211 def get_opts_as_dict(self):
3212 result = {}
3213 for i in self.introspect('--buildoptions'):
3214 result[i['name']] = i['value']
3215 return result
3216
3217 def test_buildtype_setting(self):
3218 testdir = os.path.join(self.common_test_dir, '1 trivial')
3219 self.init(testdir)
3220 opts = self.get_opts_as_dict()
3221 self.assertEqual(opts['buildtype'], 'debug')
3222 self.assertEqual(opts['debug'], True)
3223 self.setconf('-Ddebug=false')
3224 opts = self.get_opts_as_dict()
3225 self.assertEqual(opts['debug'], False)
3226 self.assertEqual(opts['buildtype'], 'debug')
3227 self.assertEqual(opts['optimization'], '0')
3228 self.setconf('-Doptimization=g')
3229 opts = self.get_opts_as_dict()
3230 self.assertEqual(opts['debug'], False)
3231 self.assertEqual(opts['buildtype'], 'debug')
3232 self.assertEqual(opts['optimization'], 'g')
3233
3234 @skipIfNoPkgconfig
3235 @skipIf(is_windows(), 'Help needed with fixing this test on windows')
3236 def test_native_dep_pkgconfig(self):
3237 testdir = os.path.join(self.unit_test_dir,
3238 '45 native dep pkgconfig var')
3239 with tempfile.NamedTemporaryFile(mode='w', delete=False, encoding='utf-8') as crossfile:
3240 crossfile.write(textwrap.dedent(
3241 '''[binaries]
3242 pkg-config = '{}'
3243
3244 [properties]
3245
3246 [host_machine]
3247 system = 'linux'
3248 cpu_family = 'arm'
3249 cpu = 'armv7'
3250 endian = 'little'
3251 '''.format(os.path.join(testdir, 'cross_pkgconfig.py'))))
3252 crossfile.flush()
3253 self.meson_cross_files = [crossfile.name]
3254
3255 env = {'PKG_CONFIG_LIBDIR': os.path.join(testdir,
3256 'native_pkgconfig')}
3257 self.init(testdir, extra_args=['-Dstart_native=false'], override_envvars=env)
3258 self.wipe()
3259 self.init(testdir, extra_args=['-Dstart_native=true'], override_envvars=env)
3260
3261 @skipIfNoPkgconfig
3262 @skipIf(is_windows(), 'Help needed with fixing this test on windows')
3263 def test_pkg_config_libdir(self):
3264 testdir = os.path.join(self.unit_test_dir,
3265 '45 native dep pkgconfig var')
3266 with tempfile.NamedTemporaryFile(mode='w', delete=False, encoding='utf-8') as crossfile:
3267 crossfile.write(textwrap.dedent(
3268 '''[binaries]
3269 pkg-config = 'pkg-config'
3270
3271 [properties]
3272 pkg_config_libdir = ['{}']
3273
3274 [host_machine]
3275 system = 'linux'
3276 cpu_family = 'arm'
3277 cpu = 'armv7'
3278 endian = 'little'
3279 '''.format(os.path.join(testdir, 'cross_pkgconfig'))))
3280 crossfile.flush()
3281 self.meson_cross_files = [crossfile.name]
3282
3283 env = {'PKG_CONFIG_LIBDIR': os.path.join(testdir,
3284 'native_pkgconfig')}
3285 self.init(testdir, extra_args=['-Dstart_native=false'], override_envvars=env)
3286 self.wipe()
3287 self.init(testdir, extra_args=['-Dstart_native=true'], override_envvars=env)
3288
3289 @skipIf(is_osx(), 'Not implemented for Darwin yet')
3290 @skipIf(is_windows(), 'POSIX only')
3291 def test_python_build_config_extensions(self):
3292 testdir = os.path.join(self.unit_test_dir,
3293 '126 python extension')
3294
3295 VERSION_INFO_KEYS = ('major', 'minor', 'micro', 'releaselevel', 'serial')
3296 EXTENSION_SUFFIX = '.extension-suffix.so'
3297 STABLE_ABI_SUFFIX = '.stable-abi-suffix.so'
3298 # macOS framework builds put libpython in PYTHONFRAMEWORKPREFIX.
3299 LIBDIR = (sysconfig.get_config_var('PYTHONFRAMEWORKPREFIX') or
3300 sysconfig.get_config_var('LIBDIR'))
3301
3302 python_build_config = {
3303 'schema_version': '1.0',
3304 'base_interpreter': sys.executable,
3305 'base_prefix': sys.base_prefix,
3306 'platform': sysconfig.get_platform(),
3307 'language': {
3308 'version': sysconfig.get_python_version(),
3309 'version_info': {key: getattr(sys.version_info, key) for key in VERSION_INFO_KEYS}
3310 },
3311 'implementation': {
3312 attr: (
3313 getattr(sys.implementation, attr)
3314 if attr != 'version' else
3315 {key: getattr(sys.implementation.version, key) for key in VERSION_INFO_KEYS}
3316 )
3317 for attr in dir(sys.implementation)
3318 if not attr.startswith('__')
3319 },
3320 'abi': {
3321 'flags': list(sys.abiflags),
3322 'extension_suffix': EXTENSION_SUFFIX,
3323 'stable_abi_suffix': STABLE_ABI_SUFFIX,
3324 },
3325 'suffixes': {
3326 'source': ['.py'],
3327 'bytecode': ['.pyc'],
3328 'optimized_bytecode': ['.pyc'],
3329 'debug_bytecode': ['.pyc'],
3330 'extensions': [EXTENSION_SUFFIX, STABLE_ABI_SUFFIX, '.so'],
3331 },
3332 'libpython': {
3333 'dynamic': os.path.join(LIBDIR, sysconfig.get_config_var('LDLIBRARY')),
3334 'static': os.path.join(LIBDIR, sysconfig.get_config_var('LIBRARY')),
3335 # set it to False on PyPy, since dylib is optional, but also
3336 # the value is currently wrong:
3337 # https://github.com/pypy/pypy/issues/5249
3338 'link_extensions': '__pypy__' not in sys.builtin_module_names,
3339 },
3340 'c_api': {
3341 'headers': sysconfig.get_config_var('INCLUDEPY'),
3342 }
3343 }
3344
3345 py3library = sysconfig.get_config_var('PY3LIBRARY')
3346 if py3library is not None:
3347 python_build_config['libpython']['dynamic_stableabi'] = os.path.join(LIBDIR, py3library)
3348
3349 build_stable_abi = sysconfig.get_config_var('Py_GIL_DISABLED') != 1 or sys.version_info >= (3, 15)
3350 intro_installed_file = os.path.join(self.builddir, 'meson-info', 'intro-installed.json')
3351 expected_files = [
3352 os.path.join(self.builddir, 'foo' + EXTENSION_SUFFIX),
3353 ]
3354 if build_stable_abi:
3355 expected_files += [
3356 os.path.join(self.builddir, 'foo_stable' + STABLE_ABI_SUFFIX),
3357 ]
3358 if is_cygwin():
3359 expected_files += [
3360 os.path.join(self.builddir, 'foo' + EXTENSION_SUFFIX.replace('.so', '.dll.a')),
3361 ]
3362 if build_stable_abi:
3363 expected_files += [
3364 os.path.join(self.builddir, 'foo_stable' + STABLE_ABI_SUFFIX.replace('.so', '.dll.a')),
3365 ]
3366
3367 for with_pkgconfig in (False, True):
3368 with self.subTest(with_pkgconfig=with_pkgconfig):
3369 if with_pkgconfig:
3370 libpc = sysconfig.get_config_var('LIBPC')
3371 if libpc is None:
3372 raise SkipTest('pkg-config subtest skipped because of no LIBPC')
3373 python_build_config['c_api']['pkgconfig_path'] = libpc
3374 # Old Ubuntu versions have incorrect LIBDIR, skip testing non-pkgconfig variant there.
3375 elif not os.path.exists(python_build_config['libpython']['dynamic']):
3376 raise SkipTest('non-pkgconfig subtest skipped because of wrong LIBDIR')
3377
3378 with tempfile.NamedTemporaryFile(mode='w', delete=False, encoding='utf-8') as python_build_config_file:
3379 json.dump(python_build_config, fp=python_build_config_file)
3380 for build_config_via_cross in (False, True):
3381 for sys_root in (None, sys.base_prefix):
3382 with self.subTest(build_config_via_cross=build_config_via_cross, sys_root=sys_root):
3383 # fd.o pkg-config does not handle sys_root correctly
3384 if sys_root is not None and with_pkgconfig and shutil.which('pkgconf') is None:
3385 raise SkipTest('sys_root subtest skipped because of fd.o pkg-config')
3386
3387 with tempfile.NamedTemporaryFile(mode='w', delete=False, encoding='utf-8') as cross_file:
3388 cross_file.write(
3389 textwrap.dedent(f'''
3390 [binaries]
3391 pkg-config = 'pkg-config'
3392 ''')
3393 )
3394 if build_config_via_cross:
3395 cross_file.write(
3396 textwrap.dedent(f'''
3397 [built-in options]
3398 python.build_config = '{python_build_config_file.name}'
3399 ''')
3400 )
3401 if sys_root is not None:
3402 cross_file.write(
3403 textwrap.dedent(f'''
3404 [properties]
3405 sys_root = '{sys_root}'
3406 ''')
3407 )
3408 cross_file.flush()
3409
3410 extra_args = ['--cross-file', cross_file.name]
3411 if not build_config_via_cross:
3412 extra_args += ['--python.build-config', python_build_config_file.name]
3413
3414 self.init(testdir, extra_args=extra_args)
3415 self.build()
3416 with open(intro_installed_file) as f:
3417 intro_installed = json.load(f)
3418 self.assertEqual(sorted(expected_files), sorted(intro_installed))
3419 self.wipe()
3420
3421 def __reconfigure(self):
3422 # Set an older version to force a reconfigure from scratch
3423 filename = os.path.join(self.privatedir, 'coredata.dat')
3424 with open(filename, 'rb') as f:
3425 obj = pickle.load(f)
3426 obj.version = '0.47.0'
3427 with open(filename, 'wb') as f:
3428 pickle.dump(obj, f)
3429
3430 def test_reconfigure(self):
3431 testdir = os.path.join(self.unit_test_dir, '47 reconfigure')
3432 self.init(testdir, extra_args=['-Dopt1=val1', '-Dsub1:werror=true'])
3433 self.setconf('-Dopt2=val2')
3434
3435 self.__reconfigure()
3436
3437 out = self.init(testdir, extra_args=['--reconfigure', '-Dopt3=val3'])
3438 self.assertRegex(out, 'Regenerating configuration from scratch')
3439 self.assertRegex(out, 'opt1 val1')
3440 self.assertRegex(out, 'opt2 val2')
3441 self.assertRegex(out, 'opt3 val3')
3442 self.assertRegex(out, 'opt4 default4')
3443 # Per subproject options are stored in augments,
3444 # not in the options themselves so these status
3445 # messages are no longer printed.
3446 #self.assertRegex(out, 'sub1:werror true')
3447 self.build()
3448 self.run_tests()
3449
3450 # Create a file in builddir and verify wipe command removes it
3451 filename = os.path.join(self.builddir, 'something')
3452 open(filename, 'w', encoding='utf-8').close()
3453 self.assertTrue(os.path.exists(filename))
3454 out = self.init(testdir, extra_args=['--wipe', '-Dopt4=val4'])
3455 self.assertFalse(os.path.exists(filename))
3456 self.assertRegex(out, 'opt1 val1')
3457 self.assertRegex(out, 'opt2 val2')
3458 self.assertRegex(out, 'opt3 val3')
3459 self.assertRegex(out, 'opt4 val4')
3460 #self.assertRegex(out, 'sub1:werror true')
3461 self.assertTrue(Path(self.builddir, '.gitignore').exists())
3462 self.build()
3463 self.run_tests()
3464
3465 def test_wipe_from_builddir(self):
3466 testdir = os.path.join(self.common_test_dir, '157 custom target subdir depend files')
3467 self.init(testdir)
3468 self.__reconfigure()
3469 self.init(testdir, extra_args=['--wipe'], workdir=self.builddir)
3470
3471 def test_target_construct_id_from_path(self):
3472 # This id is stable but not guessable.
3473 # The test is supposed to prevent unintentional
3474 # changes of target ID generation.
3475 target_id = Target.construct_id_from_path('some/obscure/subdir',
3476 'target-id', '@suffix')
3477 self.assertEqual('5e002d3@@target-id@suffix', target_id)
3478 target_id = Target.construct_id_from_path('subproject/foo/subdir/bar',
3479 'target2-id', '@other')
3480 self.assertEqual('81d46d1@@target2-id@other', target_id)
3481
3482 def test_introspect_projectinfo_without_configured_build(self):
3483 testfile = os.path.join(self.common_test_dir, '33 run program', 'meson.build')
3484 res = self.introspect_directory(testfile, '--projectinfo')
3485 self.assertEqual(set(res['buildsystem_files']), {'meson.build'})
3486 self.assertEqual(res['version'], 'undefined')
3487 self.assertEqual(res['descriptive_name'], 'run command')
3488 self.assertEqual(res['subprojects'], [])
3489
3490 testfile = os.path.join(self.common_test_dir, '40 options', 'meson.build')
3491 res = self.introspect_directory(testfile, '--projectinfo')
3492 self.assertEqual(set(res['buildsystem_files']), {'meson_options.txt', 'meson.build'})
3493 self.assertEqual(res['version'], 'undefined')
3494 self.assertEqual(res['descriptive_name'], 'options')
3495 self.assertEqual(res['subprojects'], [])
3496
3497 testfile = os.path.join(self.common_test_dir, '43 subproject options', 'meson.build')
3498 res = self.introspect_directory(testfile, '--projectinfo')
3499 self.assertEqual(set(res['buildsystem_files']), {'meson_options.txt', 'meson.build'})
3500 self.assertEqual(res['version'], 'undefined')
3501 self.assertEqual(res['descriptive_name'], 'suboptions')
3502 self.assertEqual(len(res['subprojects']), 1)
3503 subproject_files = {f.replace('\\', '/') for f in res['subprojects'][0]['buildsystem_files']}
3504 self.assertEqual(subproject_files, {'subprojects/subproject/meson_options.txt', 'subprojects/subproject/meson.build'})
3505 self.assertEqual(res['subprojects'][0]['name'], 'subproject')
3506 self.assertEqual(res['subprojects'][0]['version'], 'undefined')
3507 self.assertEqual(res['subprojects'][0]['descriptive_name'], 'subproject')
3508
3509 def test_introspect_projectinfo_subprojects(self):
3510 testdir = os.path.join(self.common_test_dir, '98 subproject subdir')
3511 self.init(testdir)
3512 res = self.introspect('--projectinfo')
3513 expected = {
3514 'descriptive_name': 'proj',
3515 'version': 'undefined',
3516 'license': ['unknown'],
3517 'license_files': [],
3518 'subproject_dir': 'subprojects',
3519 'subprojects': [
3520 {
3521 'descriptive_name': 'sub',
3522 'name': 'sub',
3523 'version': '1.0'
3524 },
3525 {
3526 'descriptive_name': 'sub_implicit',
3527 'name': 'sub_implicit',
3528 'version': '1.0',
3529 },
3530 {
3531 'descriptive_name': 'sub-novar',
3532 'name': 'sub_novar',
3533 'version': '1.0',
3534 },
3535 {
3536 'descriptive_name': 'sub_static',
3537 'name': 'sub_static',
3538 'version': 'undefined'
3539 },
3540 {
3541 'descriptive_name': 'subsub',
3542 'name': 'subsub',
3543 'version': 'undefined'
3544 },
3545 {
3546 'descriptive_name': 'subsubsub',
3547 'name': 'subsubsub',
3548 'version': 'undefined'
3549 },
3550 ]
3551 }
3552 res['subprojects'] = sorted(res['subprojects'], key=lambda i: i['name'])
3553 self.assertDictEqual(expected, res)
3554
3555 def test_introspection_target_subproject(self):
3556 testdir = os.path.join(self.common_test_dir, '42 subproject')
3557 self.init(testdir)
3558 res = self.introspect('--targets')
3559
3560 expected = {
3561 'sublib': 'sublib',
3562 'simpletest': 'sublib',
3563 'user': None
3564 }
3565
3566 for entry in res:
3567 name = entry['name']
3568 self.assertEqual(entry['subproject'], expected[name])
3569
3570 def test_introspection_target_native_subproject(self):
3571 # When the same subproject is built for both the build machine
3572 # (native : true) and the host machine (native : false) in a cross
3573 # build, it is configured twice. The two copies of its 'lib' target
3574 # share the same name and subproject but must have different ids.
3575 crossdir = os.path.join(self.unit_test_dir, '69 cross')
3576 # Reuse the cross test project to generate a native and a cross file
3577 # describing this machine, so the configuration below is treated as a
3578 # cross build (see test_identity_cross).
3579 self.init(crossdir, extra_args=['-Dgenerate=true'])
3580 self.meson_native_files = [os.path.join(self.builddir, "nativefile")]
3581 self.meson_cross_files = [os.path.join(self.builddir, "crossfile")]
3582
3583 self.new_builddir()
3584 testdir = os.path.join(self.unit_test_dir, '136 native subproject introspect')
3585 self.init(testdir)
3586 res = self.introspect('--targets')
3587
3588 ids = [entry['id'] for entry in res
3589 if entry['name'] == 'lib' and entry['subproject'] == 'recursive-both']
3590 self.assertEqual(len(ids), 2, 'subproject should be built for both machines')
3591 self.assertEqual(len(set(ids)), 2, 'native and non-native targets must have different ids')
3592
3593 def test_introspect_projectinfo_subproject_dir(self):
3594 testdir = os.path.join(self.common_test_dir, '75 custom subproject dir')
3595 self.init(testdir)
3596 res = self.introspect('--projectinfo')
3597
3598 self.assertEqual(res['subproject_dir'], 'custom_subproject_dir')
3599
3600 def test_introspect_projectinfo_subproject_dir_from_source(self):
3601 testfile = os.path.join(self.common_test_dir, '75 custom subproject dir', 'meson.build')
3602 res = self.introspect_directory(testfile, '--projectinfo')
3603
3604 self.assertEqual(res['subproject_dir'], 'custom_subproject_dir')
3605
3606 @skipIfNoExecutable('clang-format')
3607 def test_clang_format(self):
3608 if self.backend is not Backend.ninja:
3609 raise SkipTest(f'Clang-format is for now only supported on Ninja, not {self.backend.name}')
3610 testdir = os.path.join(self.unit_test_dir, '53 clang-format')
3611
3612 # Ensure that test project is in git even when running meson from tarball.
3613 srcdir = os.path.join(self.builddir, 'src')
3614 shutil.copytree(testdir, srcdir)
3615 git_init(srcdir)
3616 testdir = srcdir
3617 self.new_builddir()
3618
3619 testfile = os.path.join(testdir, 'prog.c')
3620 badfile = os.path.join(testdir, 'prog_orig_c')
3621 goodfile = os.path.join(testdir, 'prog_expected_c')
3622 testheader = os.path.join(testdir, 'header.h')
3623 badheader = os.path.join(testdir, 'header_orig_h')
3624 goodheader = os.path.join(testdir, 'header_expected_h')
3625 includefile = os.path.join(testdir, '.clang-format-include')
3626 try:
3627 shutil.copyfile(badfile, testfile)
3628 shutil.copyfile(badheader, testheader)
3629 self.init(testdir)
3630 self.assertNotEqual(Path(testfile).read_text(encoding='utf-8'),
3631 Path(goodfile).read_text(encoding='utf-8'))
3632 self.assertNotEqual(Path(testheader).read_text(encoding='utf-8'),
3633 Path(goodheader).read_text(encoding='utf-8'))
3634
3635 # test files are not in git so this should do nothing
3636 self.run_target('clang-format')
3637 self.assertNotEqual(Path(testfile).read_text(encoding='utf-8'),
3638 Path(goodfile).read_text(encoding='utf-8'))
3639 self.assertNotEqual(Path(testheader).read_text(encoding='utf-8'),
3640 Path(goodheader).read_text(encoding='utf-8'))
3641
3642 # Add an include file to reformat everything
3643 with open(includefile, 'w', encoding='utf-8') as f:
3644 f.write('*')
3645 self.run_target('clang-format')
3646 self.assertEqual(Path(testheader).read_text(encoding='utf-8'),
3647 Path(goodheader).read_text(encoding='utf-8'))
3648 finally:
3649 if os.path.exists(testfile):
3650 os.unlink(testfile)
3651 if os.path.exists(testheader):
3652 os.unlink(testheader)
3653 if os.path.exists(includefile):
3654 os.unlink(includefile)
3655
3656 @skipIfNoExecutable('clang-tidy')
3657 @skipIfNoExecutable('c++')
3658 @skipIf(is_osx(), 'Apple ships a broken clang-tidy that chokes on -pipe.')
3659 def test_clang_tidy(self):
3660 if self.backend is not Backend.ninja:
3661 raise SkipTest(f'Clang-tidy is for now only supported on Ninja, not {self.backend.name}')
3662 testdir = os.path.join(self.unit_test_dir, '68 clang-tidy')
3663 dummydir = os.path.join(testdir, 'dummydir.h')
3664 self.init(testdir, override_envvars={'CXX': 'c++'})
3665 out = self.run_target('clang-tidy')
3666 self.assertIn('cttest.cpp:4:20', out)
3667 self.assertNotIn(dummydir, out)
3668
3669 @skipIfNoExecutable('clang-tidy')
3670 @skipIfNoExecutable('c++')
3671 @skipIf(is_osx(), 'Apple ships a broken clang-tidy that chokes on -pipe.')
3672 def test_clang_tidy_fix(self):
3673 if self.backend is not Backend.ninja:
3674 raise SkipTest(f'Clang-tidy is for now only supported on Ninja, not {self.backend.name}')
3675 testdir = os.path.join(self.unit_test_dir, '68 clang-tidy')
3676
3677 # Ensure that test project is in git even when running meson from tarball.
3678 srcdir = os.path.join(self.builddir, 'src')
3679 shutil.copytree(testdir, srcdir)
3680 git_init(srcdir)
3681 testdir = srcdir
3682 self.new_builddir()
3683
3684 dummydir = os.path.join(testdir, 'dummydir.h')
3685 testfile = os.path.join(testdir, 'cttest.cpp')
3686 fixedfile = os.path.join(testdir, 'cttest_fixed.cpp')
3687 self.init(testdir, override_envvars={'CXX': 'c++'})
3688 # Make sure test files are different
3689 self.assertNotEqual(Path(testfile).read_text(encoding='utf-8'),
3690 Path(fixedfile).read_text(encoding='utf-8'))
3691 out = self.run_target('clang-tidy-fix')
3692 self.assertIn('cttest.cpp:4:20', out)
3693 self.assertNotIn(dummydir, out)
3694 # Make sure the test file is fixed
3695 self.assertEqual(Path(testfile).read_text(encoding='utf-8'),
3696 Path(fixedfile).read_text(encoding='utf-8'))
3697
3698 def test_identity_cross(self):
3699 testdir = os.path.join(self.unit_test_dir, '69 cross')
3700 # Do a build to generate a cross file where the host is this target
3701 # build.c_args is ignored here.
3702 self.init(testdir, extra_args=['-Dgenerate=true', '-Dc_args=-funroll-loops',
3703 '-Dbuild.c_args=-pedantic'])
3704 self.meson_native_files = [os.path.join(self.builddir, "nativefile")]
3705 self.assertTrue(os.path.exists(self.meson_native_files[0]))
3706 self.meson_cross_files = [os.path.join(self.builddir, "crossfile")]
3707 self.assertTrue(os.path.exists(self.meson_cross_files[0]))
3708 # Now verify that this is detected as cross and build options are
3709 # processed correctly
3710 self.new_builddir()
3711 self.init(testdir)
3712
3713 # Disabled for now as the introspection format needs to change to add augments.
3714 def DISABLED_test_introspect_buildoptions_without_configured_build(self):
3715 testdir = os.path.join(self.unit_test_dir, '58 introspect buildoptions')
3716 testfile = os.path.join(testdir, 'meson.build')
3717 res_nb = self.introspect_directory(testfile, ['--buildoptions'] + self.meson_args)
3718 self.init(testdir, default_args=False)
3719 res_wb = self.introspect('--buildoptions')
3720 self.maxDiff = None
3721 # XXX: These now generate in a different order, is that okay?
3722 self.assertListEqual(sorted(res_nb, key=lambda x: x['name']), sorted(res_wb, key=lambda x: x['name']))
3723
3724 def test_meson_configure_from_source_does_not_crash(self):
3725 testdir = os.path.join(self.unit_test_dir, '58 introspect buildoptions')
3726 self._run(self.mconf_command + [testdir])
3727
3728 @skip_if_not_language('rust')
3729 def test_meson_configure_srcdir(self):
3730 testdir = os.path.join(self.rust_test_dir, '20 rust and cpp')
3731 self._run(self.mconf_command + [testdir])
3732
3733 def test_introspect_buildoptions_cross_only(self):
3734 testdir = os.path.join(self.unit_test_dir, '82 cross only introspect')
3735 testfile = os.path.join(testdir, 'meson.build')
3736 res = self.introspect_directory(testfile, ['--buildoptions'] + self.meson_args)
3737 optnames = [o['name'] for o in res]
3738 self.assertIn('c_args', optnames)
3739 self.assertNotIn('build.c_args', optnames)
3740
3741 def test_introspect_json_flat(self):
3742 testdir = os.path.join(self.unit_test_dir, '56 introspection')
3743 self.init(testdir, extra_args=['-Dlayout=flat'])
3744 infodir = os.path.join(self.builddir, 'meson-info')
3745 self.assertPathExists(infodir)
3746
3747 with open(os.path.join(infodir, 'intro-targets.json'), encoding='utf-8') as fp:
3748 targets = json.load(fp)
3749
3750 for i in targets:
3751 for out in i['filename']:
3752 assert os.path.relpath(out, self.builddir).startswith('meson-out')
3753
3754 def test_introspect_json_dump(self):
3755 testdir = os.path.join(self.unit_test_dir, '56 introspection')
3756 self.init(testdir)
3757 infodir = os.path.join(self.builddir, 'meson-info')
3758 self.assertPathExists(infodir)
3759
3760 def assertKeyTypes(key_type_list, obj, strict: bool = True):
3761 for i in key_type_list:
3762 if isinstance(i[1], (list, tuple)) and None in i[1]:
3763 i = (i[0], tuple(x for x in i[1] if x is not None))
3764 if i[0] not in obj or obj[i[0]] is None:
3765 continue
3766 self.assertIn(i[0], obj)
3767 self.assertIsInstance(obj[i[0]], i[1])
3768 if strict:
3769 for k in obj.keys():
3770 found = False
3771 for i in key_type_list:
3772 if k == i[0]:
3773 found = True
3774 break
3775 self.assertTrue(found, f'Key "{k}" not in expected list')
3776
3777 root_keylist = [
3778 ('benchmarks', list),
3779 ('buildoptions', list),
3780 ('buildsystem_files', list),
3781 ('compilers', dict),
3782 ('dependencies', list),
3783 ('install_plan', dict),
3784 ('installed', dict),
3785 ('machines', dict),
3786 ('projectinfo', dict),
3787 ('targets', list),
3788 ('tests', list),
3789 ]
3790
3791 test_keylist = [
3792 ('cmd', list),
3793 ('env', dict),
3794 ('name', str),
3795 ('timeout', int),
3796 ('suite', list),
3797 ('is_parallel', bool),
3798 ('protocol', str),
3799 ('depends', list),
3800 ('workdir', (str, None)),
3801 ('priority', int),
3802 ('extra_paths', list),
3803 ]
3804
3805 buildoptions_keylist = [
3806 ('name', str),
3807 ('section', str),
3808 ('type', str),
3809 ('description', str),
3810 ('machine', str),
3811 ('choices', (list, None)),
3812 ('value', (str, int, bool, list)),
3813 ]
3814
3815 buildoptions_typelist = [
3816 ('combo', str, [('choices', list)]),
3817 ('string', str, []),
3818 ('boolean', bool, []),
3819 ('integer', int, []),
3820 ('array', list, []),
3821 ]
3822
3823 buildoptions_sections = ['core', 'backend', 'base', 'compiler', 'directory', 'user', 'test']
3824 buildoptions_machines = ['any', 'build', 'host']
3825
3826 dependencies_typelist = [
3827 ('name', str),
3828 ('type', str),
3829 ('version', str),
3830 ('compile_args', list),
3831 ('link_args', list),
3832 ('include_directories', list),
3833 ('sources', list),
3834 ('extra_files', list),
3835 ('dependencies', list),
3836 ('depends', list),
3837 ('meson_variables', list),
3838 ]
3839
3840 targets_typelist = [
3841 ('name', str),
3842 ('id', str),
3843 ('type', str),
3844 ('defined_in', str),
3845 ('filename', list),
3846 ('build_by_default', bool),
3847 ('target_sources', list),
3848 ('extra_files', list),
3849 ('subproject', (str, None)),
3850 ('dependencies', list),
3851 ('depends', list),
3852 ('install_filename', (list, None)),
3853 ('installed', bool),
3854 ('vs_module_defs', (str, None)),
3855 ('win_subsystem', (str, None)),
3856 ]
3857
3858 targets_sources_unknown_lang_typelist = [
3859 ('language', str),
3860 ('compiler', list),
3861 ('parameters', list),
3862 ('sources', list),
3863 ('generated_sources', list),
3864 ('unity_sources', (list, None)),
3865 ]
3866
3867 targets_sources_typelist = targets_sources_unknown_lang_typelist + [
3868 ('machine', str),
3869 ]
3870
3871 target_sources_linker_typelist = [
3872 ('linker', list),
3873 ('parameters', list),
3874 ]
3875
3876 # First load all files
3877 res = {}
3878 for i in root_keylist:
3879 curr = os.path.join(infodir, 'intro-{}.json'.format(i[0]))
3880 self.assertPathExists(curr)
3881 with open(curr, encoding='utf-8') as fp:
3882 res[i[0]] = json.load(fp)
3883
3884 assertKeyTypes(root_keylist, res)
3885
3886 # Match target ids to input and output files for ease of reference
3887 src_to_id = {}
3888 out_to_id = {}
3889 name_to_out = {}
3890 for i in res['targets']:
3891 print(json.dump(i, sys.stdout))
3892 out_to_id.update({os.path.relpath(out, self.builddir): i['id']
3893 for out in i['filename']})
3894 name_to_out.update({i['name']: i['filename']})
3895 for group in i['target_sources']:
3896 src_to_id.update({os.path.relpath(src, testdir): i['id']
3897 for src in group.get('sources', [])})
3898
3899 with self.subTest('Check Tests and Benchmarks'):
3900 tests_to_find = ['test case 1', 'test case 2', 'benchmark 1']
3901 deps_to_find = {'test case 1': [src_to_id['t1.cpp']],
3902 'test case 2': [src_to_id['t2.cpp'], src_to_id['t3.cpp']],
3903 'benchmark 1': [out_to_id['file2'], out_to_id['file3'], out_to_id['file4'], src_to_id['t3.cpp']]}
3904 for i in res['benchmarks'] + res['tests']:
3905 assertKeyTypes(test_keylist, i)
3906 if i['name'] in tests_to_find:
3907 tests_to_find.remove(i['name'])
3908 self.assertEqual(sorted(i['depends']),
3909 sorted(deps_to_find[i['name']]))
3910 self.assertListEqual(tests_to_find, [])
3911
3912 with self.subTest('Check buildoptions'):
3913 buildopts_to_find = {'cpp_std': 'c++11'}
3914 for i in res['buildoptions']:
3915 assertKeyTypes(buildoptions_keylist, i)
3916 valid_type = False
3917 for j in buildoptions_typelist:
3918 if i['type'] == j[0]:
3919 self.assertIsInstance(i['value'], j[1])
3920 assertKeyTypes(j[2], i, strict=False)
3921 valid_type = True
3922 break
3923
3924 self.assertIn(i['section'], buildoptions_sections)
3925 self.assertIn(i['machine'], buildoptions_machines)
3926 self.assertTrue(valid_type)
3927 if i['name'] in buildopts_to_find:
3928 self.assertEqual(i['value'], buildopts_to_find[i['name']])
3929 buildopts_to_find.pop(i['name'], None)
3930 self.assertDictEqual(buildopts_to_find, {})
3931
3932 with self.subTest('Check buildsystem_files'):
3933 bs_files = ['meson.build', 'meson_options.txt', 'sharedlib/meson.build', 'staticlib/meson.build']
3934 bs_files = [os.path.join(testdir, x) for x in bs_files]
3935 self.assertPathListEqual(list(sorted(res['buildsystem_files'])), list(sorted(bs_files)))
3936
3937 with self.subTest('Check dependencies'):
3938 dependencies_to_find = ['threads']
3939 for i in res['dependencies']:
3940 assertKeyTypes(dependencies_typelist, i)
3941 if i['name'] in dependencies_to_find:
3942 dependencies_to_find.remove(i['name'])
3943 self.assertListEqual(dependencies_to_find, [])
3944
3945 with self.subTest('Check projectinfo'):
3946 self.assertDictEqual(res['projectinfo'], {
3947 'version': '1.2.3',
3948 'license': ['unknown'],
3949 'license_files': [],
3950 'descriptive_name': 'introspection',
3951 'subproject_dir': 'subprojects',
3952 'subprojects': []
3953 })
3954
3955 with self.subTest('Check targets'):
3956 targets_to_find = {
3957 'sharedTestLib': ('shared library', True, False, 'sharedlib/meson.build',
3958 [os.path.join(testdir, 'sharedlib', 'shared.cpp')]),
3959 'staticTestLib': ('static library', True, False, 'staticlib/meson.build',
3960 [os.path.join(testdir, 'staticlib', 'static.c')]),
3961 'custom target test 1': ('custom', False, False, 'meson.build',
3962 [os.path.join(testdir, 'cp.py')]),
3963 'custom target test 2': ('custom', False, False, 'meson.build',
3964 name_to_out['custom target test 1']),
3965 'test1': ('executable', True, True, 'meson.build',
3966 [os.path.join(testdir, 't1.cpp')]),
3967 'test2': ('executable', True, False, 'meson.build',
3968 [os.path.join(testdir, 't2.cpp')]),
3969 'test3': ('executable', True, False, 'meson.build',
3970 [os.path.join(testdir, 't3.cpp')]),
3971 'custom target test 3': ('custom', False, False, 'meson.build',
3972 name_to_out['test3']),
3973 }
3974 for i in res['targets']:
3975 assertKeyTypes(targets_typelist, i)
3976 if i['name'] in targets_to_find:
3977 tgt = targets_to_find[i['name']]
3978 self.assertEqual(i['type'], tgt[0])
3979 self.assertEqual(i['build_by_default'], tgt[1])
3980 self.assertEqual(i['installed'], tgt[2])
3981 self.assertPathEqual(i['defined_in'], os.path.join(testdir, tgt[3]))
3982 targets_to_find.pop(i['name'], None)
3983 for j in i['target_sources']:
3984 if 'compiler' in j:
3985 if j['language'] == 'unknown':
3986 assertKeyTypes(targets_sources_unknown_lang_typelist, j)
3987 else:
3988 assertKeyTypes(targets_sources_typelist, j)
3989 self.assertEqual(j['sources'], [os.path.normpath(f) for f in tgt[4]])
3990 else:
3991 assertKeyTypes(target_sources_linker_typelist, j)
3992 self.assertDictEqual(targets_to_find, {})
3993
3994 def test_introspect_file_dump_equals_all(self):
3995 testdir = os.path.join(self.unit_test_dir, '56 introspection')
3996 self.init(testdir)
3997 res_all = self.introspect('--all')
3998 res_file = {}
3999
4000 root_keylist = [
4001 'benchmarks',
4002 'buildoptions',
4003 'buildsystem_files',
4004 'compilers',
4005 'dependencies',
4006 'installed',
4007 'install_plan',
4008 'machines',
4009 'projectinfo',
4010 'targets',
4011 'tests',
4012 ]
4013
4014 infodir = os.path.join(self.builddir, 'meson-info')
4015 self.assertPathExists(infodir)
4016 for i in root_keylist:
4017 curr = os.path.join(infodir, f'intro-{i}.json')
4018 self.assertPathExists(curr)
4019 with open(curr, encoding='utf-8') as fp:
4020 res_file[i] = json.load(fp)
4021
4022 self.assertEqual(res_all, res_file)
4023
4024 def test_introspect_meson_info(self):
4025 testdir = os.path.join(self.unit_test_dir, '56 introspection')
4026 introfile = os.path.join(self.builddir, 'meson-info', 'meson-info.json')
4027 self.init(testdir)
4028 self.assertPathExists(introfile)
4029 with open(introfile, encoding='utf-8') as fp:
4030 res1 = json.load(fp)
4031
4032 for i in ['meson_version', 'directories', 'introspection', 'build_files_updated', 'error']:
4033 self.assertIn(i, res1)
4034
4035 self.assertEqual(res1['error'], False)
4036 self.assertEqual(res1['build_files_updated'], True)
4037
4038 # Disabled for now as the introspection file format needs to change to have augments.
4039 def DISABLE_test_introspect_config_update(self):
4040 testdir = os.path.join(self.unit_test_dir, '56 introspection')
4041 introfile = os.path.join(self.builddir, 'meson-info', 'intro-buildoptions.json')
4042 self.init(testdir)
4043 self.assertPathExists(introfile)
4044 with open(introfile, encoding='utf-8') as fp:
4045 res1 = json.load(fp)
4046
4047 for i in res1:
4048 if i['name'] == 'cpp_std':
4049 i['value'] = 'c++14'
4050 if i['name'] == 'build.cpp_std':
4051 i['value'] = 'c++14'
4052 if i['name'] == 'buildtype':
4053 i['value'] = 'release'
4054 if i['name'] == 'optimization':
4055 i['value'] = '3'
4056 if i['name'] == 'debug':
4057 i['value'] = False
4058
4059 self.setconf('-Dcpp_std=c++14')
4060 self.setconf('-Dbuildtype=release')
4061
4062 with open(introfile, encoding='utf-8') as fp:
4063 res2 = json.load(fp)
4064
4065 self.assertListEqual(res1, res2)
4066
4067 def test_introspect_targets_from_source(self):
4068 testdir = os.path.join(self.unit_test_dir, '56 introspection')
4069 testfile = os.path.join(testdir, 'meson.build')
4070 introfile = os.path.join(self.builddir, 'meson-info', 'intro-targets.json')
4071 self.init(testdir)
4072 self.assertPathExists(introfile)
4073 with open(introfile, encoding='utf-8') as fp:
4074 res_wb = json.load(fp)
4075
4076 res_nb = self.introspect_directory(testfile, ['--targets'] + self.meson_args)
4077
4078 # Account for differences in output
4079 res_wb = [i for i in res_wb if i['type'] != 'custom']
4080 for i in res_wb:
4081 if i['id'] == 'test1@exe':
4082 i['build_by_default'] = 'unknown'
4083 i['filename'] = [os.path.relpath(x, self.builddir) for x in i['filename']]
4084 for k in ('install_filename', 'dependencies', 'win_subsystem'):
4085 if k in i:
4086 del i[k]
4087
4088 sources = []
4089 for j in i['target_sources']:
4090 sources += j.get('sources', [])
4091 i['target_sources'] = [{
4092 'language': 'unknown',
4093 'machine': 'host',
4094 'compiler': [],
4095 'parameters': [],
4096 'sources': sources,
4097 'generated_sources': []
4098 }]
4099
4100 self.maxDiff = None
4101 self.assertListEqual(res_nb, res_wb)
4102
4103 @skipIfNoExecutable('gettext')
4104 @skipIfNoExecutable('xgettext')
4105 def test_introspect_custom_target_subdir_source_path(self):
4106 '''
4107 Test that introspection data for custom targets in subdirectories
4108 correctly resolves relative string source paths. Regression test for
4109 https://github.com/mesonbuild/meson/pull/14885
4110 '''
4111 testdir = os.path.join(self.framework_test_dir, '6 gettext')
4112 self.init(testdir)
4113 intro = self.introspect('--targets')
4114 # i18n.merge_file in data/data3/meson.build passes a raw string
4115 # 'test.desktop.in' as input, which should be resolved relative
4116 # to data/data3, not to the project root.
4117 for target in intro:
4118 if target['type'] == 'custom' and 'test4.desktop' in target['filename'][0]:
4119 sources = target['target_sources'][0]['sources']
4120 expected = os.path.join(testdir, 'data/data3/test.desktop.in')
4121 self.assertEqual(len(sources), 1)
4122 self.assertPathEqual(sources[0], expected)
4123 break
4124 else:
4125 self.fail('Could not find test4.desktop custom target')
4126
4127 def test_introspect_ast_source(self):
4128 testdir = os.path.join(self.unit_test_dir, '56 introspection')
4129 testfile = os.path.join(testdir, 'meson.build')
4130 res_nb = self.introspect_directory(testfile, ['--ast'] + self.meson_args)
4131
4132 node_counter = {}
4133
4134 def accept_node(json_node):
4135 self.assertIsInstance(json_node, dict)
4136 for i in ['lineno', 'colno', 'end_lineno', 'end_colno']:
4137 self.assertIn(i, json_node)
4138 self.assertIsInstance(json_node[i], int)
4139 self.assertIn('node', json_node)
4140 n = json_node['node']
4141 self.assertIsInstance(n, str)
4142 self.assertIn(n, nodes)
4143 if n not in node_counter:
4144 node_counter[n] = 0
4145 node_counter[n] = node_counter[n] + 1
4146 for nodeDesc in nodes[n]:
4147 key = nodeDesc[0]
4148 func = nodeDesc[1]
4149 self.assertIn(key, json_node)
4150 if func is None:
4151 tp = nodeDesc[2]
4152 self.assertIsInstance(json_node[key], tp)
4153 continue
4154 func(json_node[key])
4155
4156 def accept_node_list(node_list):
4157 self.assertIsInstance(node_list, list)
4158 for i in node_list:
4159 accept_node(i)
4160
4161 def accept_kwargs(kwargs):
4162 self.assertIsInstance(kwargs, list)
4163 for i in kwargs:
4164 self.assertIn('key', i)
4165 self.assertIn('val', i)
4166 accept_node(i['key'])
4167 accept_node(i['val'])
4168
4169 nodes = {
4170 'BooleanNode': [('value', None, bool)],
4171 'IdNode': [('value', None, str)],
4172 'NumberNode': [('value', None, int)],
4173 'StringNode': [('value', None, str)],
4174 'ContinueNode': [],
4175 'BreakNode': [],
4176 'ArgumentNode': [('positional', accept_node_list), ('kwargs', accept_kwargs)],
4177 'ArrayNode': [('args', accept_node)],
4178 'DictNode': [('args', accept_node)],
4179 'EmptyNode': [],
4180 'OrNode': [('left', accept_node), ('right', accept_node)],
4181 'AndNode': [('left', accept_node), ('right', accept_node)],
4182 'ComparisonNode': [('left', accept_node), ('right', accept_node), ('ctype', None, str)],
4183 'ArithmeticNode': [('left', accept_node), ('right', accept_node), ('op', None, str)],
4184 'NotNode': [('right', accept_node)],
4185 'CodeBlockNode': [('lines', accept_node_list)],
4186 'IndexNode': [('object', accept_node), ('index', accept_node)],
4187 'MethodNode': [('object', accept_node), ('args', accept_node), ('name', None, str)],
4188 'FunctionNode': [('args', accept_node), ('name', None, str)],
4189 'AssignmentNode': [('value', accept_node), ('var_name', None, str)],
4190 'PlusAssignmentNode': [('value', accept_node), ('var_name', None, str)],
4191 'ForeachClauseNode': [('items', accept_node), ('block', accept_node), ('varnames', None, list)],
4192 'IfClauseNode': [('ifs', accept_node_list), ('else', accept_node)],
4193 'IfNode': [('condition', accept_node), ('block', accept_node)],
4194 'UMinusNode': [('right', accept_node)],
4195 'TernaryNode': [('condition', accept_node), ('true', accept_node), ('false', accept_node)],
4196 }
4197
4198 accept_node(res_nb)
4199
4200 for n, c in [('ContinueNode', 2), ('BreakNode', 1), ('NotNode', 3)]:
4201 self.assertIn(n, node_counter)
4202 self.assertEqual(node_counter[n], c)
4203
4204 def test_introspect_dependencies_from_source(self):
4205 testdir = os.path.join(self.unit_test_dir, '56 introspection')
4206 testfile = os.path.join(testdir, 'meson.build')
4207 res_nb = self.introspect_directory(testfile, ['--scan-dependencies'] + self.meson_args)
4208 expected = [
4209 {
4210 'name': 'threads',
4211 'required': True,
4212 'version': [],
4213 'has_fallback': False,
4214 'conditional': False
4215 },
4216 {
4217 'name': 'zlib',
4218 'required': False,
4219 'version': [],
4220 'has_fallback': False,
4221 'conditional': False
4222 },
4223 {
4224 'name': 'bugDep1',
4225 'required': 'unknown',
4226 'version': [],
4227 'has_fallback': False,
4228 'conditional': False
4229 },
4230 {
4231 'name': 'somethingthatdoesnotexist',
4232 'required': True,
4233 'version': ['>=1.2.3'],
4234 'has_fallback': False,
4235 'conditional': True
4236 },
4237 {
4238 'name': 'look_i_have_a_fallback',
4239 'required': True,
4240 'version': ['>=1.0.0', '<=99.9.9'],
4241 'has_fallback': True,
4242 'conditional': True
4243 },
4244 ]
4245 self.maxDiff = None
4246 self.assertListEqual(res_nb, expected)
4247
4248 def test_unstable_coredata(self):
4249 testdir = os.path.join(self.common_test_dir, '1 trivial')
4250 self.init(testdir)
4251 # just test that the command does not fail (e.g. because it throws an exception)
4252 self._run([*self.meson_command, 'unstable-coredata', self.builddir])
4253
4254 @skip_if_no_cmake
4255 def test_cmake_prefix_path(self):
4256 testdir = os.path.join(self.unit_test_dir, '62 cmake_prefix_path')
4257 self.init(testdir, extra_args=['-Dcmake_prefix_path=' + os.path.join(testdir, 'prefix')])
4258
4259 @skip_if_no_cmake
4260 def test_cmake_parser(self):
4261 testdir = os.path.join(self.unit_test_dir, '63 cmake parser')
4262 self.init(testdir, extra_args=['-Dcmake_prefix_path=' + os.path.join(testdir, 'prefix')])
4263
4264 def test_alias_target(self):
4265 testdir = os.path.join(self.unit_test_dir, '64 alias target')
4266 self.init(testdir)
4267 self.build()
4268 self.assertPathDoesNotExist(os.path.join(self.builddir, 'prog' + exe_suffix))
4269 self.assertPathDoesNotExist(os.path.join(self.builddir, 'hello.txt'))
4270 self.run_target('build-all')
4271 self.assertPathExists(os.path.join(self.builddir, 'prog' + exe_suffix))
4272 self.assertPathExists(os.path.join(self.builddir, 'hello.txt'))
4273 out = self.run_target('aliased-run')
4274 self.assertIn('a run target was here', out)
4275
4276 def test_configure(self):
4277 testdir = os.path.join(self.common_test_dir, '2 cpp')
4278 self.init(testdir)
4279 self._run(self.mconf_command + [self.builddir])
4280
4281 def test_configure_with_augments(self):
4282 # A list-valued augment used to crash `meson configure <builddir>`.
4283 testdir = os.path.join(self.unit_test_dir, '47 reconfigure')
4284 self.init(testdir, extra_args=['-Dsub1:c_args=-DFOO'])
4285 out = self._run(self.mconf_command + [self.builddir])
4286 self.assertIn('sub1:c_args', out)
4287 self.assertIn('[-DFOO]', out)
4288
4289 def test_summary(self):
4290 testdir = os.path.join(self.unit_test_dir, '71 summary')
4291 out = self.init(testdir, extra_args=['-Denabled_opt=enabled', f'-Dpython={sys.executable}'])
4292 expected = textwrap.dedent(r'''
4293 Some Subproject 2.0
4294
4295 string : bar
4296 integer: 1
4297 boolean: true
4298
4299 subsub undefined
4300
4301 Something: Some value
4302
4303 My Project 1.0
4304
4305 Configuration
4306 Some boolean : false
4307 Another boolean: true
4308 Some string : Hello World
4309 A list : string
4310 1
4311 true
4312 empty list :
4313 enabled_opt : enabled
4314 A number : 1
4315 yes : YES
4316 no : NO
4317 comma list : a, b, c
4318
4319 Stuff
4320 missing prog : NO
4321 existing prog : ''' + ExternalProgram('python3', [sys.executable], silent=True).path + '''
4322 missing dep : NO
4323 external dep : YES 1.2.3
4324 internal dep : YES
4325 disabler : NO
4326
4327 Plugins
4328 long comma list: alpha, alphacolor, apetag, audiofx, audioparsers, auparse,
4329 autodetect, avi
4330
4331 Subprojects (for host machine)
4332 sub : YES
4333 sub2 : NO Problem encountered: This subproject failed
4334 subsub : YES (from sub2)
4335
4336 User defined options
4337 backend : ''' + self.backend_name + '''
4338 enabled_opt : enabled
4339 libdir : lib
4340 prefix : /usr
4341 python : ''' + sys.executable + '''
4342 ''')
4343 expected_lines = expected.split('\n')[1:]
4344 out_start = out.find(expected_lines[0])
4345 out_lines = out[out_start:].split('\n')[:len(expected_lines)]
4346 for e, o in zip(expected_lines, out_lines):
4347 if e.startswith(' external dep'):
4348 self.assertRegex(o, r'^ external dep : (YES [0-9.]*|NO)$')
4349 else:
4350 self.assertEqual(o, e)
4351
4352 def test_meson_compile(self):
4353 """Test the meson compile command."""
4354
4355 def get_exe_name(basename: str) -> str:
4356 if is_windows():
4357 return f'{basename}.exe'
4358 else:
4359 return basename
4360
4361 def get_shared_lib_name(basename: str) -> str:
4362 if mesonbuild.envconfig.detect_msys2_arch():
4363 return f'lib{basename}.dll'
4364 elif is_windows():
4365 return f'{basename}.dll'
4366 elif is_cygwin():
4367 return f'cyg{basename}.dll'
4368 elif is_osx():
4369 return f'lib{basename}.dylib'
4370 else:
4371 return f'lib{basename}.so'
4372
4373 def get_static_lib_name(basename: str) -> str:
4374 return f'lib{basename}.a'
4375
4376 # Base case (no targets or additional arguments)
4377
4378 testdir = os.path.join(self.common_test_dir, '1 trivial')
4379 self.init(testdir)
4380
4381 self._run([*self.meson_command, 'compile', '-C', self.builddir])
4382 self.assertPathExists(os.path.join(self.builddir, get_exe_name('trivialprog')))
4383
4384 # `--clean`
4385
4386 self._run([*self.meson_command, 'compile', '-C', self.builddir, '--clean'])
4387 self.assertPathDoesNotExist(os.path.join(self.builddir, get_exe_name('trivialprog')))
4388
4389 # Target specified in a project with unique names
4390
4391 testdir = os.path.join(self.common_test_dir, '6 linkshared')
4392 self.init(testdir, extra_args=['--wipe'])
4393 # Multiple targets and target type specified
4394 self._run([*self.meson_command, 'compile', '-C', self.builddir, 'mylib', 'mycpplib:shared_library'])
4395 # Check that we have a shared lib, but not an executable, i.e. check that target actually worked
4396 self.assertPathExists(os.path.join(self.builddir, get_shared_lib_name('mylib')))
4397 self.assertPathDoesNotExist(os.path.join(self.builddir, get_exe_name('prog')))
4398 self.assertPathExists(os.path.join(self.builddir, get_shared_lib_name('mycpplib')))
4399 self.assertPathDoesNotExist(os.path.join(self.builddir, get_exe_name('cppprog')))
4400
4401 # Target specified in a project with non unique names
4402
4403 testdir = os.path.join(self.common_test_dir, '185 same target name')
4404 self.init(testdir, extra_args=['--wipe'])
4405 self._run([*self.meson_command, 'compile', '-C', self.builddir, './foo'])
4406 self.assertPathExists(os.path.join(self.builddir, get_static_lib_name('foo')))
4407 self._run([*self.meson_command, 'compile', '-C', self.builddir, 'sub/foo'])
4408 self.assertPathExists(os.path.join(self.builddir, 'sub', get_static_lib_name('foo')))
4409
4410 # run_target
4411
4412 testdir = os.path.join(self.common_test_dir, '51 run target')
4413 self.init(testdir, extra_args=['--wipe'])
4414 out = self._run([*self.meson_command, 'compile', '-C', self.builddir, 'py3hi'])
4415 self.assertIn('I am Python3.', out)
4416
4417 # `--$BACKEND-args`
4418
4419 testdir = os.path.join(self.common_test_dir, '1 trivial')
4420 if self.backend is Backend.ninja:
4421 self.init(testdir, extra_args=['--wipe'])
4422 # Dry run - should not create a program
4423 self._run([*self.meson_command, 'compile', '-C', self.builddir, '--ninja-args=-n'])
4424 self.assertPathDoesNotExist(os.path.join(self.builddir, get_exe_name('trivialprog')))
4425 elif self.backend is Backend.vs:
4426 self.init(testdir, extra_args=['--wipe'])
4427 self._run([*self.meson_command, 'compile', '-C', self.builddir])
4428 # Explicitly clean the target through msbuild interface
4429 self._run([*self.meson_command, 'compile', '-C', self.builddir, '--vs-args=-t:{}:Clean'.format(re.sub(r'[\%\$\@\;\.\(\)\']', '_', get_exe_name('trivialprog')))])
4430 self.assertPathDoesNotExist(os.path.join(self.builddir, get_exe_name('trivialprog')))
4431
4432 def test_spurious_reconfigure_built_dep_file(self):
4433 testdir = os.path.join(self.unit_test_dir, '73 dep files')
4434
4435 # Regression test: Spurious reconfigure was happening when build
4436 # directory is inside source directory.
4437 # See https://gitlab.freedesktop.org/gstreamer/gst-build/-/issues/85.
4438 srcdir = os.path.join(self.builddir, 'srctree')
4439 shutil.copytree(testdir, srcdir)
4440 builddir = os.path.join(srcdir, '_build')
4441 self.change_builddir(builddir)
4442
4443 self.init(srcdir)
4444 self.build()
4445
4446 # During first configure the file did not exist so no dependency should
4447 # have been set. A rebuild should not trigger a reconfigure.
4448 self.clean()
4449 out = self.build()
4450 self.assertNotIn('Project configured', out)
4451
4452 self.init(srcdir, extra_args=['--reconfigure'])
4453
4454 # During the reconfigure the file did exist, but is inside build
4455 # directory, so no dependency should have been set. A rebuild should not
4456 # trigger a reconfigure.
4457 self.clean()
4458 out = self.build()
4459 self.assertNotIn('Project configured', out)
4460
4461 def _test_junit(self, case: str) -> None:
4462 try:
4463 import lxml.etree as et
4464 except ImportError:
4465 raise SkipTest('lxml required, but not found.')
4466
4467 schema = et.XMLSchema(et.parse(str(Path(self.src_root) / 'data' / 'schema.xsd')))
4468
4469 self.init(case)
4470 self.run_tests()
4471
4472 junit = et.parse(str(Path(self.builddir) / 'meson-logs' / 'testlog.junit.xml'))
4473 try:
4474 schema.assertValid(junit)
4475 except et.DocumentInvalid as e:
4476 self.fail(e.error_log)
4477
4478 def test_junit_valid_tap(self):
4479 self._test_junit(os.path.join(self.common_test_dir, '206 tap tests'))
4480
4481 def test_junit_valid_exitcode(self):
4482 self._test_junit(os.path.join(self.common_test_dir, '41 test args'))
4483
4484 def test_junit_valid_gtest(self):
4485 self._test_junit(os.path.join(self.framework_test_dir, '2 gtest'))
4486
4487 def test_link_language_linker(self):
4488 # TODO: there should be some way to query how we're linking things
4489 # without resorting to reading the ninja.build file
4490 if self.backend is not Backend.ninja:
4491 raise SkipTest('This test reads the ninja file')
4492
4493 testdir = os.path.join(self.common_test_dir, '225 link language')
4494 self.init(testdir)
4495
4496 build_ninja = os.path.join(self.builddir, 'build.ninja')
4497 with open(build_ninja, encoding='utf-8') as f:
4498 contents = f.read()
4499
4500 self.assertRegex(contents, r'build main(\.exe)?.*: c_LINKER')
4501 self.assertRegex(contents, r'build (lib|cyg)?mylib.*: c_LINKER')
4502
4503 def test_commands_documented(self):
4504 '''
4505 Test that all listed meson commands are documented in Commands.md.
4506 '''
4507
4508 # The docs directory is not in release tarballs.
4509 if not os.path.isdir('docs'):
4510 raise SkipTest('Doc directory does not exist.')
4511 doc_path = 'docs/markdown/Commands.md'
4512
4513 md = None
4514 with open(doc_path, encoding='utf-8') as f:
4515 md = f.read()
4516 self.assertIsNotNone(md)
4517
4518 ## Get command sections
4519
4520 section_pattern = re.compile(r'^### (.+)$', re.MULTILINE)
4521 md_command_section_matches = [i for i in section_pattern.finditer(md)]
4522 md_command_sections = dict()
4523 for i, s in enumerate(md_command_section_matches):
4524 section_end = len(md) if i == len(md_command_section_matches) - 1 else md_command_section_matches[i + 1].start()
4525 md_command_sections[s.group(1)] = (s.start(), section_end)
4526
4527 ## Validate commands
4528
4529 md_commands = {k for k,v in md_command_sections.items()}
4530 help_output = self._run(self.meson_command + ['--help'])
4531 # Python's argument parser might put the command list to its own line. Or it might not.
4532 self.assertTrue(help_output.startswith('usage: '))
4533 lines = help_output.split('\n')
4534 line1 = lines[0]
4535 line2 = lines[1]
4536 if '{' in line1:
4537 cmndline = line1
4538 else:
4539 self.assertIn('{', line2)
4540 cmndline = line2
4541 cmndstr = cmndline.split('{')[1]
4542 self.assertIn('}', cmndstr)
4543 help_commands = set(cmndstr.split('}')[0].split(','))
4544 help_commands.remove('fmt') # Remove the alias
4545 self.assertTrue(len(help_commands) > 0, 'Must detect some command names.')
4546
4547 self.assertEqual(md_commands | {'help'}, help_commands, f'Doc file: `{doc_path}`')
4548
4549 ## Validate that each section has proper placeholders
4550
4551 def get_data_pattern(command):
4552 return re.compile(
4553 r'{{ ' + command + r'_usage.inc }}[\r\n]'
4554 r'.*?'
4555 r'{{ ' + command + r'_arguments.inc }}[\r\n]',
4556 flags = re.MULTILINE|re.DOTALL)
4557
4558 for command in md_commands:
4559 m = get_data_pattern(command).search(md, pos=md_command_sections[command][0], endpos=md_command_sections[command][1])
4560 self.assertIsNotNone(m, f'Command `{command}` is missing placeholders for dynamic data. Doc file: `{doc_path}`')
4561
4562 def _check_coverage_files(self, types=('text', 'xml', 'html')):
4563 covdir = Path(self.builddir) / 'meson-logs'
4564 files = []
4565 if 'text' in types:
4566 files.append('coverage.txt')
4567 if 'xml' in types:
4568 files.append('coverage.xml')
4569 if 'html' in types:
4570 files.append('coveragereport/index.html')
4571 for f in files:
4572 self.assertTrue((covdir / f).is_file(), msg=f'{f} is not a file')
4573
4574 def test_coverage(self):
4575 if mesonbuild.envconfig.detect_msys2_arch():
4576 raise SkipTest('Skipped due to problems with coverage on MSYS2')
4577 gcovr_exe, gcovr_new_rootdir = mesonbuild.tooldetect.detect_gcovr()
4578 if not gcovr_exe:
4579 raise SkipTest('gcovr not found, or too old')
4580 testdir = os.path.join(self.common_test_dir, '1 trivial')
4581 env = get_fake_env(testdir, self.builddir, self.prefix)
4582 cc = detect_c_compiler(env, MachineChoice.HOST)
4583 if cc.get_id() == 'clang':
4584 if not mesonbuild.tooldetect.detect_llvm_cov():
4585 raise SkipTest('llvm-cov not found')
4586 if cc.get_id() == 'msvc':
4587 raise SkipTest('Test only applies to non-MSVC compilers')
4588 self.init(testdir, extra_args=['-Db_coverage=true'])
4589 self.build()
4590 self.run_tests()
4591 self.run_target('coverage')
4592 self._check_coverage_files()
4593
4594 def test_coverage_complex(self):
4595 if mesonbuild.envconfig.detect_msys2_arch():
4596 raise SkipTest('Skipped due to problems with coverage on MSYS2')
4597 gcovr_exe, gcovr_new_rootdir = mesonbuild.tooldetect.detect_gcovr()
4598 if not gcovr_exe:
4599 raise SkipTest('gcovr not found, or too old')
4600 testdir = os.path.join(self.common_test_dir, '105 generatorcustom')
4601 env = get_fake_env(testdir, self.builddir, self.prefix)
4602 cc = detect_c_compiler(env, MachineChoice.HOST)
4603 if cc.get_id() == 'clang':
4604 if not mesonbuild.tooldetect.detect_llvm_cov():
4605 raise SkipTest('llvm-cov not found')
4606 if cc.get_id() == 'msvc':
4607 raise SkipTest('Test only applies to non-MSVC compilers')
4608 self.init(testdir, extra_args=['-Db_coverage=true'])
4609 self.build()
4610 self.run_tests()
4611 self.run_target('coverage')
4612 self._check_coverage_files()
4613
4614 def test_coverage_html(self):
4615 if mesonbuild.envconfig.detect_msys2_arch():
4616 raise SkipTest('Skipped due to problems with coverage on MSYS2')
4617 gcovr_exe, gcovr_new_rootdir = mesonbuild.tooldetect.detect_gcovr()
4618 if not gcovr_exe:
4619 raise SkipTest('gcovr not found, or too old')
4620 testdir = os.path.join(self.common_test_dir, '1 trivial')
4621 env = get_fake_env(testdir, self.builddir, self.prefix)
4622 cc = detect_c_compiler(env, MachineChoice.HOST)
4623 if cc.get_id() == 'clang':
4624 if not mesonbuild.tooldetect.detect_llvm_cov():
4625 raise SkipTest('llvm-cov not found')
4626 if cc.get_id() == 'msvc':
4627 raise SkipTest('Test only applies to non-MSVC compilers')
4628 self.init(testdir, extra_args=['-Db_coverage=true'])
4629 self.build()
4630 self.run_tests()
4631 self.run_target('coverage-html')
4632 self._check_coverage_files(['html'])
4633
4634 def test_coverage_text(self):
4635 if mesonbuild.envconfig.detect_msys2_arch():
4636 raise SkipTest('Skipped due to problems with coverage on MSYS2')
4637 gcovr_exe, gcovr_new_rootdir = mesonbuild.tooldetect.detect_gcovr()
4638 if not gcovr_exe:
4639 raise SkipTest('gcovr not found, or too old')
4640 testdir = os.path.join(self.common_test_dir, '1 trivial')
4641 env = get_fake_env(testdir, self.builddir, self.prefix)
4642 cc = detect_c_compiler(env, MachineChoice.HOST)
4643 if cc.get_id() == 'clang':
4644 if not mesonbuild.tooldetect.detect_llvm_cov():
4645 raise SkipTest('llvm-cov not found')
4646 if cc.get_id() == 'msvc':
4647 raise SkipTest('Test only applies to non-MSVC compilers')
4648 self.init(testdir, extra_args=['-Db_coverage=true'])
4649 self.build()
4650 self.run_tests()
4651 self.run_target('coverage-text')
4652 self._check_coverage_files(['text'])
4653
4654 def test_coverage_xml(self):
4655 if mesonbuild.envconfig.detect_msys2_arch():
4656 raise SkipTest('Skipped due to problems with coverage on MSYS2')
4657 gcovr_exe, gcovr_new_rootdir = mesonbuild.tooldetect.detect_gcovr()
4658 if not gcovr_exe:
4659 raise SkipTest('gcovr not found, or too old')
4660 testdir = os.path.join(self.common_test_dir, '1 trivial')
4661 env = get_fake_env(testdir, self.builddir, self.prefix)
4662 cc = detect_c_compiler(env, MachineChoice.HOST)
4663 if cc.get_id() == 'clang':
4664 if not mesonbuild.tooldetect.detect_llvm_cov():
4665 raise SkipTest('llvm-cov not found')
4666 if cc.get_id() == 'msvc':
4667 raise SkipTest('Test only applies to non-MSVC compilers')
4668 self.init(testdir, extra_args=['-Db_coverage=true'])
4669 self.build()
4670 self.run_tests()
4671 self.run_target('coverage-xml')
4672 self._check_coverage_files(['xml'])
4673
4674 def test_coverage_escaping(self):
4675 if mesonbuild.envconfig.detect_msys2_arch():
4676 raise SkipTest('Skipped due to problems with coverage on MSYS2')
4677 gcovr_exe, gcovr_new_rootdir = mesonbuild.tooldetect.detect_gcovr()
4678 if not gcovr_exe:
4679 raise SkipTest('gcovr not found, or too old')
4680 testdir = os.path.join(self.common_test_dir, '243 escape++')
4681 env = get_fake_env(testdir, self.builddir, self.prefix)
4682 cc = detect_c_compiler(env, MachineChoice.HOST)
4683 if cc.get_id() == 'clang':
4684 if not mesonbuild.tooldetect.detect_llvm_cov():
4685 raise SkipTest('llvm-cov not found')
4686 if cc.get_id() == 'msvc':
4687 raise SkipTest('Test only applies to non-MSVC compilers')
4688 self.init(testdir, extra_args=['-Db_coverage=true'])
4689 self.build()
4690 self.run_tests()
4691 self.run_target('coverage')
4692 self._check_coverage_files()
4693
4694 def test_cross_file_constants(self):
4695 crossfile1 = UNIT_MACHINEFILE_DIR / 'constant1.txt'
4696 crossfile2 = UNIT_MACHINEFILE_DIR / 'constant2.txt'
4697 values = mesonbuild.machinefile.parse_machine_files([crossfile1,
4698 crossfile2],
4699 self.builddir)
4700 self.assertEqual(values['binaries']['c'], '/toolchain/gcc')
4701 self.assertEqual(values['properties']['c_args'],
4702 ['--sysroot=/toolchain/sysroot', '-DSOMETHING'])
4703 self.assertEqual(values['properties']['cpp_args'],
4704 ['--sysroot=/toolchain/sysroot', '-DSOMETHING', '-DSOMETHING_ELSE'])
4705 self.assertEqual(values['properties']['rel_to_src'], os.path.join(self.builddir, 'tool'))
4706 self.assertEqual(values['properties']['rel_to_file'], os.path.join(os.path.dirname(crossfile2), 'tool'))
4707 self.assertEqual(values['properties']['no_escaping'], os.path.join(f'@{os.path.dirname(crossfile2)}@', 'tool'))
4708
4709 @skipIf(is_windows(), 'Directory cleanup fails for some reason')
4710 def test_wrap_git(self):
4711 with tempfile.TemporaryDirectory() as tmpdir:
4712 srcdir = os.path.join(tmpdir, 'src')
4713 shutil.copytree(os.path.join(self.unit_test_dir, '80 wrap-git'), srcdir)
4714 upstream = os.path.join(srcdir, 'subprojects', 'wrap_git_upstream')
4715 upstream_uri = Path(upstream).as_uri()
4716 git_init(upstream)
4717 with open(os.path.join(srcdir, 'subprojects', 'wrap_git.wrap'), 'w', encoding='utf-8') as f:
4718 f.write(textwrap.dedent('''
4719 [wrap-git]
4720 url = {}
4721 patch_directory = wrap_git_builddef
4722 revision = master
4723 '''.format(upstream_uri)))
4724 out = self.init(srcdir)
4725 self.build()
4726 self.run_tests()
4727
4728 # Make sure the warning does not occur on the first init.
4729 out_of_date_warning = 'revision may be out of date'
4730 self.assertNotIn(out_of_date_warning, out)
4731
4732 # Change the wrap's revisions, reconfigure, and make sure it does
4733 # warn on the reconfigure.
4734 with open(os.path.join(srcdir, 'subprojects', 'wrap_git.wrap'), 'w', encoding='utf-8') as f:
4735 f.write(textwrap.dedent('''
4736 [wrap-git]
4737 url = {}
4738 patch_directory = wrap_git_builddef
4739 revision = not-master
4740 '''.format(upstream_uri)))
4741 out = self.init(srcdir, extra_args='--reconfigure')
4742 self.assertIn(out_of_date_warning, out)
4743
4744 def test_extract_objects_custom_target_no_warning(self):
4745 testdir = os.path.join(self.common_test_dir, '22 object extraction')
4746
4747 out = self.init(testdir)
4748 self.assertNotRegex(out, "WARNING:.*can't be converted to File object")
4749
4750 def test_multi_output_custom_target_no_warning(self):
4751 testdir = os.path.join(self.common_test_dir, '228 custom_target source')
4752
4753 out = self.init(testdir)
4754 self.assertNotRegex(out, 'WARNING:.*Using the first one.')
4755 self.build()
4756 self.run_tests()
4757
4758 def test_custom_target_index_as_test_prereq(self):
4759 if self.backend is not Backend.ninja:
4760 raise SkipTest('ninja backend needed for "meson test" to build test dependencies')
4761
4762 testdir = os.path.join(self.unit_test_dir, '132 custom target index test')
4763 self.init(testdir)
4764 self.run_tests()
4765
4766 @skipUnless(is_linux() and (re.search('^i.86$|^x86$|^x64$|^x86_64$|^amd64$', platform.processor()) is not None),
4767 'Requires ASM compiler for x86 or x86_64 platform currently only available on Linux CI runners')
4768 def test_nostdlib(self):
4769 testdir = os.path.join(self.unit_test_dir, '77 nostdlib')
4770 machinefile = os.path.join(self.builddir, 'machine.txt')
4771 with open(machinefile, 'w', encoding='utf-8') as f:
4772 f.write(textwrap.dedent('''
4773 [properties]
4774 c_stdlib = 'mylibc'
4775 '''))
4776
4777 # Test native C stdlib
4778 self.meson_native_files = [machinefile]
4779 self.init(testdir)
4780 self.build()
4781
4782 # Test cross C stdlib
4783 self.new_builddir()
4784 self.meson_native_files = []
4785 self.meson_cross_files = [machinefile]
4786 self.init(testdir)
4787 self.build()
4788
4789 def test_meson_version_compare(self):
4790 testdir = os.path.join(self.unit_test_dir, '81 meson version compare')
4791 out = self.init(testdir)
4792 self.assertNotRegex(out, r'WARNING')
4793
4794 def test_wrap_redirect(self):
4795 redirect_wrap = os.path.join(self.builddir, 'redirect.wrap')
4796 real_wrap = os.path.join(self.builddir, 'foo/subprojects/real.wrap')
4797 os.makedirs(os.path.dirname(real_wrap))
4798
4799 # Invalid redirect, filename must have .wrap extension
4800 with open(redirect_wrap, 'w', encoding='utf-8') as f:
4801 f.write(textwrap.dedent('''
4802 [wrap-redirect]
4803 filename = foo/subprojects/real.wrapper
4804 '''))
4805 with self.assertRaisesRegex(WrapException, "wrap-redirect filename 'foo/subprojects/real.wrapper' must be a .wrap file"):
4806 PackageDefinition.from_wrap_file(redirect_wrap)
4807
4808 # Invalid redirect, filename cannot be in parent directory
4809 with open(redirect_wrap, 'w', encoding='utf-8') as f:
4810 f.write(textwrap.dedent('''
4811 [wrap-redirect]
4812 filename = ../real.wrap
4813 '''))
4814 with self.assertRaisesRegex(WrapException, "wrap-redirect filename '../real.wrap' cannot contain '..'"):
4815 PackageDefinition.from_wrap_file(redirect_wrap)
4816
4817 # Invalid redirect, filename must be in foo/subprojects/real.wrap
4818 with open(redirect_wrap, 'w', encoding='utf-8') as f:
4819 f.write(textwrap.dedent('''
4820 [wrap-redirect]
4821 filename = foo/real.wrap
4822 '''))
4823 with self.assertRaisesRegex(WrapException, "wrap-redirect filename 'foo/real.wrap' must be in the form foo/subprojects/bar.wrap"):
4824 PackageDefinition.from_wrap_file(redirect_wrap)
4825
4826 # Correct redirect
4827 with open(redirect_wrap, 'w', encoding='utf-8') as f:
4828 f.write(textwrap.dedent('''
4829 [wrap-redirect]
4830 filename = foo/subprojects/real.wrap
4831 '''))
4832 with open(real_wrap, 'w', encoding='utf-8') as f:
4833 f.write(textwrap.dedent('''
4834 [wrap-git]
4835 url = http://invalid
4836 '''))
4837 wrap = PackageDefinition.from_wrap_file(redirect_wrap)
4838 self.assertEqual(wrap.get('url'), 'http://invalid')
4839
4840 @skip_if_no_cmake
4841 def test_nested_cmake_rebuild(self) -> None:
4842 # This checks a bug where if a non-meson project is used as a third
4843 # level (or deeper) subproject it doesn't cause a rebuild if the build
4844 # files for that project are changed
4845 testdir = os.path.join(self.unit_test_dir, '84 nested subproject regenerate depends')
4846 cmakefile = Path(testdir) / 'subprojects' / 'sub2' / 'CMakeLists.txt'
4847 self.init(testdir)
4848 self.build()
4849 with cmakefile.open('a', encoding='utf-8'):
4850 os.utime(str(cmakefile))
4851 self.assertReconfiguredBuildIsNoop()
4852
4853 def test_version_file(self):
4854 srcdir = os.path.join(self.common_test_dir, '2 cpp')
4855 self.init(srcdir)
4856 projinfo = self.introspect('--projectinfo')
4857 self.assertEqual(projinfo['version'], '1.0.0')
4858
4859 def test_cflags_cppflags(self):
4860 envs = {'CPPFLAGS': '-DCPPFLAG',
4861 'CFLAGS': '-DCFLAG',
4862 'CXXFLAGS': '-DCXXFLAG'}
4863 srcdir = os.path.join(self.unit_test_dir, '88 multiple envvars')
4864 self.init(srcdir, override_envvars=envs)
4865 self.build()
4866
4867 def test_build_b_options(self) -> None:
4868 # Currently (0.57) these do nothing, but they've always been allowed
4869 srcdir = os.path.join(self.common_test_dir, '2 cpp')
4870 self.init(srcdir, extra_args=['-Dbuild.b_lto=true'])
4871
4872 def test_install_skip_subprojects(self):
4873 testdir = os.path.join(self.unit_test_dir, '91 install skip subprojects')
4874 self.init(testdir)
4875 self.build()
4876
4877 main_expected = [
4878 '',
4879 'share',
4880 'include',
4881 'foo',
4882 'bin',
4883 'share/foo',
4884 'share/foo/foo.dat',
4885 'include/foo.h',
4886 'foo/foofile',
4887 'bin/foo' + exe_suffix,
4888 ]
4889 bar_expected = [
4890 'bar',
4891 'share/bar',
4892 'share/bar/bar.dat',
4893 'include/bar.h',
4894 'bin/bar' + exe_suffix,
4895 'bar/barfile'
4896 ]
4897 env = get_fake_env(testdir, self.builddir, self.prefix)
4898 cc = detect_c_compiler(env, MachineChoice.HOST)
4899 if cc.get_argument_syntax() == 'msvc':
4900 main_expected.append('bin/foo.pdb')
4901 bar_expected.append('bin/bar.pdb')
4902 prefix = destdir_join(self.installdir, self.prefix)
4903 main_expected = [Path(prefix, p) for p in main_expected]
4904 bar_expected = [Path(prefix, p) for p in bar_expected]
4905 all_expected = main_expected + bar_expected
4906
4907 def check_installed_files(extra_args, expected):
4908 args = ['install', '--destdir', self.installdir] + extra_args
4909 self._run(self.meson_command + args, workdir=self.builddir)
4910 all_files = [p for p in Path(self.installdir).rglob('*')]
4911 self.assertEqual(sorted(expected), sorted(all_files))
4912 windows_proof_rmtree(self.installdir)
4913
4914 check_installed_files([], all_expected)
4915 check_installed_files(['--skip-subprojects'], main_expected)
4916 check_installed_files(['--skip-subprojects', 'bar'], main_expected)
4917 check_installed_files(['--skip-subprojects', 'another'], all_expected)
4918
4919 def test_adding_subproject_to_configure_project(self) -> None:
4920 srcdir = os.path.join(self.unit_test_dir, '92 new subproject in configured project')
4921 self.init(srcdir)
4922 self.build()
4923 self.setconf('-Duse-sub=true')
4924 self.build()
4925
4926 def test_devenv(self):
4927 testdir = os.path.join(self.unit_test_dir, '90 devenv')
4928 self.init(testdir)
4929 self.build()
4930
4931 cmd = self.meson_command + ['devenv', '-C', self.builddir]
4932 script = os.path.join(testdir, 'test-devenv.py')
4933 app = os.path.join(self.builddir, 'app')
4934 self._run(cmd + python_command + [script])
4935 self.assertEqual('This is text.', self._run(cmd + [app]).strip())
4936
4937 cmd = self.meson_command + ['devenv', '-C', self.builddir, '--dump']
4938 o = self._run(cmd)
4939 expected = os.pathsep.join(['/prefix', '$TEST_C', '/suffix'])
4940 self.assertIn(f'TEST_C="{expected}"', o)
4941 self.assertIn('export TEST_C', o)
4942
4943 cmd = self.meson_command + ['devenv', '-C', self.builddir, '--dump', '--dump-format', 'sh']
4944 o = self._run(cmd)
4945 expected = os.pathsep.join(['/prefix', '$TEST_C', '/suffix'])
4946 self.assertIn(f'TEST_C="{expected}"', o)
4947 self.assertNotIn('export', o)
4948
4949 cmd = self.meson_command + ['devenv', '-C', self.builddir, '--dump', '--dump-format', 'vscode']
4950 o = self._run(cmd)
4951 expected = os.pathsep.join(['/prefix', '/suffix'])
4952 self.assertIn(f'TEST_C="{expected}"', o)
4953 self.assertNotIn('export', o)
4954
4955 fname = os.path.join(self.builddir, 'dump.env')
4956 cmd = self.meson_command + ['devenv', '-C', self.builddir, '--dump', fname]
4957 o = self._run(cmd)
4958 self.assertEqual(o, '')
4959 o = Path(fname).read_text(encoding='utf-8')
4960 expected = os.pathsep.join(['/prefix', '$TEST_C', '/suffix'])
4961 self.assertIn(f'TEST_C="{expected}"', o)
4962 self.assertIn('export TEST_C', o)
4963
4964 cmd = self.meson_command + ['devenv', '-C', self.builddir] + python_command + ['-c', 'import sys; sys.exit(42)']
4965 result = subprocess.run(cmd, encoding='utf-8')
4966 self.assertEqual(result.returncode, 42)
4967
4968 @skipIfNoExecutable('clang-format')
4969 def test_clang_format_check(self):
4970 if self.backend is not Backend.ninja:
4971 raise SkipTest(f'Skipping clang-format tests with {self.backend.name} backend')
4972
4973 testdir = os.path.join(self.unit_test_dir, '93 clangformat')
4974 newdir = os.path.join(self.builddir, 'testdir')
4975 shutil.copytree(testdir, newdir)
4976 self.new_builddir()
4977 self.init(newdir)
4978
4979 # Should reformat 1 file but not return error
4980 output = self.build('clang-format')
4981 self.assertEqual(1, output.count('File reformatted:'))
4982
4983 # Reset source tree then try again with clang-format-check, it should
4984 # return an error code this time.
4985 windows_proof_rmtree(newdir)
4986 shutil.copytree(testdir, newdir)
4987 with self.assertRaises(subprocess.CalledProcessError):
4988 output = self.build('clang-format-check')
4989 self.assertEqual(1, output.count('File reformatted:'))
4990
4991 # The check format should not touch any files. Thus
4992 # running format again has some work to do.
4993 output = self.build('clang-format')
4994 self.assertEqual(1, output.count('File reformatted:'))
4995 self.build('clang-format-check')
4996
4997 def test_custom_target_implicit_include(self):
4998 testdir = os.path.join(self.unit_test_dir, '94 custominc')
4999 self.init(testdir)
5000 self.build()
5001 compdb = self.get_compdb()
5002 matches = 0
5003 for c in compdb:
5004 if 'prog.c' in c['file']:
5005 self.assertNotIn('easytogrepfor', c['command'])
5006 matches += 1
5007 self.assertEqual(matches, 1)
5008 matches = 0
5009 for c in compdb:
5010 if 'prog2.c' in c['file']:
5011 self.assertIn('easytogrepfor', c['command'])
5012 matches += 1
5013 self.assertEqual(matches, 1)
5014
5015 def test_env_flags_to_linker(self) -> None:
5016 # Compilers that act as drivers should add their compiler flags to the
5017 # linker, those that do not shouldn't
5018 with mock.patch.dict(os.environ, {'CFLAGS': '-DCFLAG', 'LDFLAGS': '-flto'}):
5019 env = get_fake_env()
5020
5021 # Get the compiler so we know which compiler class to mock.
5022 cc = detect_compiler_for(env, 'c', MachineChoice.HOST, True, '')
5023
5024 # C does have a separate linking step. It can be done through the compiler
5025 # driver or not; act accordingly.
5026 if cc.USED_FOR_SEPARATE_LINKING_STEP:
5027 link_args = env.coredata.get_external_link_args(cc.for_machine, cc.language)
5028 self.assertEqual(sorted(link_args), sorted(['-DCFLAG', '-flto']))
5029 else:
5030 link_args = env.coredata.get_external_link_args(cc.for_machine, cc.language)
5031 self.assertEqual(sorted(link_args), sorted(['-flto']))
5032
5033 def test_install_tag(self) -> None:
5034 testdir = os.path.join(self.unit_test_dir, '98 install all targets')
5035 self.init(testdir)
5036 self.build()
5037
5038 env = get_fake_env(testdir, self.builddir, self.prefix)
5039 cc = detect_c_compiler(env, MachineChoice.HOST)
5040
5041 def shared_lib_name(name):
5042 if cc.get_id() in {'msvc', 'clang-cl'}:
5043 return f'bin/{name}.dll'
5044 elif is_windows():
5045 return f'bin/lib{name}.dll'
5046 elif is_cygwin():
5047 return f'bin/cyg{name}.dll'
5048 elif is_osx():
5049 return f'lib/lib{name}.dylib'
5050 return f'lib/lib{name}.so'
5051
5052 def exe_name(name):
5053 if is_windows() or is_cygwin():
5054 return f'{name}.exe'
5055 return name
5056
5057 installpath = Path(self.installdir)
5058
5059 expected_common = {
5060 installpath,
5061 Path(installpath, 'usr'),
5062 }
5063
5064 expected_devel = expected_common | {
5065 Path(installpath, 'usr/include'),
5066 Path(installpath, 'usr/include/bar-devel.h'),
5067 Path(installpath, 'usr/include/bar2-devel.h'),
5068 Path(installpath, 'usr/include/foo1-devel.h'),
5069 Path(installpath, 'usr/include/foo2-devel.h'),
5070 Path(installpath, 'usr/include/foo3-devel.h'),
5071 Path(installpath, 'usr/include/out-devel.h'),
5072 Path(installpath, 'usr/lib'),
5073 Path(installpath, 'usr/lib/libstatic.a'),
5074 Path(installpath, 'usr/lib/libboth.a'),
5075 Path(installpath, 'usr/lib/libboth2.a'),
5076 Path(installpath, 'usr/include/ct-header1.h'),
5077 Path(installpath, 'usr/include/ct-header3.h'),
5078 Path(installpath, 'usr/include/subdir-devel'),
5079 Path(installpath, 'usr/include/custom_files'),
5080 Path(installpath, 'usr/include/custom_files/data.txt'),
5081 }
5082
5083 if cc.get_id() in {'msvc', 'clang-cl'}:
5084 expected_devel |= {
5085 Path(installpath, 'usr/bin'),
5086 Path(installpath, 'usr/bin/app.pdb'),
5087 Path(installpath, 'usr/bin/app2.pdb'),
5088 Path(installpath, 'usr/bin/both.pdb'),
5089 Path(installpath, 'usr/bin/both2.pdb'),
5090 Path(installpath, 'usr/bin/bothcustom.pdb'),
5091 Path(installpath, 'usr/bin/shared.pdb'),
5092 Path(installpath, 'usr/bin/versioned_shared-1.pdb'),
5093 Path(installpath, 'usr/lib/both.lib'),
5094 Path(installpath, 'usr/lib/both2.lib'),
5095 Path(installpath, 'usr/lib/bothcustom.lib'),
5096 Path(installpath, 'usr/lib/shared.lib'),
5097 Path(installpath, 'usr/lib/versioned_shared.lib'),
5098 Path(installpath, 'usr/otherbin'),
5099 Path(installpath, 'usr/otherbin/app-otherdir.pdb'),
5100 }
5101 elif is_windows() or is_cygwin():
5102 expected_devel |= {
5103 Path(installpath, 'usr/lib/libboth.dll.a'),
5104 Path(installpath, 'usr/lib/libboth2.dll.a'),
5105 Path(installpath, 'usr/lib/libshared.dll.a'),
5106 Path(installpath, 'usr/lib/libbothcustom.dll.a'),
5107 Path(installpath, 'usr/lib/libversioned_shared.dll.a'),
5108 }
5109 else:
5110 expected_devel |= {
5111 Path(installpath, 'usr/' + shared_lib_name('versioned_shared')),
5112 }
5113
5114 expected_runtime = expected_common | {
5115 Path(installpath, 'usr/bin'),
5116 Path(installpath, 'usr/bin/' + exe_name('app')),
5117 Path(installpath, 'usr/otherbin'),
5118 Path(installpath, 'usr/otherbin/' + exe_name('app-otherdir')),
5119 Path(installpath, 'usr/bin/' + exe_name('app2')),
5120 Path(installpath, 'usr/' + shared_lib_name('shared')),
5121 Path(installpath, 'usr/' + shared_lib_name('both')),
5122 Path(installpath, 'usr/' + shared_lib_name('both2')),
5123 }
5124
5125 if is_windows() or is_cygwin():
5126 expected_runtime |= {
5127 Path(installpath, 'usr/' + shared_lib_name('versioned_shared-1')),
5128 }
5129 elif is_osx():
5130 expected_runtime |= {
5131 Path(installpath, 'usr/' + shared_lib_name('versioned_shared.1')),
5132 }
5133 else:
5134 expected_runtime |= {
5135 Path(installpath, 'usr/' + shared_lib_name('versioned_shared') + '.1'),
5136 Path(installpath, 'usr/' + shared_lib_name('versioned_shared') + '.1.2.3'),
5137 }
5138
5139 expected_custom = expected_common | {
5140 Path(installpath, 'usr/share'),
5141 Path(installpath, 'usr/share/bar-custom.txt'),
5142 Path(installpath, 'usr/share/foo-custom.h'),
5143 Path(installpath, 'usr/share/out1-custom.txt'),
5144 Path(installpath, 'usr/share/out2-custom.txt'),
5145 Path(installpath, 'usr/share/out3-custom.txt'),
5146 Path(installpath, 'usr/share/custom_files'),
5147 Path(installpath, 'usr/share/custom_files/data.txt'),
5148 Path(installpath, 'usr/share/excludes'),
5149 Path(installpath, 'usr/share/excludes/installed.txt'),
5150 Path(installpath, 'usr/lib'),
5151 Path(installpath, 'usr/lib/libbothcustom.a'),
5152 Path(installpath, 'usr/' + shared_lib_name('bothcustom')),
5153 }
5154
5155 if is_windows() or is_cygwin():
5156 expected_custom |= {Path(installpath, 'usr/bin')}
5157 else:
5158 expected_runtime |= {Path(installpath, 'usr/lib')}
5159
5160 expected_runtime_custom = expected_runtime | expected_custom
5161
5162 expected_all = expected_devel | expected_runtime | expected_custom | {
5163 Path(installpath, 'usr/share/foo-notag.h'),
5164 Path(installpath, 'usr/share/bar-notag.txt'),
5165 Path(installpath, 'usr/share/out1-notag.txt'),
5166 Path(installpath, 'usr/share/out2-notag.txt'),
5167 Path(installpath, 'usr/share/out3-notag.txt'),
5168 Path(installpath, 'usr/share/foo2.h'),
5169 Path(installpath, 'usr/share/out1.txt'),
5170 Path(installpath, 'usr/share/out2.txt'),
5171 Path(installpath, 'usr/share/subproject'),
5172 Path(installpath, 'usr/share/subproject/aaa.txt'),
5173 Path(installpath, 'usr/share/subproject/bbb.txt'),
5174 }
5175
5176 def do_install(tags, expected_files, expected_scripts):
5177 cmd = self.meson_command + ['install', '--dry-run', '--destdir', self.installdir]
5178 cmd += ['--tags', tags] if tags else []
5179 stdout = self._run(cmd, workdir=self.builddir)
5180 installed = self.read_install_logs()
5181 self.assertEqual(sorted(expected_files), sorted(installed))
5182 self.assertEqual(expected_scripts, stdout.count('Running custom install script'))
5183
5184 do_install('devel', expected_devel, 0)
5185 do_install('runtime', expected_runtime, 0)
5186 do_install('custom', expected_custom, 1)
5187 do_install('runtime,custom', expected_runtime_custom, 1)
5188 do_install(None, expected_all, 2)
5189
5190
5191 def test_install_script_dry_run(self):
5192 testdir = os.path.join(self.common_test_dir, '53 install script')
5193 self.init(testdir)
5194 self.build()
5195
5196 cmd = self.meson_command + ['install', '--dry-run', '--destdir', self.installdir]
5197 outputs = self._run(cmd, workdir=self.builddir)
5198
5199 installpath = Path(self.installdir)
5200 self.assertFalse((installpath / 'usr/diiba/daaba/file.dat').exists())
5201 self.assertIn("DRYRUN: Writing file file.dat", outputs)
5202
5203
5204 def test_introspect_install_plan(self):
5205 testdir = os.path.join(self.unit_test_dir, '98 install all targets')
5206 introfile = os.path.join(self.builddir, 'meson-info', 'intro-install_plan.json')
5207 self.init(testdir)
5208 self.assertPathExists(introfile)
5209 with open(introfile, encoding='utf-8') as fp:
5210 res = json.load(fp)
5211
5212 env = get_fake_env(testdir, self.builddir, self.prefix)
5213
5214 def output_name(name, type_):
5215 target = type_(name=name, subdir='',
5216 orig_for_machine=MachineChoice.HOST, sources=[],
5217 structured_sources=None,
5218 objects=[], environment=env, compilers=env.coredata.compilers[MachineChoice.HOST],
5219 build_project=BuildProject('', '', SubProject(''), MachineChoice.HOST, MachineChoice.HOST),
5220 kwargs={'native': MachineChoice.HOST})
5221 target.process_compilers_late()
5222 return target.filename
5223
5224 shared_lib_name = lambda name: output_name(name, SharedLibrary)
5225 static_lib_name = lambda name: output_name(name, StaticLibrary)
5226 exe_name = lambda name: output_name(name, Executable)
5227
5228 expected = {
5229 'targets': {
5230 f'{self.builddir}/out1-notag.txt': {
5231 'build_rpaths': [],
5232 'destination': '{datadir}/out1-notag.txt',
5233 'install_rpath': None,
5234 'tag': None,
5235 'subproject': None,
5236 },
5237 f'{self.builddir}/out2-notag.txt': {
5238 'build_rpaths': [],
5239 'destination': '{datadir}/out2-notag.txt',
5240 'install_rpath': None,
5241 'tag': None,
5242 'subproject': None,
5243 },
5244 f'{self.builddir}/libstatic.a': {
5245 'build_rpaths': [],
5246 'destination': '{libdir_static}/libstatic.a',
5247 'install_rpath': None,
5248 'tag': 'devel',
5249 'subproject': None,
5250 },
5251 f'{self.builddir}/' + exe_name('app'): {
5252 'build_rpaths': [],
5253 'destination': '{bindir}/' + exe_name('app'),
5254 'install_rpath': None,
5255 'tag': 'runtime',
5256 'subproject': None,
5257 },
5258 f'{self.builddir}/' + exe_name('app-otherdir'): {
5259 'build_rpaths': [],
5260 'destination': '{prefix}/otherbin/' + exe_name('app-otherdir'),
5261 'install_rpath': None,
5262 'tag': 'runtime',
5263 'subproject': None,
5264 },
5265 f'{self.builddir}/subdir/' + exe_name('app2'): {
5266 'build_rpaths': [],
5267 'destination': '{bindir}/' + exe_name('app2'),
5268 'install_rpath': None,
5269 'tag': 'runtime',
5270 'subproject': None,
5271 },
5272 f'{self.builddir}/' + shared_lib_name('shared'): {
5273 'build_rpaths': [],
5274 'destination': '{libdir_shared}/' + shared_lib_name('shared'),
5275 'install_rpath': None,
5276 'tag': 'runtime',
5277 'subproject': None,
5278 },
5279 f'{self.builddir}/' + shared_lib_name('both'): {
5280 'build_rpaths': [],
5281 'destination': '{libdir_shared}/' + shared_lib_name('both'),
5282 'install_rpath': None,
5283 'tag': 'runtime',
5284 'subproject': None,
5285 },
5286 f'{self.builddir}/' + static_lib_name('both'): {
5287 'build_rpaths': [],
5288 'destination': '{libdir_static}/' + static_lib_name('both'),
5289 'install_rpath': None,
5290 'tag': 'devel',
5291 'subproject': None,
5292 },
5293 f'{self.builddir}/' + shared_lib_name('bothcustom'): {
5294 'build_rpaths': [],
5295 'destination': '{libdir_shared}/' + shared_lib_name('bothcustom'),
5296 'install_rpath': None,
5297 'tag': 'custom',
5298 'subproject': None,
5299 },
5300 f'{self.builddir}/' + static_lib_name('bothcustom'): {
5301 'build_rpaths': [],
5302 'destination': '{libdir_static}/' + static_lib_name('bothcustom'),
5303 'install_rpath': None,
5304 'tag': 'custom',
5305 'subproject': None,
5306 },
5307 f'{self.builddir}/subdir/' + shared_lib_name('both2'): {
5308 'build_rpaths': [],
5309 'destination': '{libdir_shared}/' + shared_lib_name('both2'),
5310 'install_rpath': None,
5311 'tag': 'runtime',
5312 'subproject': None,
5313 },
5314 f'{self.builddir}/subdir/' + static_lib_name('both2'): {
5315 'build_rpaths': [],
5316 'destination': '{libdir_static}/' + static_lib_name('both2'),
5317 'install_rpath': None,
5318 'tag': 'devel',
5319 'subproject': None,
5320 },
5321 f'{self.builddir}/out1-custom.txt': {
5322 'build_rpaths': [],
5323 'destination': '{datadir}/out1-custom.txt',
5324 'install_rpath': None,
5325 'tag': 'custom',
5326 'subproject': None,
5327 },
5328 f'{self.builddir}/out2-custom.txt': {
5329 'build_rpaths': [],
5330 'destination': '{datadir}/out2-custom.txt',
5331 'install_rpath': None,
5332 'tag': 'custom',
5333 'subproject': None,
5334 },
5335 f'{self.builddir}/out3-custom.txt': {
5336 'build_rpaths': [],
5337 'destination': '{datadir}/out3-custom.txt',
5338 'install_rpath': None,
5339 'tag': 'custom',
5340 'subproject': None,
5341 },
5342 f'{self.builddir}/subdir/out1.txt': {
5343 'build_rpaths': [],
5344 'destination': '{datadir}/out1.txt',
5345 'install_rpath': None,
5346 'tag': None,
5347 'subproject': None,
5348 },
5349 f'{self.builddir}/subdir/out2.txt': {
5350 'build_rpaths': [],
5351 'destination': '{datadir}/out2.txt',
5352 'install_rpath': None,
5353 'tag': None,
5354 'subproject': None,
5355 },
5356 f'{self.builddir}/out-devel.h': {
5357 'build_rpaths': [],
5358 'destination': '{includedir}/out-devel.h',
5359 'install_rpath': None,
5360 'tag': 'devel',
5361 'subproject': None,
5362 },
5363 f'{self.builddir}/out3-notag.txt': {
5364 'build_rpaths': [],
5365 'destination': '{datadir}/out3-notag.txt',
5366 'install_rpath': None,
5367 'tag': None,
5368 'subproject': None,
5369 },
5370 },
5371 'configure': {
5372 f'{self.builddir}/foo-notag.h': {
5373 'destination': '{datadir}/foo-notag.h',
5374 'tag': None,
5375 'subproject': None,
5376 },
5377 f'{self.builddir}/foo2-devel.h': {
5378 'destination': '{includedir}/foo2-devel.h',
5379 'tag': 'devel',
5380 'subproject': None,
5381 },
5382 f'{self.builddir}/foo-custom.h': {
5383 'destination': '{datadir}/foo-custom.h',
5384 'tag': 'custom',
5385 'subproject': None,
5386 },
5387 f'{self.builddir}/subdir/foo2.h': {
5388 'destination': '{datadir}/foo2.h',
5389 'tag': None,
5390 'subproject': None,
5391 },
5392 },
5393 'data': {
5394 f'{testdir}/bar-notag.txt': {
5395 'destination': '{datadir}/bar-notag.txt',
5396 'tag': None,
5397 'subproject': None,
5398 },
5399 f'{testdir}/bar-devel.h': {
5400 'destination': '{includedir}/bar-devel.h',
5401 'tag': 'devel',
5402 'subproject': None,
5403 },
5404 f'{testdir}/bar-custom.txt': {
5405 'destination': '{datadir}/bar-custom.txt',
5406 'tag': 'custom',
5407 'subproject': None,
5408 },
5409 f'{testdir}/subdir/bar2-devel.h': {
5410 'destination': '{includedir}/bar2-devel.h',
5411 'tag': 'devel',
5412 'subproject': None,
5413 },
5414 f'{testdir}/subprojects/subproject/aaa.txt': {
5415 'destination': '{datadir}/subproject/aaa.txt',
5416 'tag': None,
5417 'subproject': 'subproject',
5418 },
5419 f'{testdir}/subprojects/subproject/bbb.txt': {
5420 'destination': '{datadir}/subproject/bbb.txt',
5421 'tag': 'data',
5422 'subproject': 'subproject',
5423 },
5424 },
5425 'headers': {
5426 f'{testdir}/foo1-devel.h': {
5427 'destination': '{includedir}/foo1-devel.h',
5428 'tag': 'devel',
5429 'subproject': None,
5430 },
5431 f'{testdir}/subdir/foo3-devel.h': {
5432 'destination': '{includedir}/foo3-devel.h',
5433 'tag': 'devel',
5434 'subproject': None,
5435 },
5436 },
5437 'install_subdirs': {
5438 f'{testdir}/custom_files': {
5439 'destination': '{datadir}/custom_files',
5440 'tag': 'custom',
5441 'subproject': None,
5442 'exclude_dirs': [],
5443 'exclude_files': [],
5444 },
5445 f'{testdir}/excludes': {
5446 'destination': '{datadir}/excludes',
5447 'tag': 'custom',
5448 'subproject': None,
5449 'exclude_dirs': ['excluded'],
5450 'exclude_files': ['excluded.txt'],
5451 }
5452 }
5453 }
5454
5455 fix_path = lambda path: os.path.sep.join(path.split('/'))
5456 expected_fixed = {
5457 data_type: {
5458 fix_path(source): {
5459 key: fix_path(value) if key == 'destination' else value
5460 for key, value in attributes.items()
5461 }
5462 for source, attributes in files.items()
5463 }
5464 for data_type, files in expected.items()
5465 }
5466
5467 for data_type, files in expected_fixed.items():
5468 for file, details in files.items():
5469 with self.subTest(key='{}.{}'.format(data_type, file)):
5470 self.assertEqual(res[data_type][file], details)
5471
5472 @skip_if_not_language('rust')
5473 @skipIfNoExecutable('rustdoc')
5474 def test_rustdoc(self) -> None:
5475 if self.backend is not Backend.ninja:
5476 raise unittest.SkipTest('Rust is only supported with ninja currently')
5477 try:
5478 with tempfile.TemporaryDirectory() as tmpdir:
5479 testdir = os.path.join(tmpdir, 'a')
5480 shutil.copytree(os.path.join(self.rust_test_dir, '9 unit tests'),
5481 testdir)
5482 self.init(testdir)
5483 self.build('rustdoc')
5484 except PermissionError:
5485 # When run under Windows CI, something (virus scanner?)
5486 # holds on to the git files so cleaning up the dir
5487 # fails sometimes.
5488 pass
5489
5490 @skip_if_not_language('rust')
5491 @skipIfNoExecutable('clippy-driver')
5492 def test_rust_clippy(self) -> None:
5493 if self.backend is not Backend.ninja:
5494 raise unittest.SkipTest('Rust is only supported with ninja currently')
5495 # When clippy is used, we should get an exception since a variable named
5496 # "foo" is used, but is on our denylist
5497 testdir = os.path.join(self.rust_test_dir, '1 basic')
5498 self.init(testdir)
5499 self.build('clippy')
5500
5501 self.wipe()
5502 self.init(testdir, extra_args=['--werror', '-Db_colorout=never'])
5503 with self.assertRaises(subprocess.CalledProcessError) as cm:
5504 self.build('clippy')
5505 self.assertTrue('error: use of a blacklisted/placeholder name `foo`' in cm.exception.stdout or
5506 'error: use of a disallowed/placeholder name `foo`' in cm.exception.stdout)
5507
5508 @skip_if_not_language('rust')
5509 @skipIfNoExecutable('clippy-driver')
5510 def test_rust_clippy_as_rustc(self) -> None:
5511 if self.backend is not Backend.ninja:
5512 raise unittest.SkipTest('Rust is only supported with ninja currently')
5513 # When clippy is used, we should get an exception since a variable named
5514 # "foo" is used, but is on our denylist
5515 testdir = os.path.join(self.rust_test_dir, '1 basic')
5516 self.init(testdir, extra_args=['--werror'], override_envvars={'RUSTC': 'clippy-driver'})
5517 with self.assertRaises(subprocess.CalledProcessError) as cm:
5518 self.build()
5519 self.assertTrue('error: use of a blacklisted/placeholder name `foo`' in cm.exception.stdout or
5520 'error: use of a disallowed/placeholder name `foo`' in cm.exception.stdout)
5521
5522 @skip_if_not_language('rust')
5523 def test_rust_test_warnings(self) -> None:
5524 if self.backend is not Backend.ninja:
5525 raise unittest.SkipTest('Rust is only supported with ninja currently')
5526 testdir = os.path.join(self.rust_test_dir, '9 unit tests')
5527 self.init(testdir, extra_args=['--fatal-meson-warnings'])
5528
5529 @skip_if_not_language('rust')
5530 def test_rust_rlib_linkage(self) -> None:
5531 if self.backend is not Backend.ninja:
5532 raise unittest.SkipTest('Rust is only supported with ninja currently')
5533 template = textwrap.dedent('''\
5534 use std::process::exit;
5535
5536 pub fn fun() {{
5537 exit({});
5538 }}
5539 ''')
5540
5541 testdir = os.path.join(self.unit_test_dir, '101 rlib linkage')
5542 gen_file = os.path.join(testdir, 'lib.rs')
5543 with open(gen_file, 'w', encoding='utf-8') as f:
5544 f.write(template.format(0))
5545 self.addCleanup(windows_proof_rm, gen_file)
5546
5547 self.init(testdir)
5548 self.build()
5549 self.run_tests()
5550
5551 with open(gen_file, 'w', encoding='utf-8') as f:
5552 f.write(template.format(39))
5553
5554 self.build()
5555 with self.assertRaises(subprocess.CalledProcessError) as cm:
5556 self.run_tests()
5557 self.assertEqual(cm.exception.returncode, 1)
5558 self.assertIn('exit status 39', cm.exception.stdout)
5559
5560 @skip_if_not_language('rust')
5561 def test_bindgen_drops_invalid(self) -> None:
5562 if self.backend is not Backend.ninja:
5563 raise unittest.SkipTest('Rust is only supported with ninja currently')
5564 testdir = os.path.join(self.rust_test_dir, '12 bindgen')
5565 env = get_fake_env(testdir, self.builddir, self.prefix)
5566 cc = detect_c_compiler(env, MachineChoice.HOST)
5567 # bindgen understands compiler args that clang understands, but not
5568 # flags by other compilers
5569 if cc.get_id() == 'gcc':
5570 bad_arg = '-fdse'
5571 elif cc.get_id() == 'msvc':
5572 bad_arg = '/fastfail'
5573 else:
5574 raise unittest.SkipTest('Test only supports GCC and MSVC')
5575 self.init(testdir, extra_args=[f"-Dc_args=['-DCMD_ARG', '{bad_arg}']"])
5576 intro = self.introspect(['--targets'])
5577 for i in intro:
5578 if i['type'] == 'custom' and i['id'].startswith('rustmod-bindgen'):
5579 args = i['target_sources'][0]['compiler']
5580 self.assertIn('-DCMD_ARG', args)
5581 self.assertIn('-DPROJECT_ARG', args)
5582 self.assertIn('-DGLOBAL_ARG', args)
5583 self.assertNotIn(bad_arg, args)
5584 self.assertNotIn('-mtls-dialect=gnu2', args)
5585 self.assertNotIn('/fp:fast', args)
5586 return
5587
5588 def test_custom_target_name(self):
5589 testdir = os.path.join(self.unit_test_dir, '99 custom target name')
5590 self.init(testdir)
5591 out = self.build()
5592 if self.backend is Backend.ninja:
5593 self.assertIn('Generating file.txt with a custom command', out)
5594 self.assertIn('Generating subdir/file.txt with a custom command', out)
5595
5596 def test_symlinked_subproject(self):
5597 testdir = os.path.join(self.unit_test_dir, '107 subproject symlink')
5598 subproject_dir = os.path.join(testdir, 'subprojects')
5599 subproject = os.path.join(testdir, 'symlinked_subproject')
5600 symlinked_subproject = os.path.join(testdir, 'subprojects', 'symlinked_subproject')
5601 if not os.path.exists(subproject_dir):
5602 os.mkdir(subproject_dir)
5603 try:
5604 os.symlink(subproject, symlinked_subproject)
5605 except OSError:
5606 raise SkipTest("Symlinks are not available on this machine")
5607 self.addCleanup(os.remove, symlinked_subproject)
5608
5609 self.init(testdir)
5610 self.build()
5611
5612 def test_configure_same_noop(self):
5613 testdir = os.path.join(self.unit_test_dir, '109 configure same noop')
5614 args = [
5615 '-Dstring=val',
5616 '-Dboolean=true',
5617 '-Dcombo=two',
5618 '-Dinteger=7',
5619 '-Darray=[\'three\']',
5620 '-Dfeature=disabled',
5621 '--buildtype=plain',
5622 '--prefix=/abc',
5623 ]
5624 self.init(testdir, extra_args=args)
5625
5626 filename = Path(self.privatedir) / 'coredata.dat'
5627
5628 olddata = filename.read_bytes()
5629 oldmtime = os.path.getmtime(filename)
5630
5631 for opt in ('-Dstring=val', '--buildtype=plain', '-Dfeature=disabled', '-Dprefix=/abc'):
5632 self.setconf([opt])
5633 newdata = filename.read_bytes()
5634 newmtime = os.path.getmtime(filename)
5635 self.assertEqual(oldmtime, newmtime)
5636 self.assertEqual(olddata, newdata)
5637 olddata = newdata
5638 oldmtime = newmtime
5639
5640 for opt in ('-Dstring=abc', '--buildtype=release', '-Dfeature=enabled', '-Dprefix=/def'):
5641 self.setconf([opt])
5642 newdata = filename.read_bytes()
5643 newmtime = os.path.getmtime(filename)
5644 self.assertGreater(newmtime, oldmtime)
5645 self.assertNotEqual(olddata, newdata)
5646 olddata = newdata
5647 oldmtime = newmtime
5648
5649 def test_link_language_promotion(self):
5650 if self.backend is Backend.vs:
5651 raise SkipTest('target introspection is lacking linker details')
5652 testdir = os.path.join(self.unit_test_dir, '134 promote link_language')
5653 self.init(testdir)
5654 cintrospection = self.introspect('--compilers')
5655 clinker = cintrospection['host']['c']['linker_exelist']
5656
5657 tintrospection = self.introspect('--targets')
5658 consumer = next(t for t in tintrospection if t['name'] == 'consumer')
5659 linker_src = next(s for s in consumer['target_sources'] if 'linker' in s)
5660
5661 self.assertEqual(clinker, linker_src['linker'])
5662
5663 def __test_multi_stds(self, test_c: bool = True, test_objc: bool = False) -> None:
5664 assert test_c or test_objc, 'must test something'
5665 testdir = os.path.join(self.unit_test_dir, '115 c cpp stds')
5666 self.init(testdir, extra_args=[f'-Dwith-c={str(test_c).lower()}',
5667 f'-Dwith-objc={str(test_objc).lower()}'])
5668 # Invalid values should fail whatever compiler we have
5669 with self.assertRaises(subprocess.CalledProcessError):
5670 self.setconf('-Dc_std=invalid')
5671 with self.assertRaises(subprocess.CalledProcessError):
5672 self.setconf('-Dc_std=c89,invalid')
5673 with self.assertRaises(subprocess.CalledProcessError):
5674 self.setconf('-Dc_std=c++11')
5675 env = get_fake_env()
5676 if test_c:
5677 cc = detect_c_compiler(env, MachineChoice.HOST)
5678 if test_objc:
5679 objc = detect_compiler_for(env, 'objc', MachineChoice.HOST, True, '')
5680 assert objc is not None
5681 if test_c and cc.get_argument_syntax() != objc.get_argument_syntax():
5682 # The test doesn't work correctly in this case because we can
5683 # end up with incompatible stds, like gnu89 with cl.exe for C
5684 # and clang.exe for ObjC
5685 return
5686 if not test_c:
5687 cc = objc
5688
5689 if cc.get_id() in {'msvc', 'clang-cl'}:
5690 # default_option should have selected those
5691 self.assertEqual(self.getconf('c_std'), 'c89')
5692 self.assertEqual(self.getconf('cpp_std'), 'vc++11')
5693 # This is deprecated but works for C
5694 self.setconf('-Dc_std=gnu99')
5695 self.assertEqual(self.getconf('c_std'), 'c99')
5696 # C++ however never accepted that fallback
5697 with self.assertRaises(subprocess.CalledProcessError):
5698 self.setconf('-Dcpp_std=gnu++11')
5699 # The first supported std should be selected
5700 self.setconf('-Dcpp_std=gnu++11,vc++11,c++11')
5701 self.assertEqual(self.getconf('cpp_std'), 'vc++11')
5702 elif cc.get_id() in {'gcc', 'clang'}:
5703 # default_option should have selected those
5704 self.assertEqual(self.getconf('c_std'), 'gnu89')
5705 self.assertEqual(self.getconf('cpp_std'), 'gnu++98')
5706 # The first supported std should be selected
5707 self.setconf('-Dcpp_std=c++11,gnu++11,vc++11')
5708 self.assertEqual(self.getconf('cpp_std'), 'c++11')
5709
5710 def test_c_cpp_stds(self) -> None:
5711 self.__test_multi_stds()
5712
5713 @skip_if_not_language('objc')
5714 @skip_if_not_language('objcpp')
5715 def test_objc_objcpp_stds(self) -> None:
5716 self.__test_multi_stds(test_c=False, test_objc=True)
5717
5718 @skip_if_not_language('objc')
5719 @skip_if_not_language('objcpp')
5720 def test_c_cpp_objc_objcpp_stds(self) -> None:
5721 self.__test_multi_stds(test_objc=True)
5722
5723 def test_slice(self):
5724 testdir = os.path.join(self.unit_test_dir, '128 test slice')
5725 self.init(testdir)
5726 self.build()
5727
5728 for arg, expectation in {'1/1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
5729 '1/2': [1, 3, 5, 7, 9],
5730 '2/2': [2, 4, 6, 8, 10],
5731 '1/10': [1],
5732 '2/10': [2],
5733 '10/10': [10],
5734 }.items():
5735 output = self._run(self.mtest_command + ['--slice=' + arg])
5736 tests = sorted([
5737 int(x) for x in re.findall(r'^[ 0-9]+/[0-9]+ test_slice:test-([0-9]*)', output, flags=re.MULTILINE)
5738 ])
5739 self.assertEqual(tests, expectation)
5740
5741 for arg, expectation in {'': 'error: argument --slice: value does not conform to format \'SLICE/NUM_SLICES\'',
5742 '0': 'error: argument --slice: value does not conform to format \'SLICE/NUM_SLICES\'',
5743 '0/1': 'error: argument --slice: SLICE is not a positive integer',
5744 'a/1': 'error: argument --slice: SLICE is not an integer',
5745 '1/0': 'error: argument --slice: NUM_SLICES is not a positive integer',
5746 '1/a': 'error: argument --slice: NUM_SLICES is not an integer',
5747 '2/1': 'error: argument --slice: SLICE exceeds NUM_SLICES',
5748 '1/11': 'ERROR: number of slices (11) exceeds number of tests (10)',
5749 }.items():
5750 with self.assertRaises(subprocess.CalledProcessError) as cm:
5751 self._run(self.mtest_command + ['--slice=' + arg])
5752 self.assertIn(expectation, cm.exception.output)
5753
5754 def test_rsp_support(self):
5755 env = get_fake_env()
5756 cc = detect_c_compiler(env, MachineChoice.HOST)
5757 has_rsp = cc.linker.id in {
5758 'ld.bfd', 'ld.eld', 'ld.gold', 'ld.lld', 'ld.mold', 'ld.qcld', 'ld.wasm',
5759 'link', 'lld-link', 'mwldarm', 'mwldeppc', 'optlink', 'xilink',
5760 }
5761 self.assertEqual(cc.linker.get_accepts_rsp(), has_rsp)
5762
5763 def test_nonexisting_bargs(self):
5764 testdir = os.path.join(self.unit_test_dir, '116 empty project')
5765 args = ['-Db_ndebug=if_release']
5766 self.init(testdir, extra_args=args)
5767
5768 def test_wipe_with_args(self):
5769 testdir = os.path.join(self.common_test_dir, '1 trivial')
5770 self.init(testdir, extra_args=['-Dc_args=-DSOMETHING'])
5771 self.init(testdir, extra_args=['--wipe'])
5772
5773 def test_interactive_tap(self):
5774 testdir = os.path.join(self.unit_test_dir, '124 interactive tap')
5775 self.init(testdir, extra_args=['--wrap-mode=forcefallback'])
5776 output = self._run(self.mtest_command + ['--interactive'])
5777 self.assertRegex(output, r'Ok:\s*0')
5778 self.assertRegex(output, r'Fail:\s*0')
5779 self.assertRegex(output, r'Ignored:\s*1')
5780
5781 @skip_if_not_language('fortran')
5782 def test_fortran_cross_target_module_dep(self) -> None:
5783 if self.backend is not Backend.ninja:
5784 raise SkipTest('Test is only relavent on the ninja backend')
5785 testdir = os.path.join(self.fortran_test_dir, '8 module names')
5786 self.init(testdir, extra_args=['-Dunittest=true'])
5787
5788 # Find the correct output to compile, regardless of what compiler is being used
5789 comp = self.get_compdb()
5790 entry = first(comp, lambda e: e['file'].endswith('lib.f90'))
5791 assert entry is not None, 'for mypy'
5792 output = entry['output']
5793
5794 self.build(output, extra_args=['-j1'])
5795
5796 @skip_if_not_language('fortran')
5797 def test_fortran_new_module_in_dep(self) -> None:
5798 if self.backend is not Backend.ninja:
5799 raise SkipTest('Test is only relavent on the ninja backend')
5800 testdir = self.copy_srcdir(os.path.join(self.fortran_test_dir, '8 module names'))
5801 self.init(testdir, extra_args=['-Dunittest=true'])
5802 self.build()
5803
5804 with open(os.path.join(testdir, 'mod1.f90'), 'a', encoding='utf-8') as f:
5805 f.write(textwrap.dedent("""\
5806 module MyMod3
5807 implicit none
5808
5809 integer, parameter :: myModVal3 =1
5810
5811 end module MyMod3
5812 """))
5813
5814 with open(os.path.join(testdir, 'test.f90'), 'w', encoding='utf-8') as f:
5815 f.write(textwrap.dedent("""\
5816 program main
5817 use MyMod2
5818 use MyMod3
5819 implicit none
5820
5821 call showvalues()
5822 print*, "MyModValu3 = ", myModVal3
5823
5824 end program
5825 """))
5826
5827 # Find the correct output to compile, regardless of what compiler is being used
5828 comp = self.get_compdb()
5829 entry = first(comp, lambda e: e['file'].endswith('lib.f90'))
5830 assert entry is not None, 'for mypy'
5831 output = entry['output']
5832
5833 self.build(output, extra_args=['-j1'])
5834
5835 def test_run_command_output(self):
5836 '''
5837 Test that run_command will output to stdout/stderr if `check: false`.
5838 '''
5839 testdir = os.path.join(self.common_test_dir, '33 run program')
5840
5841 # inprocess=False uses BasePlatformTests::_run, which by default
5842 # redirects all stderr to stdout, so we look for the expected stderr
5843 # in the merged stdout.
5844 # inprocess=True captures stderr and stdout separately, but doesn't
5845 # return stderr (only printing it on failure) so unless we change the
5846 # function signature we can't get at the stderr output
5847 out = self.init(testdir, inprocess=False)
5848 # No output at all
5849 self.assertTrue('stdout|capture:false,console:false' not in out)
5850 self.assertTrue('stderr|capture:false,console:false' not in out)
5851 # Output not captured, but printed
5852 self.assertTrue('stdout|capture:false,console:true' in out)
5853 self.assertTrue('stderr|capture:false,console:true' in out)
5854 # Output captured, but not printed
5855 self.assertTrue('stdout|capture:true,console:false' not in out)
5856 self.assertTrue('stderr|capture:true,console:false' not in out)
5857 # Output captured and printed
5858 self.assertTrue('stdout|capture:true,console:true' in out)
5859 self.assertTrue('stderr|capture:true,console:true' in out)