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 def create_dummy_subproject(self, project_dir, name):
1659 path = os.path.join(project_dir, 'subprojects', name)
1660 os.makedirs(path)
1661 with open(os.path.join(path, 'meson.build'), 'w', encoding='utf-8') as ofile:
1662 ofile.write(f"project('{name}', version: '1.0')")
1663 return path
1664
1665 def dist_impl(self, vcs_init, vcs_add_all=None, include_subprojects=True):
1666 # Create this on the fly because having rogue .git directories inside
1667 # the source tree leads to all kinds of trouble.
1668 with tempfile.TemporaryDirectory() as project_dir:
1669 with open(os.path.join(project_dir, 'meson.build'), 'w', encoding='utf-8') as ofile:
1670 ofile.write(textwrap.dedent('''\
1671 project('disttest', 'c', version : '1.4.3')
1672 e = executable('distexe', 'distexe.c')
1673 test('dist test', e)
1674 subproject('vcssub', required : false)
1675 subproject('tarballsub', required : false)
1676 subproject('samerepo', required : false)
1677 '''))
1678 distexe_c = os.path.join(project_dir, 'distexe.c')
1679 with open(distexe_c, 'w', encoding='utf-8') as ofile:
1680 ofile.write(textwrap.dedent('''\
1681 #include<stdio.h>
1682
1683 int main(int argc, char **argv) {
1684 printf("I am a distribution test.\\n");
1685 return 0;
1686 }
1687 '''))
1688 xz_distfile = os.path.join(self.distdir, 'disttest-1.4.3.tar.xz')
1689 xz_checksumfile = xz_distfile + '.sha256sum'
1690 bz_distfile = os.path.join(self.distdir, 'disttest-1.4.3.tar.bz2')
1691 bz_checksumfile = bz_distfile + '.sha256sum'
1692 gz_distfile = os.path.join(self.distdir, 'disttest-1.4.3.tar.gz')
1693 gz_checksumfile = gz_distfile + '.sha256sum'
1694 zip_distfile = os.path.join(self.distdir, 'disttest-1.4.3.zip')
1695 zip_checksumfile = zip_distfile + '.sha256sum'
1696 vcs_init(project_dir)
1697 if include_subprojects:
1698 vcs_init(self.create_dummy_subproject(project_dir, 'vcssub'))
1699 self.create_dummy_subproject(project_dir, 'tarballsub')
1700 self.create_dummy_subproject(project_dir, 'unusedsub')
1701 if vcs_add_all:
1702 vcs_add_all(self.create_dummy_subproject(project_dir, 'samerepo'))
1703 self.init(project_dir)
1704 self.build('dist')
1705 self.assertPathExists(xz_distfile)
1706 self.assertPathExists(xz_checksumfile)
1707 self.assertPathDoesNotExist(bz_distfile)
1708 self.assertPathDoesNotExist(bz_checksumfile)
1709 self.assertPathDoesNotExist(gz_distfile)
1710 self.assertPathDoesNotExist(gz_checksumfile)
1711 self.assertPathDoesNotExist(zip_distfile)
1712 self.assertPathDoesNotExist(zip_checksumfile)
1713 # update a source file timestamp; dist should succeed anyway
1714 os.utime(distexe_c)
1715 self._run(self.meson_command + ['dist', '--formats', 'bztar'],
1716 workdir=self.builddir)
1717 self.assertPathExists(bz_distfile)
1718 self.assertPathExists(bz_checksumfile)
1719 self._run(self.meson_command + ['dist', '--formats', 'gztar'],
1720 workdir=self.builddir)
1721 self.assertPathExists(gz_distfile)
1722 self.assertPathExists(gz_checksumfile)
1723 self._run(self.meson_command + ['dist', '--formats', 'zip'],
1724 workdir=self.builddir)
1725 self.assertPathExists(zip_distfile)
1726 self.assertPathExists(zip_checksumfile)
1727 os.remove(xz_distfile)
1728 os.remove(xz_checksumfile)
1729 os.remove(bz_distfile)
1730 os.remove(bz_checksumfile)
1731 os.remove(gz_distfile)
1732 os.remove(gz_checksumfile)
1733 os.remove(zip_distfile)
1734 os.remove(zip_checksumfile)
1735 self._run(self.meson_command + ['dist', '--formats', 'xztar,bztar,gztar,zip'],
1736 workdir=self.builddir)
1737 self.assertPathExists(xz_distfile)
1738 self.assertPathExists(xz_checksumfile)
1739 self.assertPathExists(bz_distfile)
1740 self.assertPathExists(bz_checksumfile)
1741 self.assertPathExists(gz_distfile)
1742 self.assertPathExists(gz_checksumfile)
1743 self.assertPathExists(zip_distfile)
1744 self.assertPathExists(zip_checksumfile)
1745
1746 if include_subprojects:
1747 # Verify that without --include-subprojects we have files from
1748 # the main project and also files from subprojects part of the
1749 # main vcs repository.
1750 z = zipfile.ZipFile(zip_distfile)
1751 expected = ['disttest-1.4.3/',
1752 'disttest-1.4.3/meson.build',
1753 'disttest-1.4.3/distexe.c']
1754 if vcs_add_all:
1755 expected += ['disttest-1.4.3/subprojects/',
1756 'disttest-1.4.3/subprojects/samerepo/',
1757 'disttest-1.4.3/subprojects/samerepo/meson.build']
1758 self.assertEqual(sorted(expected),
1759 sorted(z.namelist()))
1760 # Verify that with --include-subprojects we now also have files
1761 # from tarball and separate vcs subprojects. But not files from
1762 # unused subprojects.
1763 self._run(self.meson_command + ['dist', '--formats', 'zip', '--include-subprojects'],
1764 workdir=self.builddir)
1765 z = zipfile.ZipFile(zip_distfile)
1766 expected += ['disttest-1.4.3/subprojects/tarballsub/',
1767 'disttest-1.4.3/subprojects/tarballsub/meson.build',
1768 'disttest-1.4.3/subprojects/vcssub/',
1769 'disttest-1.4.3/subprojects/vcssub/meson.build']
1770 self.assertEqual(sorted(expected),
1771 sorted(z.namelist()))
1772 if vcs_add_all:
1773 # Verify we can distribute separately subprojects in the same vcs
1774 # repository as the main project.
1775 subproject_dir = os.path.join(project_dir, 'subprojects', 'samerepo')
1776 self.new_builddir()
1777 self.init(subproject_dir)
1778 self.build('dist')
1779 xz_distfile = os.path.join(self.distdir, 'samerepo-1.0.tar.xz')
1780 xz_checksumfile = xz_distfile + '.sha256sum'
1781 self.assertPathExists(xz_distfile)
1782 self.assertPathExists(xz_checksumfile)
1783 tar = tarfile.open(xz_distfile, "r:xz") # [ignore encoding]
1784 self.assertEqual(sorted(['samerepo-1.0',
1785 'samerepo-1.0/meson.build']),
1786 sorted(i.name for i in tar))
1787
1788 def test_rpath_uses_ORIGIN(self):
1789 '''
1790 Test that built targets use $ORIGIN in rpath, which ensures that they
1791 are relocatable and ensures that builds are reproducible since the
1792 build directory won't get embedded into the built binaries.
1793 '''
1794 if is_windows() or is_cygwin():
1795 raise SkipTest('Windows PE/COFF binaries do not use RPATH')
1796 testdir = os.path.join(self.common_test_dir, '39 library chain')
1797 self.init(testdir)
1798 self.build()
1799 for each in ('prog', 'subdir/liblib1.so', ):
1800 rpath = get_rpath(os.path.join(self.builddir, each))
1801 self.assertTrue(rpath, f'Rpath could not be determined for {each}.')
1802 if is_dragonflybsd():
1803 # DragonFly BSD will prepend /usr/lib/gccVERSION to the rpath,
1804 # so ignore that.
1805 self.assertTrue(rpath.startswith('/usr/lib/gcc'))
1806 rpaths = rpath.split(':')[1:]
1807 else:
1808 rpaths = rpath.split(':')
1809 for path in rpaths:
1810 self.assertTrue(path.startswith('$ORIGIN'), msg=(each, path))
1811 # These two don't link to anything else, so they do not need an rpath entry.
1812 for each in ('subdir/subdir2/liblib2.so', 'subdir/subdir3/liblib3.so'):
1813 rpath = get_rpath(os.path.join(self.builddir, each))
1814 if is_dragonflybsd():
1815 # The rpath should be equal to /usr/lib/gccVERSION
1816 self.assertTrue(rpath.startswith('/usr/lib/gcc'))
1817 self.assertEqual(len(rpath.split(':')), 1)
1818 else:
1819 self.assertIsNone(rpath)
1820
1821 def test_dash_d_dedup(self):
1822 testdir = os.path.join(self.unit_test_dir, '9 d dedup')
1823 self.init(testdir)
1824 cmd = self.get_compdb()[0]['command']
1825 self.assertTrue('-D FOO -D BAR' in cmd or
1826 '"-D" "FOO" "-D" "BAR"' in cmd or
1827 '/D FOO /D BAR' in cmd or
1828 '"/D" "FOO" "/D" "BAR"' in cmd)
1829
1830 def test_all_forbidden_targets_tested(self):
1831 '''
1832 Test that all forbidden targets are tested in the '150 reserved targets'
1833 test. Needs to be a unit test because it accesses Meson internals.
1834 '''
1835 testdir = os.path.join(self.common_test_dir, '150 reserved targets')
1836 targets = set(mesonbuild.coredata.FORBIDDEN_TARGET_NAMES)
1837 # We don't actually define a target with this name
1838 targets.remove('build.ninja')
1839 # Remove this to avoid multiple entries with the same name
1840 # but different case.
1841 targets.remove('PHONY')
1842 for i in targets:
1843 self.assertPathExists(os.path.join(testdir, i))
1844
1845 def detect_prebuild_env(self):
1846 env = get_fake_env()
1847 cc = detect_c_compiler(env, MachineChoice.HOST)
1848 stlinker = detect_static_linker(env, cc)
1849 if is_windows():
1850 object_suffix = 'obj'
1851 shared_suffix = 'dll'
1852 elif is_cygwin():
1853 object_suffix = 'o'
1854 shared_suffix = 'dll'
1855 elif is_osx():
1856 object_suffix = 'o'
1857 shared_suffix = 'dylib'
1858 else:
1859 object_suffix = 'o'
1860 shared_suffix = 'so'
1861 return (cc, stlinker, object_suffix, shared_suffix)
1862
1863 def detect_prebuild_env_versioned(self):
1864 (cc, stlinker, object_suffix, shared_suffix) = self.detect_prebuild_env()
1865 shared_suffixes = [shared_suffix]
1866 if shared_suffix == 'so':
1867 # .so may have version information integrated into the filename
1868 shared_suffixes += ['so.1', 'so.1.2.3', '1.so', '1.so.2.3']
1869 return (cc, stlinker, object_suffix, shared_suffixes)
1870
1871 def pbcompile(self, compiler, source, objectfile, extra_args=None):
1872 cmd = compiler.get_exelist()
1873 extra_args = extra_args or []
1874 if compiler.get_argument_syntax() == 'msvc':
1875 cmd += ['/nologo', '/Fo' + objectfile, '/c', source] + extra_args
1876 else:
1877 cmd += ['-c', source, '-o', objectfile] + extra_args
1878 subprocess.check_call(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
1879
1880 def test_prebuilt_object(self):
1881 (compiler, _, object_suffix, _) = self.detect_prebuild_env()
1882 tdir = os.path.join(self.unit_test_dir, '15 prebuilt object')
1883 source = os.path.join(tdir, 'source.c')
1884 objectfile = os.path.join(tdir, 'prebuilt.' + object_suffix)
1885 self.pbcompile(compiler, source, objectfile)
1886 try:
1887 self.init(tdir)
1888 self.build()
1889 self.run_tests()
1890 finally:
1891 os.unlink(objectfile)
1892
1893 def build_static_lib(self, compiler, linker, source, objectfile, outfile, extra_args=None):
1894 if extra_args is None:
1895 extra_args = []
1896 link_cmd = linker.get_exelist()
1897 link_cmd += linker.get_always_args()
1898 link_cmd += linker.get_std_link_args(get_fake_env(), False)
1899 link_cmd += linker.get_output_args(outfile)
1900 link_cmd += [objectfile]
1901 self.pbcompile(compiler, source, objectfile, extra_args=extra_args)
1902 try:
1903 subprocess.check_call(link_cmd)
1904 finally:
1905 os.unlink(objectfile)
1906
1907 def test_prebuilt_static_lib(self):
1908 (cc, stlinker, object_suffix, _) = self.detect_prebuild_env()
1909 tdir = os.path.join(self.unit_test_dir, '16 prebuilt static')
1910 source = os.path.join(tdir, 'libdir/best.c')
1911 objectfile = os.path.join(tdir, 'libdir/best.' + object_suffix)
1912 stlibfile = os.path.join(tdir, 'libdir/libbest.a')
1913 self.build_static_lib(cc, stlinker, source, objectfile, stlibfile)
1914 # Run the test
1915 try:
1916 self.init(tdir)
1917 self.build()
1918 self.run_tests()
1919 finally:
1920 os.unlink(stlibfile)
1921
1922 def build_shared_lib(self, compiler, source, objectfile, outfile, impfile, extra_args=None):
1923 if extra_args is None:
1924 extra_args = []
1925 if compiler.get_argument_syntax() == 'msvc':
1926 link_cmd = compiler.get_linker_exelist() + [
1927 '/NOLOGO', '/DLL', '/DEBUG', '/IMPLIB:' + impfile,
1928 '/OUT:' + outfile, objectfile]
1929 else:
1930 if not (compiler.info.is_windows() or compiler.info.is_cygwin() or compiler.info.is_darwin()):
1931 extra_args += ['-fPIC']
1932 link_cmd = compiler.get_exelist() + ['-shared', '-o', outfile, objectfile]
1933 if not is_osx():
1934 link_cmd += ['-Wl,-soname=' + os.path.basename(outfile)]
1935 self.pbcompile(compiler, source, objectfile, extra_args=extra_args)
1936 try:
1937 subprocess.check_call(link_cmd)
1938 finally:
1939 os.unlink(objectfile)
1940
1941 def test_prebuilt_shared_lib(self):
1942 (cc, _, object_suffix, shared_suffix) = self.detect_prebuild_env()
1943 tdir = self.copy_srcdir(os.path.join(self.unit_test_dir, '17 prebuilt shared'))
1944 source = os.path.join(tdir, 'alexandria.c')
1945 objectfile = os.path.join(tdir, 'alexandria.' + object_suffix)
1946 impfile = os.path.join(tdir, 'alexandria.lib')
1947 if cc.get_argument_syntax() == 'msvc':
1948 shlibfile = os.path.join(tdir, 'alexandria.' + shared_suffix)
1949 elif is_cygwin():
1950 shlibfile = os.path.join(tdir, 'cygalexandria.' + shared_suffix)
1951 else:
1952 shlibfile = os.path.join(tdir, 'libalexandria.' + shared_suffix)
1953 self.build_shared_lib(cc, source, objectfile, shlibfile, impfile)
1954
1955 if is_windows():
1956 def cleanup() -> None:
1957 """Clean up all the garbage MSVC writes in the source tree."""
1958
1959 for fname in glob(os.path.join(tdir, 'alexandria.*')):
1960 if os.path.splitext(fname)[1] not in {'.c', '.h'}:
1961 os.unlink(fname)
1962 self.addCleanup(cleanup)
1963 else:
1964 self.addCleanup(os.unlink, shlibfile)
1965
1966 # Run the test
1967 self.init(tdir)
1968 self.build()
1969 self.run_tests()
1970
1971 def test_prebuilt_shared_lib_rpath(self) -> None:
1972 (cc, _, object_suffix, shared_suffix) = self.detect_prebuild_env()
1973 tdir = os.path.join(self.unit_test_dir, '17 prebuilt shared')
1974 with tempfile.TemporaryDirectory() as d:
1975 source = os.path.join(tdir, 'alexandria.c')
1976 objectfile = os.path.join(d, 'alexandria.' + object_suffix)
1977 impfile = os.path.join(d, 'alexandria.lib')
1978 if cc.get_argument_syntax() == 'msvc':
1979 shlibfile = os.path.join(d, 'alexandria.' + shared_suffix)
1980 elif is_cygwin():
1981 shlibfile = os.path.join(d, 'cygalexandria.' + shared_suffix)
1982 else:
1983 shlibfile = os.path.join(d, 'libalexandria.' + shared_suffix)
1984 # Ensure MSVC extra files end up in the directory that gets deleted
1985 # at the end
1986 with chdir(d):
1987 self.build_shared_lib(cc, source, objectfile, shlibfile, impfile)
1988
1989 # Run the test
1990 self.init(tdir, extra_args=[f'-Dsearch_dir={d}'])
1991 self.build()
1992 self.run_tests()
1993
1994 @skipIfNoPkgconfig
1995 def test_prebuilt_shared_lib_pkg_config(self) -> None:
1996 (cc, _, object_suffix, shared_suffixes) = self.detect_prebuild_env_versioned()
1997 tdir = os.path.join(self.unit_test_dir, '17 prebuilt shared')
1998 for shared_suffix in shared_suffixes:
1999 with tempfile.TemporaryDirectory() as d:
2000 source = os.path.join(tdir, 'alexandria.c')
2001 objectfile = os.path.join(d, 'alexandria.' + object_suffix)
2002 impfile = os.path.join(d, 'alexandria.lib')
2003 if cc.get_argument_syntax() == 'msvc':
2004 shlibfile = os.path.join(d, 'alexandria.' + shared_suffix)
2005 linkfile = impfile # MSVC links against the *.lib instead of the *.dll
2006 elif is_cygwin():
2007 shlibfile = os.path.join(d, 'cygalexandria.' + shared_suffix)
2008 linkfile = shlibfile
2009 else:
2010 shlibfile = os.path.join(d, 'libalexandria.' + shared_suffix)
2011 linkfile = shlibfile
2012 # Ensure MSVC extra files end up in the directory that gets deleted
2013 # at the end
2014 with chdir(d):
2015 self.build_shared_lib(cc, source, objectfile, shlibfile, impfile)
2016
2017 with open(os.path.join(d, 'alexandria.pc'), 'w',
2018 encoding='utf-8') as f:
2019 f.write(textwrap.dedent('''
2020 Name: alexandria
2021 Description: alexandria
2022 Version: 1.0.0
2023 Libs: {}
2024 ''').format(
2025 Path(linkfile).as_posix().replace(' ', r'\ '),
2026 ))
2027
2028 # Run the test
2029 self.init(tdir, override_envvars={'PKG_CONFIG_PATH': d},
2030 extra_args=['-Dmethod=pkg-config'])
2031 self.build()
2032 self.run_tests()
2033
2034 self.wipe()
2035
2036 @skip_if_no_cmake
2037 def test_prebuilt_shared_lib_cmake(self) -> None:
2038 (cc, _, object_suffix, shared_suffixes) = self.detect_prebuild_env_versioned()
2039 tdir = os.path.join(self.unit_test_dir, '17 prebuilt shared')
2040 for shared_suffix in shared_suffixes:
2041 with tempfile.TemporaryDirectory() as d:
2042 source = os.path.join(tdir, 'alexandria.c')
2043 objectfile = os.path.join(d, 'alexandria.' + object_suffix)
2044 impfile = os.path.join(d, 'alexandria.lib')
2045 if cc.get_argument_syntax() == 'msvc':
2046 shlibfile = os.path.join(d, 'alexandria.' + shared_suffix)
2047 linkfile = impfile # MSVC links against the *.lib instead of the *.dll
2048 elif is_cygwin():
2049 shlibfile = os.path.join(d, 'cygalexandria.' + shared_suffix)
2050 linkfile = shlibfile
2051 else:
2052 shlibfile = os.path.join(d, 'libalexandria.' + shared_suffix)
2053 linkfile = shlibfile
2054 # Ensure MSVC extra files end up in the directory that gets deleted
2055 # at the end
2056 with chdir(d):
2057 self.build_shared_lib(cc, source, objectfile, shlibfile, impfile)
2058
2059 with open(os.path.join(d, 'alexandriaConfig.cmake'), 'w',
2060 encoding='utf-8') as f:
2061 f.write(textwrap.dedent('''
2062 set(alexandria_FOUND ON)
2063 set(alexandria_LIBRARIES "{}")
2064 set(alexandria_INCLUDE_DIRS "{}")
2065 ''').format(
2066 re.sub(r'([\\"])', r'\\\1', linkfile),
2067 re.sub(r'([\\"])', r'\\\1', tdir),
2068 ))
2069
2070 # Run the test
2071 self.init(tdir, override_envvars={'CMAKE_PREFIX_PATH': d},
2072 extra_args=['-Dmethod=cmake'])
2073 self.build()
2074 self.run_tests()
2075
2076 self.wipe()
2077
2078 def test_prebuilt_shared_lib_rpath_same_prefix(self) -> None:
2079 (cc, _, object_suffix, shared_suffix) = self.detect_prebuild_env()
2080 orig_tdir = os.path.join(self.unit_test_dir, '17 prebuilt shared')
2081
2082 # Put the shared library in a location that shares a common prefix with
2083 # the source directory:
2084 #
2085 # .../
2086 # foo-lib/
2087 # libalexandria.so
2088 # foo/
2089 # meson.build
2090 # ...
2091 #
2092 # This allows us to check that the .../foo-lib/libalexandria.so path is
2093 # preserved correctly when meson processes it.
2094 with tempfile.TemporaryDirectory() as d:
2095 libdir = os.path.join(d, 'foo-lib')
2096 os.mkdir(libdir)
2097
2098 source = os.path.join(orig_tdir, 'alexandria.c')
2099 objectfile = os.path.join(libdir, 'alexandria.' + object_suffix)
2100 impfile = os.path.join(libdir, 'alexandria.lib')
2101 if cc.get_argument_syntax() == 'msvc':
2102 shlibfile = os.path.join(libdir, 'alexandria.' + shared_suffix)
2103 elif is_cygwin():
2104 shlibfile = os.path.join(libdir, 'cygalexandria.' + shared_suffix)
2105 else:
2106 shlibfile = os.path.join(libdir, 'libalexandria.' + shared_suffix)
2107 # Ensure MSVC extra files end up in the directory that gets deleted
2108 # at the end
2109 with chdir(libdir):
2110 self.build_shared_lib(cc, source, objectfile, shlibfile, impfile)
2111
2112 tdir = os.path.join(d, 'foo')
2113 shutil.copytree(orig_tdir, tdir)
2114
2115 # Run the test
2116 self.init(tdir, extra_args=[f'-Dsearch_dir={libdir}'])
2117 self.build()
2118 self.run_tests()
2119
2120 def test_underscore_prefix_detection_list(self) -> None:
2121 '''
2122 Test the underscore detection hardcoded lookup list
2123 against what was detected in the binary.
2124 '''
2125 env, cc = get_convincing_fake_env_and_cc(self.builddir, self.prefix)
2126 expected_uscore = cc._symbols_have_underscore_prefix_searchbin()
2127 list_uscore = cc._symbols_have_underscore_prefix_list()
2128 if list_uscore is not None:
2129 self.assertEqual(list_uscore, expected_uscore)
2130 else:
2131 raise SkipTest('No match in underscore prefix list for this platform.')
2132
2133 def test_underscore_prefix_detection_define(self) -> None:
2134 '''
2135 Test the underscore detection based on compiler-defined preprocessor macro
2136 against what was detected in the binary.
2137 '''
2138 env, cc = get_convincing_fake_env_and_cc(self.builddir, self.prefix)
2139 expected_uscore = cc._symbols_have_underscore_prefix_searchbin()
2140 define_uscore = cc._symbols_have_underscore_prefix_define()
2141 if define_uscore is not None:
2142 self.assertEqual(define_uscore, expected_uscore)
2143 else:
2144 raise SkipTest('Did not find the underscore prefix define __USER_LABEL_PREFIX__')
2145
2146 @skipIfNoPkgconfig
2147 def test_pkgconfig_static(self):
2148 '''
2149 Test that the we prefer static libraries when `static: true` is
2150 passed to dependency() with pkg-config. Can't be an ordinary test
2151 because we need to build libs and try to find them from meson.build
2152
2153 Also test that it's not a hard error to have unsatisfiable library deps
2154 since system libraries -lm will never be found statically.
2155 https://github.com/mesonbuild/meson/issues/2785
2156 '''
2157 (cc, stlinker, objext, shext) = self.detect_prebuild_env()
2158 testdir = os.path.join(self.unit_test_dir, '18 pkgconfig static')
2159 source = os.path.join(testdir, 'foo.c')
2160 objectfile = os.path.join(testdir, 'foo.' + objext)
2161 stlibfile = os.path.join(testdir, 'libfoo.a')
2162 impfile = os.path.join(testdir, 'foo.lib')
2163 if cc.get_argument_syntax() == 'msvc':
2164 shlibfile = os.path.join(testdir, 'foo.' + shext)
2165 elif is_cygwin():
2166 shlibfile = os.path.join(testdir, 'cygfoo.' + shext)
2167 else:
2168 shlibfile = os.path.join(testdir, 'libfoo.' + shext)
2169 # Build libs
2170 self.build_static_lib(cc, stlinker, source, objectfile, stlibfile, extra_args=['-DFOO_STATIC'])
2171 self.build_shared_lib(cc, source, objectfile, shlibfile, impfile)
2172 # Run test
2173 try:
2174 self.init(testdir, override_envvars={'PKG_CONFIG_LIBDIR': self.builddir})
2175 self.build()
2176 self.run_tests()
2177 finally:
2178 os.unlink(stlibfile)
2179 os.unlink(shlibfile)
2180 if is_windows():
2181 # Clean up all the garbage MSVC writes in the
2182 # source tree.
2183 for fname in glob(os.path.join(testdir, 'foo.*')):
2184 if os.path.splitext(fname)[1] not in ['.c', '.h', '.in']:
2185 os.unlink(fname)
2186
2187 @skipIfNoPkgconfig
2188 @mock.patch.dict(os.environ)
2189 def test_pkgconfig_gen_escaping(self):
2190 testdir = os.path.join(self.common_test_dir, '44 pkgconfig-gen')
2191 prefix = '/usr/with spaces'
2192 libdir = 'lib'
2193 self.init(testdir, extra_args=['--prefix=' + prefix,
2194 '--libdir=' + libdir])
2195 # Find foo dependency
2196 os.environ['PKG_CONFIG_LIBDIR'] = self.privatedir
2197 env = get_fake_env(testdir, self.builddir, self.prefix)
2198 kwargs = {'required': True, 'silent': True, 'native': MachineChoice.HOST}
2199 foo_dep = PkgConfigDependency('libanswer', env, kwargs)
2200 # Ensure link_args are properly quoted
2201 libdir = PurePath(prefix) / PurePath(libdir)
2202 link_args = ['-L' + libdir.as_posix(), '-lanswer']
2203 self.assertEqual(foo_dep.get_link_args(), link_args)
2204 # Ensure include args are properly quoted
2205 incdir = PurePath(prefix) / PurePath('include')
2206 cargs = ['-I' + incdir.as_posix(), '-DLIBFOO']
2207 # pkg-config and pkgconf does not respect the same order
2208 self.assertEqual(sorted(foo_dep.get_compile_args()), sorted(cargs))
2209
2210 @skipIfNoPkgconfig
2211 def test_pkgconfig_relocatable(self):
2212 '''
2213 Test that it generates relocatable pkgconfig when module
2214 option pkgconfig.relocatable=true.
2215 '''
2216 testdir_rel = os.path.join(self.common_test_dir, '44 pkgconfig-gen')
2217 self.init(testdir_rel, extra_args=['-Dpkgconfig.relocatable=true'])
2218
2219 def check_pcfile(name, *, relocatable, levels=2):
2220 with open(os.path.join(self.privatedir, name), encoding='utf-8') as f:
2221 pcfile = f.read()
2222 # The pkgconfig module always uses posix path regardless of platform
2223 prefix_rel = PurePath('${pcfiledir}', *(['..'] * levels)).as_posix()
2224 (self.assertIn if relocatable else self.assertNotIn)(
2225 f'prefix={prefix_rel}\n',
2226 pcfile)
2227
2228 check_pcfile('libvartest.pc', relocatable=True)
2229 check_pcfile('libvartest2.pc', relocatable=True)
2230
2231 self.wipe()
2232 self.init(testdir_rel, extra_args=['-Dpkgconfig.relocatable=false'])
2233
2234 check_pcfile('libvartest.pc', relocatable=False)
2235 check_pcfile('libvartest2.pc', relocatable=False)
2236
2237 self.wipe()
2238 testdir_abs = os.path.join(self.unit_test_dir, '105 pkgconfig relocatable with absolute path')
2239 self.init(testdir_abs)
2240
2241 check_pcfile('libsimple.pc', relocatable=True, levels=3)
2242
2243 def test_array_option_change(self):
2244 def get_opt():
2245 opts = self.introspect('--buildoptions')
2246 for x in opts:
2247 if x.get('name') == 'list':
2248 return x
2249 raise Exception(opts)
2250
2251 expected = {
2252 'name': 'list',
2253 'description': 'list',
2254 'section': 'user',
2255 'type': 'array',
2256 'value': ['foo', 'bar'],
2257 'choices': ['foo', 'bar', 'oink', 'boink'],
2258 'machine': 'any',
2259 }
2260 tdir = os.path.join(self.unit_test_dir, '19 array option')
2261 self.init(tdir)
2262 original = get_opt()
2263 self.assertDictEqual(original, expected)
2264
2265 expected['value'] = ['oink', 'boink']
2266 self.setconf('-Dlist=oink,boink')
2267 changed = get_opt()
2268 self.assertEqual(changed, expected)
2269
2270 def test_array_option_bad_change(self):
2271 def get_opt():
2272 opts = self.introspect('--buildoptions')
2273 for x in opts:
2274 if x.get('name') == 'list':
2275 return x
2276 raise Exception(opts)
2277
2278 expected = {
2279 'name': 'list',
2280 'description': 'list',
2281 'section': 'user',
2282 'type': 'array',
2283 'value': ['foo', 'bar'],
2284 'choices': ['foo', 'bar', 'oink', 'boink'],
2285 'machine': 'any',
2286 }
2287 tdir = os.path.join(self.unit_test_dir, '19 array option')
2288 self.init(tdir)
2289 original = get_opt()
2290 self.assertDictEqual(original, expected)
2291 with self.assertRaises(subprocess.CalledProcessError):
2292 self.setconf('-Dlist=bad')
2293 changed = get_opt()
2294 self.assertDictEqual(changed, expected)
2295
2296 def test_array_option_empty_equivalents(self):
2297 """Array options treat -Dopt=[] and -Dopt= as equivalent."""
2298 def get_opt():
2299 opts = self.introspect('--buildoptions')
2300 for x in opts:
2301 if x.get('name') == 'list':
2302 return x
2303 raise Exception(opts)
2304
2305 expected = {
2306 'name': 'list',
2307 'description': 'list',
2308 'section': 'user',
2309 'type': 'array',
2310 'value': [],
2311 'choices': ['foo', 'bar', 'oink', 'boink'],
2312 'machine': 'any',
2313 }
2314 tdir = os.path.join(self.unit_test_dir, '19 array option')
2315 self.init(tdir, extra_args='-Dlist=')
2316 original = get_opt()
2317 self.assertDictEqual(original, expected)
2318
2319 def test_executable_names(self):
2320 testdir = os.path.join(self.unit_test_dir, '121 executable suffix')
2321 self.init(testdir)
2322 self.build()
2323 exe1 = os.path.join(self.builddir, 'foo' + exe_suffix)
2324 exe2 = os.path.join(self.builddir, 'foo.bin')
2325 self.assertPathExists(exe1)
2326 self.assertPathExists(exe2)
2327 self.assertNotEqual(exe1, exe2)
2328
2329 # Wipe and run the compile command against the target names
2330 self.init(testdir, extra_args=['--wipe'])
2331 self._run([*self.meson_command, 'compile', '-C', self.builddir, './foo'])
2332 self._run([*self.meson_command, 'compile', '-C', self.builddir, './foo.bin'])
2333 self.assertPathExists(exe1)
2334 self.assertPathExists(exe2)
2335 self.assertNotEqual(exe1, exe2)
2336
2337
2338 def opt_has(self, name, value):
2339 res = self.introspect('--buildoptions')
2340 found = False
2341 for i in res:
2342 if i['name'] == name:
2343 self.assertEqual(i['value'], value)
2344 found = True
2345 break
2346 self.assertTrue(found, "Array option not found in introspect data.")
2347
2348 def test_free_stringarray_setting(self):
2349 testdir = os.path.join(self.common_test_dir, '40 options')
2350 self.init(testdir)
2351 self.opt_has('free_array_opt', [])
2352 self.setconf('-Dfree_array_opt=foo,bar', will_build=False)
2353 self.opt_has('free_array_opt', ['foo', 'bar'])
2354 self.setconf("-Dfree_array_opt=['a,b', 'c,d']", will_build=False)
2355 self.opt_has('free_array_opt', ['a,b', 'c,d'])
2356
2357 # When running under Travis Mac CI, the file updates seem to happen
2358 # too fast so the timestamps do not get properly updated.
2359 # Call this method before file operations in appropriate places
2360 # to make things work.
2361 def mac_ci_delay(self):
2362 if IS_CI and is_osx():
2363 import time
2364 time.sleep(1)
2365
2366 def test_options_with_choices_changing(self) -> None:
2367 """Detect when options like arrays or combos have their choices change."""
2368 testdir = Path(os.path.join(self.unit_test_dir, '83 change option choices'))
2369 options1 = str(testdir / 'meson_options.1.txt')
2370 options2 = str(testdir / 'meson_options.2.txt')
2371
2372 # Test that old options are changed to the new defaults if they are not valid
2373 real_options = str(testdir / 'meson_options.txt')
2374 self.addCleanup(os.unlink, real_options)
2375
2376 shutil.copy(options1, real_options)
2377 self.init(str(testdir))
2378 self.mac_ci_delay()
2379 shutil.copy(options2, real_options)
2380
2381 self.build()
2382 opts = self.introspect('--buildoptions')
2383 for item in opts:
2384 if item['name'] == 'combo':
2385 self.assertEqual(item['value'], 'b')
2386 self.assertEqual(item['choices'], ['b', 'c', 'd'])
2387 elif item['name'] == 'array':
2388 self.assertEqual(item['value'], ['b'])
2389 self.assertEqual(item['choices'], ['b', 'c', 'd'])
2390
2391 self.wipe()
2392 self.mac_ci_delay()
2393
2394 # When the old options are valid they should remain
2395 shutil.copy(options1, real_options)
2396 self.init(str(testdir), extra_args=['-Dcombo=c', '-Darray=b,c'])
2397 self.mac_ci_delay()
2398 shutil.copy(options2, real_options)
2399 self.build()
2400 opts = self.introspect('--buildoptions')
2401 for item in opts:
2402 if item['name'] == 'combo':
2403 self.assertEqual(item['value'], 'c')
2404 self.assertEqual(item['choices'], ['b', 'c', 'd'])
2405 elif item['name'] == 'array':
2406 self.assertEqual(item['value'], ['b', 'c'])
2407 self.assertEqual(item['choices'], ['b', 'c', 'd'])
2408
2409 def test_options_listed_in_build_options(self) -> None:
2410 """Detect when changed options become listed in build options."""
2411 testdir = os.path.join(self.unit_test_dir, '113 list build options')
2412
2413 out = self.init(testdir)
2414 for line in out.splitlines():
2415 if line.startswith('Message: Build options:'):
2416 self.assertNotIn('-Dauto_features=auto', line)
2417 self.assertNotIn('-Doptional=auto', line)
2418
2419 self.wipe()
2420 self.mac_ci_delay()
2421
2422 out = self.init(testdir, extra_args=['-Dauto_features=disabled', '-Doptional=enabled'])
2423 for line in out.splitlines():
2424 if line.startswith('Message: Build options:'):
2425 self.assertIn('-Dauto_features=disabled', line)
2426 self.assertIn('-Doptional=enabled', line)
2427
2428 self.setconf('-Doptional=disabled')
2429 out = self.build()
2430 for line in out.splitlines():
2431 if line.startswith('Message: Build options:'):
2432 self.assertIn('-Dauto_features=disabled', line)
2433 self.assertNotIn('-Doptional=enabled', line)
2434 self.assertIn('-Doptional=disabled', line)
2435
2436 def test_subproject_promotion(self):
2437 testdir = os.path.join(self.unit_test_dir, '12 promote')
2438 workdir = os.path.join(self.builddir, 'work')
2439 shutil.copytree(testdir, workdir)
2440 spdir = os.path.join(workdir, 'subprojects')
2441 s3dir = os.path.join(spdir, 's3')
2442 scommondir = os.path.join(spdir, 'scommon')
2443 self.assertFalse(os.path.isdir(s3dir))
2444 subprocess.check_call(self.wrap_command + ['promote', 's3'],
2445 cwd=workdir,
2446 stdout=subprocess.DEVNULL)
2447 self.assertTrue(os.path.isdir(s3dir))
2448 self.assertFalse(os.path.isdir(scommondir))
2449 self.assertNotEqual(subprocess.call(self.wrap_command + ['promote', 'scommon'],
2450 cwd=workdir,
2451 stderr=subprocess.DEVNULL), 0)
2452 self.assertNotEqual(subprocess.call(self.wrap_command + ['promote', 'invalid/path/to/scommon'],
2453 cwd=workdir,
2454 stderr=subprocess.DEVNULL), 0)
2455 self.assertFalse(os.path.isdir(scommondir))
2456 subprocess.check_call(self.wrap_command + ['promote', 'subprojects/s2/subprojects/scommon'], cwd=workdir)
2457 self.assertTrue(os.path.isdir(scommondir))
2458 promoted_wrap = os.path.join(spdir, 'athing.wrap')
2459 self.assertFalse(os.path.isfile(promoted_wrap))
2460 subprocess.check_call(self.wrap_command + ['promote', 'athing'], cwd=workdir)
2461 self.assertTrue(os.path.isfile(promoted_wrap))
2462 self.new_builddir() # Ensure builddir is not parent or workdir
2463 self.init(workdir)
2464 self.build()
2465
2466 def test_subproject_promotion_wrap(self):
2467 testdir = os.path.join(self.unit_test_dir, '43 promote wrap')
2468 workdir = os.path.join(self.builddir, 'work')
2469 shutil.copytree(testdir, workdir)
2470 spdir = os.path.join(workdir, 'subprojects')
2471
2472 ambiguous_wrap = os.path.join(spdir, 'ambiguous.wrap')
2473 self.assertNotEqual(subprocess.call(self.wrap_command + ['promote', 'ambiguous'],
2474 cwd=workdir,
2475 stderr=subprocess.DEVNULL), 0)
2476 self.assertFalse(os.path.isfile(ambiguous_wrap))
2477 subprocess.check_call(self.wrap_command + ['promote', 'subprojects/s2/subprojects/ambiguous.wrap'], cwd=workdir)
2478 self.assertTrue(os.path.isfile(ambiguous_wrap))
2479
2480 def test_warning_location(self):
2481 tdir = os.path.join(self.unit_test_dir, '22 warning location')
2482 out = self.init(tdir)
2483 for expected in [
2484 r'meson.build:4: WARNING: Keyword argument "link_with" defined multiple times.',
2485 r'sub' + os.path.sep + r'meson.build:3: WARNING: Keyword argument "link_with" defined multiple times.',
2486 r'meson.build:6: WARNING: a warning of some sort',
2487 r'sub' + os.path.sep + r'meson.build:4: WARNING: subdir warning',
2488 r'meson.build:7: WARNING: Module SIMD has no backwards or forwards compatibility and might not exist in future releases.',
2489 r"meson.build:11: WARNING: The variable(s) 'MISSING' in the input file 'conf.in' are not present in the given configuration data.",
2490 ]:
2491 with self.subTest(expected):
2492 self.assertRegex(out, re.escape(expected))
2493
2494 for wd in [
2495 self.src_root,
2496 self.builddir,
2497 os.getcwd(),
2498 ]:
2499 with self.subTest(wd):
2500 self.new_builddir()
2501 out = self.init(tdir, workdir=wd)
2502 expected = os.path.join(relpath(tdir, self.src_root), 'meson.build')
2503 relwd = relpath(self.src_root, wd)
2504 if relwd != '.':
2505 expected = os.path.join(relwd, expected)
2506 expected = '\n' + expected + ':'
2507 self.assertIn(expected, out)
2508
2509 def test_error_location_path(self):
2510 '''Test locations in meson errors contain correct paths'''
2511 # this list contains errors from all the different steps in the
2512 # lexer/parser/interpreter we have tests for.
2513 for (t, f) in [
2514 ('10 out of bounds', 'meson.build'),
2515 ('17 wrong plusassign', 'meson.build'),
2516 ('55 bad option argument', 'meson_options.txt'),
2517 ('93 subdir parse error', os.path.join('subdir', 'meson.build')),
2518 ('94 invalid option file', 'meson_options.txt'),
2519 ]:
2520 tdir = os.path.join(self.src_root, 'test cases', 'failing', t)
2521
2522 for wd in [
2523 self.src_root,
2524 self.builddir,
2525 os.getcwd(),
2526 ]:
2527 try:
2528 self.init(tdir, workdir=wd)
2529 except subprocess.CalledProcessError as e:
2530 expected = os.path.join('test cases', 'failing', t, f)
2531 relwd = relpath(self.src_root, wd)
2532 if relwd != '.':
2533 expected = os.path.join(relwd, expected)
2534 expected = '\n' + expected + ':'
2535 self.assertIn(expected, e.output)
2536 else:
2537 self.fail('configure unexpectedly succeeded')
2538
2539 def test_permitted_method_kwargs(self):
2540 tdir = os.path.join(self.unit_test_dir, '25 non-permitted kwargs')
2541 with self.assertRaises(subprocess.CalledProcessError) as cm:
2542 self.init(tdir)
2543 self.assertIn('ERROR: compiler.has_header_symbol got unknown keyword arguments "prefixxx"', cm.exception.output)
2544
2545 def _template_test_fresh(self, lang: Language, target_type: str, env: Environment, ninja: list[str]) -> None:
2546 if is_windows() and lang == 'fortran' and target_type == 'library':
2547 # non-Gfortran Windows Fortran compilers do not do shared libraries in a Fortran standard way
2548 # see "test cases/fortran/6 dynamic"
2549 fc = detect_compiler_for(env, 'fortran', MachineChoice.HOST, True, '')
2550 if fc.get_id() in {'intel-cl', 'pgi'}:
2551 raise SkipTest('The Intel (classic) and PGI fortran compilers do not support standard shared libraries')
2552
2553 # test empty directory
2554 with tempfile.TemporaryDirectory() as tmpdir:
2555 self._run(self.meson_command + ['init', '--language', lang, '--type', target_type],
2556 workdir=tmpdir)
2557 self._run(self.setup_command + ['--backend=ninja', 'builddir'], workdir=tmpdir)
2558 self._run(ninja, workdir=os.path.join(tmpdir, 'builddir'))
2559
2560 # custom executable name
2561 if target_type == 'executable':
2562 with tempfile.TemporaryDirectory() as tmpdir:
2563 self._run(self.meson_command + ['init', '--language', lang, '--type', target_type,
2564 '--executable', 'foobar'],
2565 workdir=tmpdir)
2566 self._run(self.setup_command + ['--backend=ninja', 'builddir'], workdir=tmpdir)
2567 self._run(ninja, workdir=os.path.join(tmpdir, 'builddir'))
2568
2569 if lang not in {'cs', 'java'}:
2570 exe = os.path.join(tmpdir, 'builddir', 'foobar' + exe_suffix)
2571 self.assertTrue(os.path.exists(exe))
2572
2573 def _template_test_dirty(self, lang: Language, target_type: str, env: Environment, ninja: list[str]) -> None:
2574 if is_windows() and lang == 'fortran' and target_type == 'library':
2575 # non-Gfortran Windows Fortran compilers do not do shared libraries in a Fortran standard way
2576 # see "test cases/fortran/6 dynamic"
2577 fc = detect_compiler_for(env, 'fortran', MachineChoice.HOST, True, '')
2578 if fc.get_id() in {'intel-cl', 'pgi'}:
2579 raise SkipTest('The Intel (classic) and PGI fortran compilers do not support standard shared libraries')
2580
2581 # test empty directory
2582 with tempfile.TemporaryDirectory() as tmpdir:
2583 self._run(self.meson_command + ['init', '--language', lang, '--type', target_type],
2584 workdir=tmpdir)
2585 self._run(self.setup_command + ['--backend=ninja', 'builddir'], workdir=tmpdir)
2586 self._run(ninja, workdir=os.path.join(tmpdir, 'builddir'))
2587
2588 # test directory with existing code file
2589 if lang in {'c', 'cpp', 'd'}:
2590 with tempfile.TemporaryDirectory() as tmpdir:
2591 with open(os.path.join(tmpdir, 'foo.' + lang), 'w', encoding='utf-8') as f:
2592 f.write('int main(void) {}')
2593 self._run(self.meson_command + ['init', '-b'], workdir=tmpdir)
2594
2595 elif lang in {'java'}:
2596 with tempfile.TemporaryDirectory() as tmpdir:
2597 with open(os.path.join(tmpdir, 'Foo.' + lang), 'w', encoding='utf-8') as f:
2598 f.write('public class Foo { public static void main() {} }')
2599 self._run(self.meson_command + ['init', '-b'], workdir=tmpdir)
2600
2601 def _test_template(self, lang: Language) -> None:
2602 ninja = mesonbuild.tooldetect.detect_ninja()
2603 if ninja is None:
2604 raise SkipTest('This test currently requires ninja. Fix this once "meson build" works.')
2605
2606 env = get_fake_env(bdir=self.builddir)
2607
2608 extra_lang: Language | None
2609 match lang:
2610 case 'cuda':
2611 extra_lang = 'cpp'
2612 case 'vala':
2613 extra_lang = 'c'
2614 case _:
2615 extra_lang = None
2616
2617 if extra_lang is not None:
2618 try:
2619 comp = detect_compiler_for(env, extra_lang, MachineChoice.HOST, True, '')
2620 except EnvironmentException:
2621 comp = None
2622 if comp is None:
2623 raise SkipTest(f'Could not find compiler for {extra_lang}, which is required for {lang}')
2624
2625 with tempfile.TemporaryDirectory() as d:
2626 try:
2627 comp = detect_compiler_for(env, lang, MachineChoice.HOST, True, '')
2628 if comp is None:
2629 raise SkipTest(f'Could not find compiler for language: {lang}')
2630 comp.sanity_check(d)
2631 except EnvironmentException:
2632 raise SkipTest(f'Compiler for language {lang} failed to sanity check')
2633
2634 for target_type, fresh in itertools.product(('executable', 'library'), (True, False)):
2635 with self.subTest(type=target_type, fresh=fresh):
2636 func = self._template_test_fresh if fresh else self._template_test_dirty
2637 try:
2638 func(lang, target_type, env, ninja)
2639 except subprocess.CalledProcessError as e:
2640 self.fail(e.stdout)
2641
2642 def test_template_c(self) -> None:
2643 self._test_template('c')
2644
2645 def test_template_cpp(self) -> None:
2646 self._test_template('cpp')
2647
2648 def test_template_cs(self) -> None:
2649 self._test_template('cs')
2650
2651 def test_template_cuda(self) -> None:
2652 self._test_template('cuda')
2653
2654 def test_template_d(self) -> None:
2655 if is_osx():
2656 raise SkipTest('The D template fails under MacOS CI, we are unsure why. Patches welcome.')
2657 self._test_template('d')
2658
2659 def test_template_fortran(self) -> None:
2660 self._test_template('fortran')
2661
2662 def test_template_java(self) -> None:
2663 self._test_template('java')
2664
2665 def test_template_objc(self) -> None:
2666 self._test_template('objc')
2667
2668 def test_template_objcpp(self) -> None:
2669 self._test_template('objcpp')
2670
2671 def test_template_rust(self) -> None:
2672 self._test_template('rust')
2673
2674 def test_template_vala(self) -> None:
2675 self._test_template('vala')
2676
2677 def test_compiler_run_command(self):
2678 '''
2679 The test checks that the compiler object can be passed to
2680 run_command().
2681 '''
2682 testdir = os.path.join(self.unit_test_dir, '24 compiler run_command')
2683 self.init(testdir)
2684
2685 def test_identical_target_name_in_subproject_flat_layout(self):
2686 '''
2687 Test that identical targets in different subprojects do not collide
2688 if layout is flat.
2689 '''
2690 testdir = os.path.join(self.common_test_dir, '172 identical target name in subproject flat layout')
2691 self.init(testdir, extra_args=['--layout=flat'])
2692 self.build()
2693
2694 def test_identical_target_name_in_subdir_flat_layout(self):
2695 '''
2696 Test that identical targets in different subdirs do not collide
2697 if layout is flat.
2698 '''
2699 testdir = os.path.join(self.common_test_dir, '181 same target name flat layout')
2700 self.init(testdir, extra_args=['--layout=flat'])
2701 self.build()
2702
2703 def test_flock(self):
2704 exception_raised = False
2705 with tempfile.TemporaryDirectory() as tdir:
2706 with DirectoryLock(tdir, 'lock', DirectoryLockAction.FAIL, 'failed to lock directory'):
2707 try:
2708 with DirectoryLock(tdir, 'lock', DirectoryLockAction.FAIL, 'expected failure'):
2709 pass
2710 except MesonException:
2711 exception_raised = True
2712 self.assertTrue(exception_raised, 'Double locking did not raise exception.')
2713
2714 @skipIf(is_osx(), 'Test not applicable to OSX')
2715 def test_check_module_linking(self):
2716 """
2717 Test that link_with: a shared module issues a warning
2718 https://github.com/mesonbuild/meson/issues/2865
2719 (That an error is raised on OSX is exercised by test failing/78)
2720 """
2721 tdir = os.path.join(self.unit_test_dir, '30 shared_mod linking')
2722 out = self.init(tdir)
2723 msg = ('''DEPRECATION: target prog links against shared module mymod, which is incorrect.
2724 This will be an error in meson 2.0, so please use shared_library() for mymod instead.
2725 If shared_module() was used for mymod because it has references to undefined symbols,
2726 use shared_library() with `override_options: ['b_lundef=false']` instead.''')
2727 self.assertIn(msg, out)
2728
2729 def test_mixed_language_linker_check(self):
2730 testdir = os.path.join(self.unit_test_dir, '96 compiler.links file arg')
2731 self.init(testdir)
2732 cmds = self.get_meson_log_compiler_checks()
2733 self.assertEqual(len(cmds), 5)
2734 # Path to the compilers, gleaned from cc.compiles tests
2735 cc = cmds[0][0]
2736 cxx = cmds[1][0]
2737 # cc.links
2738 self.assertEqual(cmds[2][0], cc)
2739 # cxx.links with C source
2740 self.assertEqual(cmds[3][0], cc)
2741 self.assertEqual(cmds[4][0], cxx)
2742 if self.backend is Backend.ninja:
2743 # updating the file to check causes a reconfigure
2744 #
2745 # only the ninja backend is competent enough to detect reconfigured
2746 # no-op builds without build targets
2747 self.utime(os.path.join(testdir, 'test.c'))
2748 self.assertReconfiguredBuildIsNoop()
2749
2750 def test_ndebug_if_release_disabled(self):
2751 testdir = os.path.join(self.unit_test_dir, '28 ndebug if-release')
2752 self.init(testdir, extra_args=['--buildtype=release', '-Db_ndebug=if-release'])
2753 self.build()
2754 exe = os.path.join(self.builddir, 'main')
2755 self.assertEqual(b'NDEBUG=1', subprocess.check_output(exe).strip())
2756
2757 def test_ndebug_if_release_enabled(self):
2758 testdir = os.path.join(self.unit_test_dir, '28 ndebug if-release')
2759 self.init(testdir, extra_args=['--buildtype=debugoptimized', '-Db_ndebug=if-release'])
2760 self.build()
2761 exe = os.path.join(self.builddir, 'main')
2762 self.assertEqual(b'NDEBUG=0', subprocess.check_output(exe).strip())
2763
2764 def test_guessed_linker_dependencies(self):
2765 '''
2766 Test that meson adds dependencies for libraries based on the final
2767 linker command line.
2768 '''
2769 testdirbase = os.path.join(self.unit_test_dir, '29 guessed linker dependencies')
2770 testdirlib = os.path.join(testdirbase, 'lib')
2771
2772 extra_args = None
2773 libdir_flags = ['-L']
2774 env = get_fake_env(testdirlib, self.builddir, self.prefix)
2775 if detect_c_compiler(env, MachineChoice.HOST).get_id() in {'msvc', 'clang-cl', 'intel-cl'}:
2776 # msvc-like compiler, also test it with msvc-specific flags
2777 libdir_flags += ['/LIBPATH:', '-LIBPATH:']
2778 else:
2779 # static libraries are not linkable with -l with msvc because meson installs them
2780 # as .a files which unix_args_to_native will not know as it expects libraries to use
2781 # .lib as extension. For a DLL the import library is installed as .lib. Thus for msvc
2782 # this tests needs to use shared libraries to test the path resolving logic in the
2783 # dependency generation code path.
2784 extra_args = ['--default-library', 'static']
2785
2786 initial_builddir = self.builddir
2787 initial_installdir = self.installdir
2788
2789 for libdir_flag in libdir_flags:
2790 # build library
2791 self.new_builddir()
2792 self.init(testdirlib, extra_args=extra_args)
2793 self.build()
2794 self.install()
2795 libbuilddir = self.builddir
2796 installdir = self.installdir
2797 libdir = os.path.join(self.installdir, self.prefix.lstrip('/').lstrip('\\'), 'lib')
2798
2799 # build user of library
2800 self.new_builddir()
2801 # replace is needed because meson mangles platform paths passed via LDFLAGS
2802 self.init(os.path.join(testdirbase, 'exe'),
2803 override_envvars={"LDFLAGS": '{}{}'.format(libdir_flag, libdir.replace('\\', '/'))})
2804 self.build()
2805 self.assertBuildIsNoop()
2806
2807 # rebuild library
2808 exebuilddir = self.builddir
2809 self.installdir = installdir
2810 self.builddir = libbuilddir
2811 # Microsoft's compiler is quite smart about touching import libs on changes,
2812 # so ensure that there is actually a change in symbols.
2813 self.setconf('-Dmore_exports=true')
2814 self.build()
2815 self.install()
2816 # no ensure_backend_detects_changes needed because self.setconf did that already
2817
2818 # assert user of library will be rebuild
2819 self.builddir = exebuilddir
2820 self.assertRebuiltTarget('app')
2821
2822 # restore dirs for the next test case
2823 self.installdir = initial_builddir
2824 self.builddir = initial_installdir
2825
2826 def test_conflicting_d_dash_option(self):
2827 testdir = os.path.join(self.unit_test_dir, '37 mixed command line args')
2828 with self.assertRaises((subprocess.CalledProcessError, RuntimeError)) as e:
2829 self.init(testdir, extra_args=['-Dbindir=foo', '--bindir=bar'])
2830 # Just to ensure that we caught the correct error
2831 self.assertIn('as both', e.stderr)
2832
2833 def _test_same_option_twice(self, arg, args):
2834 testdir = os.path.join(self.unit_test_dir, '37 mixed command line args')
2835 self.init(testdir, extra_args=args)
2836 opts = self.introspect('--buildoptions')
2837 for item in opts:
2838 if item['name'] == arg:
2839 self.assertEqual(item['value'], 'bar')
2840 return
2841 raise Exception(f'Missing {arg} value?')
2842
2843 def test_same_dash_option_twice(self):
2844 self._test_same_option_twice('bindir', ['--bindir=foo', '--bindir=bar'])
2845
2846 def test_same_d_option_twice(self):
2847 self._test_same_option_twice('bindir', ['-Dbindir=foo', '-Dbindir=bar'])
2848
2849 def test_same_project_d_option_twice(self):
2850 self._test_same_option_twice('one', ['-Done=foo', '-Done=bar'])
2851
2852 def _test_same_option_twice_configure(self, arg, args):
2853 testdir = os.path.join(self.unit_test_dir, '37 mixed command line args')
2854 self.init(testdir)
2855 self.setconf(args)
2856 opts = self.introspect('--buildoptions')
2857 for item in opts:
2858 if item['name'] == arg:
2859 self.assertEqual(item['value'], 'bar')
2860 return
2861 raise Exception(f'Missing {arg} value?')
2862
2863 def test_same_dash_option_twice_configure(self):
2864 self._test_same_option_twice_configure(
2865 'bindir', ['--bindir=foo', '--bindir=bar'])
2866
2867 def test_same_d_option_twice_configure(self):
2868 self._test_same_option_twice_configure(
2869 'bindir', ['-Dbindir=foo', '-Dbindir=bar'])
2870
2871 def test_same_project_d_option_twice_configure(self):
2872 self._test_same_option_twice_configure(
2873 'one', ['-Done=foo', '-Done=bar'])
2874
2875 def test_command_line(self):
2876 testdir = os.path.join(self.unit_test_dir, '34 command line')
2877
2878 # Verify default values when passing no args that affect the
2879 # configuration, and as a bonus, test that --profile-self works.
2880 out = self.init(testdir, extra_args=['--profile-self', '--fatal-meson-warnings'])
2881 self.assertNotIn('[default: true]', out)
2882 obj = mesonbuild.coredata.load(self.builddir)
2883 self.assertEqual(obj.optstore.get_value_for('default_library'), 'static')
2884 self.assertEqual(obj.optstore.get_value_for('warning_level'), '1')
2885 self.assertEqual(obj.optstore.get_value_for(OptionKey('set_sub_opt', '')), True)
2886 self.assertEqual(obj.optstore.get_value_for(OptionKey('subp_opt', 'subp')), 'default3')
2887 self.wipe()
2888
2889 # warning_level is special, it's --warnlevel instead of --warning-level
2890 # for historical reasons
2891 self.init(testdir, extra_args=['--warnlevel=2', '--fatal-meson-warnings'])
2892 obj = mesonbuild.coredata.load(self.builddir)
2893 self.assertEqual(obj.optstore.get_value_for('warning_level'), '2')
2894 self.setconf('--warnlevel=3')
2895 obj = mesonbuild.coredata.load(self.builddir)
2896 self.assertEqual(obj.optstore.get_value_for('warning_level'), '3')
2897 self.setconf('--warnlevel=everything')
2898 obj = mesonbuild.coredata.load(self.builddir)
2899 self.assertEqual(obj.optstore.get_value_for('warning_level'), 'everything')
2900 self.wipe()
2901
2902 # But when using -D syntax, it should be 'warning_level'
2903 self.init(testdir, extra_args=['-Dwarning_level=2', '--fatal-meson-warnings'])
2904 obj = mesonbuild.coredata.load(self.builddir)
2905 self.assertEqual(obj.optstore.get_value_for('warning_level'), '2')
2906 self.setconf('-Dwarning_level=3')
2907 obj = mesonbuild.coredata.load(self.builddir)
2908 self.assertEqual(obj.optstore.get_value_for('warning_level'), '3')
2909 self.setconf('-Dwarning_level=everything')
2910 obj = mesonbuild.coredata.load(self.builddir)
2911 self.assertEqual(obj.optstore.get_value_for('warning_level'), 'everything')
2912 self.wipe()
2913
2914 # Mixing --option and -Doption is forbidden
2915 with self.assertRaises((subprocess.CalledProcessError, RuntimeError)) as cm:
2916 self.init(testdir, extra_args=['--warnlevel=1', '-Dwarning_level=3'])
2917 if isinstance(cm.exception, subprocess.CalledProcessError):
2918 self.assertNotEqual(0, cm.exception.returncode)
2919 self.assertIn('as both', cm.exception.output)
2920 else:
2921 self.assertIn('as both', str(cm.exception))
2922 self.init(testdir)
2923 with self.assertRaises((subprocess.CalledProcessError, RuntimeError)) as cm:
2924 self.setconf(['--warnlevel=1', '-Dwarning_level=3'])
2925 if isinstance(cm.exception, subprocess.CalledProcessError):
2926 self.assertNotEqual(0, cm.exception.returncode)
2927 self.assertIn('as both', cm.exception.output)
2928 else:
2929 self.assertIn('as both', str(cm.exception))
2930 self.wipe()
2931
2932 # --default-library should override default value from project()
2933 self.init(testdir, extra_args=['--default-library=both', '--fatal-meson-warnings'])
2934 obj = mesonbuild.coredata.load(self.builddir)
2935 self.assertEqual(obj.optstore.get_value_for('default_library'), 'both')
2936 self.setconf('--default-library=shared')
2937 obj = mesonbuild.coredata.load(self.builddir)
2938 self.assertEqual(obj.optstore.get_value_for('default_library'), 'shared')
2939 if self.backend is Backend.ninja:
2940 # reconfigure target works only with ninja backend
2941 self.build('reconfigure')
2942 obj = mesonbuild.coredata.load(self.builddir)
2943 self.assertEqual(obj.optstore.get_value_for('default_library'), 'shared')
2944 self.wipe()
2945
2946 # Should fail on unknown options
2947 with self.assertRaises((subprocess.CalledProcessError, RuntimeError)) as cm:
2948 self.init(testdir, extra_args=['-Dbad=1', '-Dfoo=2', '-Dwrong_link_args=foo'])
2949 self.assertNotEqual(0, cm.exception.returncode)
2950 self.assertIn(msg, cm.exception.output)
2951 self.wipe()
2952
2953 # Should fail on malformed option
2954 msg = "Option 'foo' must have a value separated by equals sign."
2955 with self.assertRaises((subprocess.CalledProcessError, RuntimeError)) as cm:
2956 self.init(testdir, extra_args=['-Dfoo'])
2957 if isinstance(cm.exception, subprocess.CalledProcessError):
2958 self.assertNotEqual(0, cm.exception.returncode)
2959 self.assertIn(msg, cm.exception.output)
2960 else:
2961 self.assertIn(msg, str(cm.exception))
2962 self.init(testdir)
2963 with self.assertRaises((subprocess.CalledProcessError, RuntimeError)) as cm:
2964 self.setconf('-Dfoo')
2965 if isinstance(cm.exception, subprocess.CalledProcessError):
2966 self.assertNotEqual(0, cm.exception.returncode)
2967 self.assertIn(msg, cm.exception.output)
2968 else:
2969 self.assertIn(msg, str(cm.exception))
2970 self.wipe()
2971
2972 # It is not an error to set wrong option for unknown subprojects or
2973 # language because we don't have control on which one will be selected.
2974 self.init(testdir, extra_args=['-Dc_wrong=1', '-Dwrong:bad=1'])
2975 self.wipe()
2976
2977 # Test we can set subproject option
2978 self.init(testdir, extra_args=['-Dsubp:subp_opt=foo', '--fatal-meson-warnings'])
2979 obj = mesonbuild.coredata.load(self.builddir)
2980 self.assertEqual(obj.optstore.get_value_for(OptionKey('subp_opt', 'subp')), 'foo')
2981 self.wipe()
2982
2983 # c_args value should be parsed with split_args
2984 self.init(testdir, extra_args=['-Dc_args=-Dfoo -Dbar "-Dthird=one two"', '--fatal-meson-warnings'])
2985 obj = mesonbuild.coredata.load(self.builddir)
2986 self.assertEqual(obj.optstore.get_value_for(OptionKey('c_args')), ['-Dfoo', '-Dbar', '-Dthird=one two'])
2987
2988 self.setconf('-Dc_args="foo bar" one two')
2989 obj = mesonbuild.coredata.load(self.builddir)
2990 self.assertEqual(obj.optstore.get_value_for(OptionKey('c_args')), ['foo bar', 'one', 'two'])
2991 self.wipe()
2992
2993 self.init(testdir, extra_args=['-Dset_percent_opt=myoption%', '--fatal-meson-warnings'])
2994 obj = mesonbuild.coredata.load(self.builddir)
2995 self.assertEqual(obj.optstore.get_value_for(OptionKey('set_percent_opt', '')), 'myoption%')
2996 self.wipe()
2997
2998 # Setting a 2nd time the same option should override the first value
2999 try:
3000 self.init(testdir, extra_args=['--bindir=foo', '--bindir=bar',
3001 '-Dbuildtype=plain', '-Dbuildtype=release',
3002 '-Db_sanitize=address', '-Db_sanitize=thread',
3003 '-Dc_args=-Dfoo', '-Dc_args=-Dbar',
3004 '-Db_lundef=false', '--fatal-meson-warnings'])
3005 obj = mesonbuild.coredata.load(self.builddir)
3006 self.assertEqual(obj.optstore.get_value_for('bindir'), 'bar')
3007 self.assertEqual(obj.optstore.get_value_for('buildtype'), 'release')
3008 self.assertEqual(obj.optstore.get_value_for('b_sanitize'), ['thread'])
3009 self.assertEqual(obj.optstore.get_value_for(OptionKey('c_args')), ['-Dbar'])
3010 self.setconf(['--bindir=bar', '--bindir=foo',
3011 '-Dbuildtype=release', '-Dbuildtype=plain',
3012 '-Db_sanitize=thread', '-Db_sanitize=address',
3013 '-Dc_args=-Dbar', '-Dc_args=-Dfoo'])
3014 obj = mesonbuild.coredata.load(self.builddir)
3015 self.assertEqual(obj.optstore.get_value_for('bindir'), 'foo')
3016 self.assertEqual(obj.optstore.get_value_for('buildtype'), 'plain')
3017 self.assertEqual(obj.optstore.get_value_for('b_sanitize'), ['address'])
3018 self.assertEqual(obj.optstore.get_value_for(OptionKey('c_args')), ['-Dfoo'])
3019 self.wipe()
3020 except KeyError:
3021 # Ignore KeyError, it happens on CI for compilers that does not
3022 # support b_sanitize. We have to test with a base option because
3023 # they used to fail this test with Meson 0.46 an earlier versions.
3024 pass
3025
3026 def test_warning_level_0(self):
3027 testdir = os.path.join(self.common_test_dir, '207 warning level 0')
3028
3029 # Verify default values when passing no args
3030 self.init(testdir)
3031 obj = mesonbuild.coredata.load(self.builddir)
3032 self.assertEqual(obj.optstore.get_value_for('warning_level'), '0')
3033 self.wipe()
3034
3035 # verify we can override w/ --warnlevel
3036 self.init(testdir, extra_args=['--warnlevel=1'])
3037 obj = mesonbuild.coredata.load(self.builddir)
3038 self.assertEqual(obj.optstore.get_value_for('warning_level'), '1')
3039 self.setconf('--warnlevel=0')
3040 obj = mesonbuild.coredata.load(self.builddir)
3041 self.assertEqual(obj.optstore.get_value_for('warning_level'), '0')
3042 self.wipe()
3043
3044 # verify we can override w/ -Dwarning_level
3045 self.init(testdir, extra_args=['-Dwarning_level=1'])
3046 obj = mesonbuild.coredata.load(self.builddir)
3047 self.assertEqual(obj.optstore.get_value_for('warning_level'), '1')
3048 self.setconf('-Dwarning_level=0')
3049 obj = mesonbuild.coredata.load(self.builddir)
3050 self.assertEqual(obj.optstore.get_value_for('warning_level'), '0')
3051 self.wipe()
3052
3053 def test_feature_check_usage_subprojects(self):
3054 testdir = os.path.join(self.unit_test_dir, '40 featurenew subprojects')
3055 out = self.init(testdir)
3056 # Parent project warns correctly
3057 self.assertRegex(out, "WARNING: Project targets '>= 0.45'.*'0.47.0': dict")
3058 # Subprojects warn correctly
3059 self.assertRegex(out, r"foo\| .*WARNING: Project targets '>= 0.40'.*'0.44.0': disabler")
3060 self.assertRegex(out, r"baz\| .*WARNING: Project does not target a minimum version.*'0.44.0': disabler")
3061 # Subproject has a new-enough meson_version, no warning
3062 self.assertNotRegex(out, "WARNING: Project targets.*Python")
3063 # Ensure a summary is printed in the subproject and the outer project
3064 self.assertRegex(out, r"\| WARNING: Project specifies a minimum meson_version '>= 0.40'")
3065 self.assertRegex(out, r"\| \* 0.44.0: {'disabler'}")
3066 self.assertRegex(out, "WARNING: Project specifies a minimum meson_version '>= 0.45'")
3067 self.assertRegex(out, " * 0.47.0: {'dict'}")
3068
3069 def test_configure_file_warnings(self):
3070 testdir = os.path.join(self.common_test_dir, "14 configure file")
3071 out = self.init(testdir)
3072 self.assertRegex(out, "WARNING:.*'empty'.*config.h.in.*not present.*")
3073 self.assertRegex(out, "WARNING:.*'FOO_BAR'.*nosubst-nocopy2.txt.in.*not present.*")
3074 self.assertRegex(out, "WARNING:.*'empty'.*config.h.in.*not present.*")
3075 self.assertRegex(out, "WARNING:.*empty configuration_data.*test.py.in")
3076 # Warnings for configuration files that are overwritten.
3077 self.assertRegex(out, "WARNING:.*\"double_output.txt\".*overwrites")
3078 self.assertRegex(out, "WARNING:.*\"subdir.double_output2.txt\".*overwrites")
3079 self.assertNotRegex(out, "WARNING:.*no_write_conflict.txt.*overwrites")
3080 self.assertNotRegex(out, "WARNING:.*@BASENAME@.*overwrites")
3081 self.assertRegex(out, "WARNING:.*\"sameafterbasename\".*overwrites")
3082 # No warnings about empty configuration data objects passed to files with substitutions
3083 self.assertNotRegex(out, "WARNING:.*empty configuration_data.*nosubst-nocopy1.txt.in")
3084 self.assertNotRegex(out, "WARNING:.*empty configuration_data.*nosubst-nocopy2.txt.in")
3085 with open(os.path.join(self.builddir, 'nosubst-nocopy1.txt'), 'rb') as f:
3086 self.assertEqual(f.read().strip(), b'/* #undef FOO_BAR */')
3087 with open(os.path.join(self.builddir, 'nosubst-nocopy2.txt'), 'rb') as f:
3088 self.assertEqual(f.read().strip(), b'')
3089
3090 def test_dirs(self):
3091 with tempfile.TemporaryDirectory() as containing:
3092 with tempfile.TemporaryDirectory(dir=containing) as srcdir:
3093 mfile = os.path.join(srcdir, 'meson.build')
3094 of = open(mfile, 'w', encoding='utf-8')
3095 of.write("project('foobar', 'c')\n")
3096 of.close()
3097 pc = subprocess.run(self.setup_command,
3098 cwd=srcdir,
3099 stdout=subprocess.PIPE,
3100 stderr=subprocess.DEVNULL)
3101 self.assertIn(b'Must specify at least one directory name', pc.stdout)
3102 with tempfile.TemporaryDirectory(dir=srcdir) as builddir:
3103 subprocess.run(self.setup_command,
3104 check=True,
3105 cwd=builddir,
3106 stdout=subprocess.DEVNULL,
3107 stderr=subprocess.DEVNULL)
3108
3109 def get_opts_as_dict(self):
3110 result = {}
3111 for i in self.introspect('--buildoptions'):
3112 result[i['name']] = i['value']
3113 return result
3114
3115 def test_buildtype_setting(self):
3116 testdir = os.path.join(self.common_test_dir, '1 trivial')
3117 self.init(testdir)
3118 opts = self.get_opts_as_dict()
3119 self.assertEqual(opts['buildtype'], 'debug')
3120 self.assertEqual(opts['debug'], True)
3121 self.setconf('-Ddebug=false')
3122 opts = self.get_opts_as_dict()
3123 self.assertEqual(opts['debug'], False)
3124 self.assertEqual(opts['buildtype'], 'debug')
3125 self.assertEqual(opts['optimization'], '0')
3126 self.setconf('-Doptimization=g')
3127 opts = self.get_opts_as_dict()
3128 self.assertEqual(opts['debug'], False)
3129 self.assertEqual(opts['buildtype'], 'debug')
3130 self.assertEqual(opts['optimization'], 'g')
3131
3132 @skipIfNoPkgconfig
3133 @skipIf(is_windows(), 'Help needed with fixing this test on windows')
3134 def test_native_dep_pkgconfig(self):
3135 testdir = os.path.join(self.unit_test_dir,
3136 '45 native dep pkgconfig var')
3137 with tempfile.NamedTemporaryFile(mode='w', delete=False, encoding='utf-8') as crossfile:
3138 crossfile.write(textwrap.dedent(
3139 '''[binaries]
3140 pkg-config = '{}'
3141
3142 [properties]
3143
3144 [host_machine]
3145 system = 'linux'
3146 cpu_family = 'arm'
3147 cpu = 'armv7'
3148 endian = 'little'
3149 '''.format(os.path.join(testdir, 'cross_pkgconfig.py'))))
3150 crossfile.flush()
3151 self.meson_cross_files = [crossfile.name]
3152
3153 env = {'PKG_CONFIG_LIBDIR': os.path.join(testdir,
3154 'native_pkgconfig')}
3155 self.init(testdir, extra_args=['-Dstart_native=false'], override_envvars=env)
3156 self.wipe()
3157 self.init(testdir, extra_args=['-Dstart_native=true'], override_envvars=env)
3158
3159 @skipIfNoPkgconfig
3160 @skipIf(is_windows(), 'Help needed with fixing this test on windows')
3161 def test_pkg_config_libdir(self):
3162 testdir = os.path.join(self.unit_test_dir,
3163 '45 native dep pkgconfig var')
3164 with tempfile.NamedTemporaryFile(mode='w', delete=False, encoding='utf-8') as crossfile:
3165 crossfile.write(textwrap.dedent(
3166 '''[binaries]
3167 pkg-config = 'pkg-config'
3168
3169 [properties]
3170 pkg_config_libdir = ['{}']
3171
3172 [host_machine]
3173 system = 'linux'
3174 cpu_family = 'arm'
3175 cpu = 'armv7'
3176 endian = 'little'
3177 '''.format(os.path.join(testdir, 'cross_pkgconfig'))))
3178 crossfile.flush()
3179 self.meson_cross_files = [crossfile.name]
3180
3181 env = {'PKG_CONFIG_LIBDIR': os.path.join(testdir,
3182 'native_pkgconfig')}
3183 self.init(testdir, extra_args=['-Dstart_native=false'], override_envvars=env)
3184 self.wipe()
3185 self.init(testdir, extra_args=['-Dstart_native=true'], override_envvars=env)
3186
3187 @skipIf(is_osx(), 'Not implemented for Darwin yet')
3188 @skipIf(is_windows(), 'POSIX only')
3189 def test_python_build_config_extensions(self):
3190 testdir = os.path.join(self.unit_test_dir,
3191 '126 python extension')
3192
3193 VERSION_INFO_KEYS = ('major', 'minor', 'micro', 'releaselevel', 'serial')
3194 EXTENSION_SUFFIX = '.extension-suffix.so'
3195 STABLE_ABI_SUFFIX = '.stable-abi-suffix.so'
3196 # macOS framework builds put libpython in PYTHONFRAMEWORKPREFIX.
3197 LIBDIR = (sysconfig.get_config_var('PYTHONFRAMEWORKPREFIX') or
3198 sysconfig.get_config_var('LIBDIR'))
3199
3200 python_build_config = {
3201 'schema_version': '1.0',
3202 'base_interpreter': sys.executable,
3203 'base_prefix': sys.base_prefix,
3204 'platform': sysconfig.get_platform(),
3205 'language': {
3206 'version': sysconfig.get_python_version(),
3207 'version_info': {key: getattr(sys.version_info, key) for key in VERSION_INFO_KEYS}
3208 },
3209 'implementation': {
3210 attr: (
3211 getattr(sys.implementation, attr)
3212 if attr != 'version' else
3213 {key: getattr(sys.implementation.version, key) for key in VERSION_INFO_KEYS}
3214 )
3215 for attr in dir(sys.implementation)
3216 if not attr.startswith('__')
3217 },
3218 'abi': {
3219 'flags': list(sys.abiflags),
3220 'extension_suffix': EXTENSION_SUFFIX,
3221 'stable_abi_suffix': STABLE_ABI_SUFFIX,
3222 },
3223 'suffixes': {
3224 'source': ['.py'],
3225 'bytecode': ['.pyc'],
3226 'optimized_bytecode': ['.pyc'],
3227 'debug_bytecode': ['.pyc'],
3228 'extensions': [EXTENSION_SUFFIX, STABLE_ABI_SUFFIX, '.so'],
3229 },
3230 'libpython': {
3231 'dynamic': os.path.join(LIBDIR, sysconfig.get_config_var('LDLIBRARY')),
3232 'static': os.path.join(LIBDIR, sysconfig.get_config_var('LIBRARY')),
3233 # set it to False on PyPy, since dylib is optional, but also
3234 # the value is currently wrong:
3235 # https://github.com/pypy/pypy/issues/5249
3236 'link_extensions': '__pypy__' not in sys.builtin_module_names,
3237 },
3238 'c_api': {
3239 'headers': sysconfig.get_config_var('INCLUDEPY'),
3240 }
3241 }
3242
3243 py3library = sysconfig.get_config_var('PY3LIBRARY')
3244 if py3library is not None:
3245 python_build_config['libpython']['dynamic_stableabi'] = os.path.join(LIBDIR, py3library)
3246
3247 build_stable_abi = sysconfig.get_config_var('Py_GIL_DISABLED') != 1 or sys.version_info >= (3, 15)
3248 intro_installed_file = os.path.join(self.builddir, 'meson-info', 'intro-installed.json')
3249 expected_files = [
3250 os.path.join(self.builddir, 'foo' + EXTENSION_SUFFIX),
3251 ]
3252 if build_stable_abi:
3253 expected_files += [
3254 os.path.join(self.builddir, 'foo_stable' + STABLE_ABI_SUFFIX),
3255 ]
3256 if is_cygwin():
3257 expected_files += [
3258 os.path.join(self.builddir, 'foo' + EXTENSION_SUFFIX.replace('.so', '.dll.a')),
3259 ]
3260 if build_stable_abi:
3261 expected_files += [
3262 os.path.join(self.builddir, 'foo_stable' + STABLE_ABI_SUFFIX.replace('.so', '.dll.a')),
3263 ]
3264
3265 for with_pkgconfig in (False, True):
3266 with self.subTest(with_pkgconfig=with_pkgconfig):
3267 if with_pkgconfig:
3268 libpc = sysconfig.get_config_var('LIBPC')
3269 if libpc is None:
3270 raise SkipTest('pkg-config subtest skipped because of no LIBPC')
3271 python_build_config['c_api']['pkgconfig_path'] = libpc
3272 # Old Ubuntu versions have incorrect LIBDIR, skip testing non-pkgconfig variant there.
3273 elif not os.path.exists(python_build_config['libpython']['dynamic']):
3274 raise SkipTest('non-pkgconfig subtest skipped because of wrong LIBDIR')
3275
3276 with tempfile.NamedTemporaryFile(mode='w', delete=False, encoding='utf-8') as python_build_config_file:
3277 json.dump(python_build_config, fp=python_build_config_file)
3278 for build_config_via_cross in (False, True):
3279 for sys_root in (None, sys.base_prefix):
3280 with self.subTest(build_config_via_cross=build_config_via_cross, sys_root=sys_root):
3281 # fd.o pkg-config does not handle sys_root correctly
3282 if sys_root is not None and with_pkgconfig and shutil.which('pkgconf') is None:
3283 raise SkipTest('sys_root subtest skipped because of fd.o pkg-config')
3284
3285 with tempfile.NamedTemporaryFile(mode='w', delete=False, encoding='utf-8') as cross_file:
3286 cross_file.write(
3287 textwrap.dedent(f'''
3288 [binaries]
3289 pkg-config = 'pkg-config'
3290 ''')
3291 )
3292 if build_config_via_cross:
3293 cross_file.write(
3294 textwrap.dedent(f'''
3295 [built-in options]
3296 python.build_config = '{python_build_config_file.name}'
3297 ''')
3298 )
3299 if sys_root is not None:
3300 cross_file.write(
3301 textwrap.dedent(f'''
3302 [properties]
3303 sys_root = '{sys_root}'
3304 ''')
3305 )
3306 cross_file.flush()
3307
3308 extra_args = ['--cross-file', cross_file.name]
3309 if not build_config_via_cross:
3310 extra_args += ['--python.build-config', python_build_config_file.name]
3311
3312 self.init(testdir, extra_args=extra_args)
3313 self.build()
3314 with open(intro_installed_file) as f:
3315 intro_installed = json.load(f)
3316 self.assertEqual(sorted(expected_files), sorted(intro_installed))
3317 self.wipe()
3318
3319 def __reconfigure(self):
3320 # Set an older version to force a reconfigure from scratch
3321 filename = os.path.join(self.privatedir, 'coredata.dat')
3322 with open(filename, 'rb') as f:
3323 obj = pickle.load(f)
3324 obj.version = '0.47.0'
3325 with open(filename, 'wb') as f:
3326 pickle.dump(obj, f)
3327
3328 def test_reconfigure(self):
3329 testdir = os.path.join(self.unit_test_dir, '47 reconfigure')
3330 self.init(testdir, extra_args=['-Dopt1=val1', '-Dsub1:werror=true'])
3331 self.setconf('-Dopt2=val2')
3332
3333 self.__reconfigure()
3334
3335 out = self.init(testdir, extra_args=['--reconfigure', '-Dopt3=val3'])
3336 self.assertRegex(out, 'Regenerating configuration from scratch')
3337 self.assertRegex(out, 'opt1 val1')
3338 self.assertRegex(out, 'opt2 val2')
3339 self.assertRegex(out, 'opt3 val3')
3340 self.assertRegex(out, 'opt4 default4')
3341 # Per subproject options are stored in augments,
3342 # not in the options themselves so these status
3343 # messages are no longer printed.
3344 #self.assertRegex(out, 'sub1:werror true')
3345 self.build()
3346 self.run_tests()
3347
3348 # Create a file in builddir and verify wipe command removes it
3349 filename = os.path.join(self.builddir, 'something')
3350 open(filename, 'w', encoding='utf-8').close()
3351 self.assertTrue(os.path.exists(filename))
3352 out = self.init(testdir, extra_args=['--wipe', '-Dopt4=val4'])
3353 self.assertFalse(os.path.exists(filename))
3354 self.assertRegex(out, 'opt1 val1')
3355 self.assertRegex(out, 'opt2 val2')
3356 self.assertRegex(out, 'opt3 val3')
3357 self.assertRegex(out, 'opt4 val4')
3358 #self.assertRegex(out, 'sub1:werror true')
3359 self.assertTrue(Path(self.builddir, '.gitignore').exists())
3360 self.build()
3361 self.run_tests()
3362
3363 def test_wipe_from_builddir(self):
3364 testdir = os.path.join(self.common_test_dir, '157 custom target subdir depend files')
3365 self.init(testdir)
3366 self.__reconfigure()
3367 self.init(testdir, extra_args=['--wipe'], workdir=self.builddir)
3368
3369 def test_target_construct_id_from_path(self):
3370 # This id is stable but not guessable.
3371 # The test is supposed to prevent unintentional
3372 # changes of target ID generation.
3373 target_id = Target.construct_id_from_path('some/obscure/subdir',
3374 'target-id', '@suffix')
3375 self.assertEqual('5e002d3@@target-id@suffix', target_id)
3376 target_id = Target.construct_id_from_path('subproject/foo/subdir/bar',
3377 'target2-id', '@other')
3378 self.assertEqual('81d46d1@@target2-id@other', target_id)
3379
3380 def test_introspect_projectinfo_without_configured_build(self):
3381 testfile = os.path.join(self.common_test_dir, '33 run program', 'meson.build')
3382 res = self.introspect_directory(testfile, '--projectinfo')
3383 self.assertEqual(set(res['buildsystem_files']), {'meson.build'})
3384 self.assertEqual(res['version'], 'undefined')
3385 self.assertEqual(res['descriptive_name'], 'run command')
3386 self.assertEqual(res['subprojects'], [])
3387
3388 testfile = os.path.join(self.common_test_dir, '40 options', 'meson.build')
3389 res = self.introspect_directory(testfile, '--projectinfo')
3390 self.assertEqual(set(res['buildsystem_files']), {'meson_options.txt', 'meson.build'})
3391 self.assertEqual(res['version'], 'undefined')
3392 self.assertEqual(res['descriptive_name'], 'options')
3393 self.assertEqual(res['subprojects'], [])
3394
3395 testfile = os.path.join(self.common_test_dir, '43 subproject options', 'meson.build')
3396 res = self.introspect_directory(testfile, '--projectinfo')
3397 self.assertEqual(set(res['buildsystem_files']), {'meson_options.txt', 'meson.build'})
3398 self.assertEqual(res['version'], 'undefined')
3399 self.assertEqual(res['descriptive_name'], 'suboptions')
3400 self.assertEqual(len(res['subprojects']), 1)
3401 subproject_files = {f.replace('\\', '/') for f in res['subprojects'][0]['buildsystem_files']}
3402 self.assertEqual(subproject_files, {'subprojects/subproject/meson_options.txt', 'subprojects/subproject/meson.build'})
3403 self.assertEqual(res['subprojects'][0]['name'], 'subproject')
3404 self.assertEqual(res['subprojects'][0]['version'], 'undefined')
3405 self.assertEqual(res['subprojects'][0]['descriptive_name'], 'subproject')
3406
3407 def test_introspect_projectinfo_subprojects(self):
3408 testdir = os.path.join(self.common_test_dir, '98 subproject subdir')
3409 self.init(testdir)
3410 res = self.introspect('--projectinfo')
3411 expected = {
3412 'descriptive_name': 'proj',
3413 'version': 'undefined',
3414 'license': ['unknown'],
3415 'license_files': [],
3416 'subproject_dir': 'subprojects',
3417 'subprojects': [
3418 {
3419 'descriptive_name': 'sub',
3420 'name': 'sub',
3421 'version': '1.0'
3422 },
3423 {
3424 'descriptive_name': 'sub_implicit',
3425 'name': 'sub_implicit',
3426 'version': '1.0',
3427 },
3428 {
3429 'descriptive_name': 'sub-novar',
3430 'name': 'sub_novar',
3431 'version': '1.0',
3432 },
3433 {
3434 'descriptive_name': 'sub_static',
3435 'name': 'sub_static',
3436 'version': 'undefined'
3437 },
3438 {
3439 'descriptive_name': 'subsub',
3440 'name': 'subsub',
3441 'version': 'undefined'
3442 },
3443 {
3444 'descriptive_name': 'subsubsub',
3445 'name': 'subsubsub',
3446 'version': 'undefined'
3447 },
3448 ]
3449 }
3450 res['subprojects'] = sorted(res['subprojects'], key=lambda i: i['name'])
3451 self.assertDictEqual(expected, res)
3452
3453 def test_introspection_target_subproject(self):
3454 testdir = os.path.join(self.common_test_dir, '42 subproject')
3455 self.init(testdir)
3456 res = self.introspect('--targets')
3457
3458 expected = {
3459 'sublib': 'sublib',
3460 'simpletest': 'sublib',
3461 'user': None
3462 }
3463
3464 for entry in res:
3465 name = entry['name']
3466 self.assertEqual(entry['subproject'], expected[name])
3467
3468 def test_introspection_target_native_subproject(self):
3469 # When the same subproject is built for both the build machine
3470 # (native : true) and the host machine (native : false) in a cross
3471 # build, it is configured twice. The two copies of its 'lib' target
3472 # share the same name and subproject but must have different ids.
3473 crossdir = os.path.join(self.unit_test_dir, '69 cross')
3474 # Reuse the cross test project to generate a native and a cross file
3475 # describing this machine, so the configuration below is treated as a
3476 # cross build (see test_identity_cross).
3477 self.init(crossdir, extra_args=['-Dgenerate=true'])
3478 self.meson_native_files = [os.path.join(self.builddir, "nativefile")]
3479 self.meson_cross_files = [os.path.join(self.builddir, "crossfile")]
3480
3481 self.new_builddir()
3482 testdir = os.path.join(self.unit_test_dir, '136 native subproject introspect')
3483 self.init(testdir)
3484 res = self.introspect('--targets')
3485
3486 ids = [entry['id'] for entry in res
3487 if entry['name'] == 'lib' and entry['subproject'] == 'recursive-both']
3488 self.assertEqual(len(ids), 2, 'subproject should be built for both machines')
3489 self.assertEqual(len(set(ids)), 2, 'native and non-native targets must have different ids')
3490
3491 def test_introspect_projectinfo_subproject_dir(self):
3492 testdir = os.path.join(self.common_test_dir, '75 custom subproject dir')
3493 self.init(testdir)
3494 res = self.introspect('--projectinfo')
3495
3496 self.assertEqual(res['subproject_dir'], 'custom_subproject_dir')
3497
3498 def test_introspect_projectinfo_subproject_dir_from_source(self):
3499 testfile = os.path.join(self.common_test_dir, '75 custom subproject dir', 'meson.build')
3500 res = self.introspect_directory(testfile, '--projectinfo')
3501
3502 self.assertEqual(res['subproject_dir'], 'custom_subproject_dir')
3503
3504 @skipIfNoExecutable('clang-format')
3505 def test_clang_format(self):
3506 if self.backend is not Backend.ninja:
3507 raise SkipTest(f'Clang-format is for now only supported on Ninja, not {self.backend.name}')
3508 testdir = os.path.join(self.unit_test_dir, '53 clang-format')
3509
3510 # Ensure that test project is in git even when running meson from tarball.
3511 srcdir = os.path.join(self.builddir, 'src')
3512 shutil.copytree(testdir, srcdir)
3513 git_init(srcdir)
3514 testdir = srcdir
3515 self.new_builddir()
3516
3517 testfile = os.path.join(testdir, 'prog.c')
3518 badfile = os.path.join(testdir, 'prog_orig_c')
3519 goodfile = os.path.join(testdir, 'prog_expected_c')
3520 testheader = os.path.join(testdir, 'header.h')
3521 badheader = os.path.join(testdir, 'header_orig_h')
3522 goodheader = os.path.join(testdir, 'header_expected_h')
3523 includefile = os.path.join(testdir, '.clang-format-include')
3524 try:
3525 shutil.copyfile(badfile, testfile)
3526 shutil.copyfile(badheader, testheader)
3527 self.init(testdir)
3528 self.assertNotEqual(Path(testfile).read_text(encoding='utf-8'),
3529 Path(goodfile).read_text(encoding='utf-8'))
3530 self.assertNotEqual(Path(testheader).read_text(encoding='utf-8'),
3531 Path(goodheader).read_text(encoding='utf-8'))
3532
3533 # test files are not in git so this should do nothing
3534 self.run_target('clang-format')
3535 self.assertNotEqual(Path(testfile).read_text(encoding='utf-8'),
3536 Path(goodfile).read_text(encoding='utf-8'))
3537 self.assertNotEqual(Path(testheader).read_text(encoding='utf-8'),
3538 Path(goodheader).read_text(encoding='utf-8'))
3539
3540 # Add an include file to reformat everything
3541 with open(includefile, 'w', encoding='utf-8') as f:
3542 f.write('*')
3543 self.run_target('clang-format')
3544 self.assertEqual(Path(testheader).read_text(encoding='utf-8'),
3545 Path(goodheader).read_text(encoding='utf-8'))
3546 finally:
3547 if os.path.exists(testfile):
3548 os.unlink(testfile)
3549 if os.path.exists(testheader):
3550 os.unlink(testheader)
3551 if os.path.exists(includefile):
3552 os.unlink(includefile)
3553
3554 @skipIfNoExecutable('clang-tidy')
3555 @skipIfNoExecutable('c++')
3556 @skipIf(is_osx(), 'Apple ships a broken clang-tidy that chokes on -pipe.')
3557 def test_clang_tidy(self):
3558 if self.backend is not Backend.ninja:
3559 raise SkipTest(f'Clang-tidy is for now only supported on Ninja, not {self.backend.name}')
3560 testdir = os.path.join(self.unit_test_dir, '68 clang-tidy')
3561 dummydir = os.path.join(testdir, 'dummydir.h')
3562 self.init(testdir, override_envvars={'CXX': 'c++'})
3563 out = self.run_target('clang-tidy')
3564 self.assertIn('cttest.cpp:4:20', out)
3565 self.assertNotIn(dummydir, out)
3566
3567 @skipIfNoExecutable('clang-tidy')
3568 @skipIfNoExecutable('c++')
3569 @skipIf(is_osx(), 'Apple ships a broken clang-tidy that chokes on -pipe.')
3570 def test_clang_tidy_fix(self):
3571 if self.backend is not Backend.ninja:
3572 raise SkipTest(f'Clang-tidy is for now only supported on Ninja, not {self.backend.name}')
3573 testdir = os.path.join(self.unit_test_dir, '68 clang-tidy')
3574
3575 # Ensure that test project is in git even when running meson from tarball.
3576 srcdir = os.path.join(self.builddir, 'src')
3577 shutil.copytree(testdir, srcdir)
3578 git_init(srcdir)
3579 testdir = srcdir
3580 self.new_builddir()
3581
3582 dummydir = os.path.join(testdir, 'dummydir.h')
3583 testfile = os.path.join(testdir, 'cttest.cpp')
3584 fixedfile = os.path.join(testdir, 'cttest_fixed.cpp')
3585 self.init(testdir, override_envvars={'CXX': 'c++'})
3586 # Make sure test files are different
3587 self.assertNotEqual(Path(testfile).read_text(encoding='utf-8'),
3588 Path(fixedfile).read_text(encoding='utf-8'))
3589 out = self.run_target('clang-tidy-fix')
3590 self.assertIn('cttest.cpp:4:20', out)
3591 self.assertNotIn(dummydir, out)
3592 # Make sure the test file is fixed
3593 self.assertEqual(Path(testfile).read_text(encoding='utf-8'),
3594 Path(fixedfile).read_text(encoding='utf-8'))
3595
3596 def test_identity_cross(self):
3597 testdir = os.path.join(self.unit_test_dir, '69 cross')
3598 # Do a build to generate a cross file where the host is this target
3599 # build.c_args is ignored here.
3600 self.init(testdir, extra_args=['-Dgenerate=true', '-Dc_args=-funroll-loops',
3601 '-Dbuild.c_args=-pedantic'])
3602 self.meson_native_files = [os.path.join(self.builddir, "nativefile")]
3603 self.assertTrue(os.path.exists(self.meson_native_files[0]))
3604 self.meson_cross_files = [os.path.join(self.builddir, "crossfile")]
3605 self.assertTrue(os.path.exists(self.meson_cross_files[0]))
3606 # Now verify that this is detected as cross and build options are
3607 # processed correctly
3608 self.new_builddir()
3609 self.init(testdir)
3610
3611 # Disabled for now as the introspection format needs to change to add augments.
3612 def DISABLED_test_introspect_buildoptions_without_configured_build(self):
3613 testdir = os.path.join(self.unit_test_dir, '58 introspect buildoptions')
3614 testfile = os.path.join(testdir, 'meson.build')
3615 res_nb = self.introspect_directory(testfile, ['--buildoptions'] + self.meson_args)
3616 self.init(testdir, default_args=False)
3617 res_wb = self.introspect('--buildoptions')
3618 self.maxDiff = None
3619 # XXX: These now generate in a different order, is that okay?
3620 self.assertListEqual(sorted(res_nb, key=lambda x: x['name']), sorted(res_wb, key=lambda x: x['name']))
3621
3622 def test_meson_configure_from_source_does_not_crash(self):
3623 testdir = os.path.join(self.unit_test_dir, '58 introspect buildoptions')
3624 self._run(self.mconf_command + [testdir])
3625
3626 @skip_if_not_language('rust')
3627 def test_meson_configure_srcdir(self):
3628 testdir = os.path.join(self.rust_test_dir, '20 rust and cpp')
3629 self._run(self.mconf_command + [testdir])
3630
3631 def test_introspect_buildoptions_cross_only(self):
3632 testdir = os.path.join(self.unit_test_dir, '82 cross only introspect')
3633 testfile = os.path.join(testdir, 'meson.build')
3634 res = self.introspect_directory(testfile, ['--buildoptions'] + self.meson_args)
3635 optnames = [o['name'] for o in res]
3636 self.assertIn('c_args', optnames)
3637 self.assertNotIn('build.c_args', optnames)
3638
3639 def test_introspect_json_flat(self):
3640 testdir = os.path.join(self.unit_test_dir, '56 introspection')
3641 self.init(testdir, extra_args=['-Dlayout=flat'])
3642 infodir = os.path.join(self.builddir, 'meson-info')
3643 self.assertPathExists(infodir)
3644
3645 with open(os.path.join(infodir, 'intro-targets.json'), encoding='utf-8') as fp:
3646 targets = json.load(fp)
3647
3648 for i in targets:
3649 for out in i['filename']:
3650 assert os.path.relpath(out, self.builddir).startswith('meson-out')
3651
3652 def test_introspect_json_dump(self):
3653 testdir = os.path.join(self.unit_test_dir, '56 introspection')
3654 self.init(testdir)
3655 infodir = os.path.join(self.builddir, 'meson-info')
3656 self.assertPathExists(infodir)
3657
3658 def assertKeyTypes(key_type_list, obj, strict: bool = True):
3659 for i in key_type_list:
3660 if isinstance(i[1], (list, tuple)) and None in i[1]:
3661 i = (i[0], tuple(x for x in i[1] if x is not None))
3662 if i[0] not in obj or obj[i[0]] is None:
3663 continue
3664 self.assertIn(i[0], obj)
3665 self.assertIsInstance(obj[i[0]], i[1])
3666 if strict:
3667 for k in obj.keys():
3668 found = False
3669 for i in key_type_list:
3670 if k == i[0]:
3671 found = True
3672 break
3673 self.assertTrue(found, f'Key "{k}" not in expected list')
3674
3675 root_keylist = [
3676 ('benchmarks', list),
3677 ('buildoptions', list),
3678 ('buildsystem_files', list),
3679 ('compilers', dict),
3680 ('dependencies', list),
3681 ('install_plan', dict),
3682 ('installed', dict),
3683 ('machines', dict),
3684 ('projectinfo', dict),
3685 ('targets', list),
3686 ('tests', list),
3687 ]
3688
3689 test_keylist = [
3690 ('cmd', list),
3691 ('env', dict),
3692 ('name', str),
3693 ('timeout', int),
3694 ('suite', list),
3695 ('is_parallel', bool),
3696 ('protocol', str),
3697 ('depends', list),
3698 ('workdir', (str, None)),
3699 ('priority', int),
3700 ('extra_paths', list),
3701 ]
3702
3703 buildoptions_keylist = [
3704 ('name', str),
3705 ('section', str),
3706 ('type', str),
3707 ('description', str),
3708 ('machine', str),
3709 ('choices', (list, None)),
3710 ('value', (str, int, bool, list)),
3711 ]
3712
3713 buildoptions_typelist = [
3714 ('combo', str, [('choices', list)]),
3715 ('string', str, []),
3716 ('boolean', bool, []),
3717 ('integer', int, []),
3718 ('array', list, []),
3719 ]
3720
3721 buildoptions_sections = ['core', 'backend', 'base', 'compiler', 'directory', 'user', 'test']
3722 buildoptions_machines = ['any', 'build', 'host']
3723
3724 dependencies_typelist = [
3725 ('name', str),
3726 ('type', str),
3727 ('version', str),
3728 ('compile_args', list),
3729 ('link_args', list),
3730 ('include_directories', list),
3731 ('sources', list),
3732 ('extra_files', list),
3733 ('dependencies', list),
3734 ('depends', list),
3735 ('meson_variables', list),
3736 ]
3737
3738 targets_typelist = [
3739 ('name', str),
3740 ('id', str),
3741 ('type', str),
3742 ('defined_in', str),
3743 ('filename', list),
3744 ('build_by_default', bool),
3745 ('target_sources', list),
3746 ('extra_files', list),
3747 ('subproject', (str, None)),
3748 ('dependencies', list),
3749 ('depends', list),
3750 ('install_filename', (list, None)),
3751 ('installed', bool),
3752 ('vs_module_defs', (str, None)),
3753 ('win_subsystem', (str, None)),
3754 ]
3755
3756 targets_sources_unknown_lang_typelist = [
3757 ('language', str),
3758 ('compiler', list),
3759 ('parameters', list),
3760 ('sources', list),
3761 ('generated_sources', list),
3762 ('unity_sources', (list, None)),
3763 ]
3764
3765 targets_sources_typelist = targets_sources_unknown_lang_typelist + [
3766 ('machine', str),
3767 ]
3768
3769 target_sources_linker_typelist = [
3770 ('linker', list),
3771 ('parameters', list),
3772 ]
3773
3774 # First load all files
3775 res = {}
3776 for i in root_keylist:
3777 curr = os.path.join(infodir, 'intro-{}.json'.format(i[0]))
3778 self.assertPathExists(curr)
3779 with open(curr, encoding='utf-8') as fp:
3780 res[i[0]] = json.load(fp)
3781
3782 assertKeyTypes(root_keylist, res)
3783
3784 # Match target ids to input and output files for ease of reference
3785 src_to_id = {}
3786 out_to_id = {}
3787 name_to_out = {}
3788 for i in res['targets']:
3789 print(json.dump(i, sys.stdout))
3790 out_to_id.update({os.path.relpath(out, self.builddir): i['id']
3791 for out in i['filename']})
3792 name_to_out.update({i['name']: i['filename']})
3793 for group in i['target_sources']:
3794 src_to_id.update({os.path.relpath(src, testdir): i['id']
3795 for src in group.get('sources', [])})
3796
3797 with self.subTest('Check Tests and Benchmarks'):
3798 tests_to_find = ['test case 1', 'test case 2', 'benchmark 1']
3799 deps_to_find = {'test case 1': [src_to_id['t1.cpp']],
3800 'test case 2': [src_to_id['t2.cpp'], src_to_id['t3.cpp']],
3801 'benchmark 1': [out_to_id['file2'], out_to_id['file3'], out_to_id['file4'], src_to_id['t3.cpp']]}
3802 for i in res['benchmarks'] + res['tests']:
3803 assertKeyTypes(test_keylist, i)
3804 if i['name'] in tests_to_find:
3805 tests_to_find.remove(i['name'])
3806 self.assertEqual(sorted(i['depends']),
3807 sorted(deps_to_find[i['name']]))
3808 self.assertListEqual(tests_to_find, [])
3809
3810 with self.subTest('Check buildoptions'):
3811 buildopts_to_find = {'cpp_std': 'c++11'}
3812 for i in res['buildoptions']:
3813 assertKeyTypes(buildoptions_keylist, i)
3814 valid_type = False
3815 for j in buildoptions_typelist:
3816 if i['type'] == j[0]:
3817 self.assertIsInstance(i['value'], j[1])
3818 assertKeyTypes(j[2], i, strict=False)
3819 valid_type = True
3820 break
3821
3822 self.assertIn(i['section'], buildoptions_sections)
3823 self.assertIn(i['machine'], buildoptions_machines)
3824 self.assertTrue(valid_type)
3825 if i['name'] in buildopts_to_find:
3826 self.assertEqual(i['value'], buildopts_to_find[i['name']])
3827 buildopts_to_find.pop(i['name'], None)
3828 self.assertDictEqual(buildopts_to_find, {})
3829
3830 with self.subTest('Check buildsystem_files'):
3831 bs_files = ['meson.build', 'meson_options.txt', 'sharedlib/meson.build', 'staticlib/meson.build']
3832 bs_files = [os.path.join(testdir, x) for x in bs_files]
3833 self.assertPathListEqual(list(sorted(res['buildsystem_files'])), list(sorted(bs_files)))
3834
3835 with self.subTest('Check dependencies'):
3836 dependencies_to_find = ['threads']
3837 for i in res['dependencies']:
3838 assertKeyTypes(dependencies_typelist, i)
3839 if i['name'] in dependencies_to_find:
3840 dependencies_to_find.remove(i['name'])
3841 self.assertListEqual(dependencies_to_find, [])
3842
3843 with self.subTest('Check projectinfo'):
3844 self.assertDictEqual(res['projectinfo'], {
3845 'version': '1.2.3',
3846 'license': ['unknown'],
3847 'license_files': [],
3848 'descriptive_name': 'introspection',
3849 'subproject_dir': 'subprojects',
3850 'subprojects': []
3851 })
3852
3853 with self.subTest('Check targets'):
3854 targets_to_find = {
3855 'sharedTestLib': ('shared library', True, False, 'sharedlib/meson.build',
3856 [os.path.join(testdir, 'sharedlib', 'shared.cpp')]),
3857 'staticTestLib': ('static library', True, False, 'staticlib/meson.build',
3858 [os.path.join(testdir, 'staticlib', 'static.c')]),
3859 'custom target test 1': ('custom', False, False, 'meson.build',
3860 [os.path.join(testdir, 'cp.py')]),
3861 'custom target test 2': ('custom', False, False, 'meson.build',
3862 name_to_out['custom target test 1']),
3863 'test1': ('executable', True, True, 'meson.build',
3864 [os.path.join(testdir, 't1.cpp')]),
3865 'test2': ('executable', True, False, 'meson.build',
3866 [os.path.join(testdir, 't2.cpp')]),
3867 'test3': ('executable', True, False, 'meson.build',
3868 [os.path.join(testdir, 't3.cpp')]),
3869 'custom target test 3': ('custom', False, False, 'meson.build',
3870 name_to_out['test3']),
3871 }
3872 for i in res['targets']:
3873 assertKeyTypes(targets_typelist, i)
3874 if i['name'] in targets_to_find:
3875 tgt = targets_to_find[i['name']]
3876 self.assertEqual(i['type'], tgt[0])
3877 self.assertEqual(i['build_by_default'], tgt[1])
3878 self.assertEqual(i['installed'], tgt[2])
3879 self.assertPathEqual(i['defined_in'], os.path.join(testdir, tgt[3]))
3880 targets_to_find.pop(i['name'], None)
3881 for j in i['target_sources']:
3882 if 'compiler' in j:
3883 if j['language'] == 'unknown':
3884 assertKeyTypes(targets_sources_unknown_lang_typelist, j)
3885 else:
3886 assertKeyTypes(targets_sources_typelist, j)
3887 self.assertEqual(j['sources'], [os.path.normpath(f) for f in tgt[4]])
3888 else:
3889 assertKeyTypes(target_sources_linker_typelist, j)
3890 self.assertDictEqual(targets_to_find, {})
3891
3892 def test_introspect_file_dump_equals_all(self):
3893 testdir = os.path.join(self.unit_test_dir, '56 introspection')
3894 self.init(testdir)
3895 res_all = self.introspect('--all')
3896 res_file = {}
3897
3898 root_keylist = [
3899 'benchmarks',
3900 'buildoptions',
3901 'buildsystem_files',
3902 'compilers',
3903 'dependencies',
3904 'installed',
3905 'install_plan',
3906 'machines',
3907 'projectinfo',
3908 'targets',
3909 'tests',
3910 ]
3911
3912 infodir = os.path.join(self.builddir, 'meson-info')
3913 self.assertPathExists(infodir)
3914 for i in root_keylist:
3915 curr = os.path.join(infodir, f'intro-{i}.json')
3916 self.assertPathExists(curr)
3917 with open(curr, encoding='utf-8') as fp:
3918 res_file[i] = json.load(fp)
3919
3920 self.assertEqual(res_all, res_file)
3921
3922 def test_introspect_meson_info(self):
3923 testdir = os.path.join(self.unit_test_dir, '56 introspection')
3924 introfile = os.path.join(self.builddir, 'meson-info', 'meson-info.json')
3925 self.init(testdir)
3926 self.assertPathExists(introfile)
3927 with open(introfile, encoding='utf-8') as fp:
3928 res1 = json.load(fp)
3929
3930 for i in ['meson_version', 'directories', 'introspection', 'build_files_updated', 'error']:
3931 self.assertIn(i, res1)
3932
3933 self.assertEqual(res1['error'], False)
3934 self.assertEqual(res1['build_files_updated'], True)
3935
3936 # Disabled for now as the introspection file format needs to change to have augments.
3937 def DISABLE_test_introspect_config_update(self):
3938 testdir = os.path.join(self.unit_test_dir, '56 introspection')
3939 introfile = os.path.join(self.builddir, 'meson-info', 'intro-buildoptions.json')
3940 self.init(testdir)
3941 self.assertPathExists(introfile)
3942 with open(introfile, encoding='utf-8') as fp:
3943 res1 = json.load(fp)
3944
3945 for i in res1:
3946 if i['name'] == 'cpp_std':
3947 i['value'] = 'c++14'
3948 if i['name'] == 'build.cpp_std':
3949 i['value'] = 'c++14'
3950 if i['name'] == 'buildtype':
3951 i['value'] = 'release'
3952 if i['name'] == 'optimization':
3953 i['value'] = '3'
3954 if i['name'] == 'debug':
3955 i['value'] = False
3956
3957 self.setconf('-Dcpp_std=c++14')
3958 self.setconf('-Dbuildtype=release')
3959
3960 with open(introfile, encoding='utf-8') as fp:
3961 res2 = json.load(fp)
3962
3963 self.assertListEqual(res1, res2)
3964
3965 def test_introspect_targets_from_source(self):
3966 testdir = os.path.join(self.unit_test_dir, '56 introspection')
3967 testfile = os.path.join(testdir, 'meson.build')
3968 introfile = os.path.join(self.builddir, 'meson-info', 'intro-targets.json')
3969 self.init(testdir)
3970 self.assertPathExists(introfile)
3971 with open(introfile, encoding='utf-8') as fp:
3972 res_wb = json.load(fp)
3973
3974 res_nb = self.introspect_directory(testfile, ['--targets'] + self.meson_args)
3975
3976 # Account for differences in output
3977 res_wb = [i for i in res_wb if i['type'] != 'custom']
3978 for i in res_wb:
3979 if i['id'] == 'test1@exe':
3980 i['build_by_default'] = 'unknown'
3981 i['filename'] = [os.path.relpath(x, self.builddir) for x in i['filename']]
3982 for k in ('install_filename', 'dependencies', 'win_subsystem'):
3983 if k in i:
3984 del i[k]
3985
3986 sources = []
3987 for j in i['target_sources']:
3988 sources += j.get('sources', [])
3989 i['target_sources'] = [{
3990 'language': 'unknown',
3991 'machine': 'host',
3992 'compiler': [],
3993 'parameters': [],
3994 'sources': sources,
3995 'generated_sources': []
3996 }]
3997
3998 self.maxDiff = None
3999 self.assertListEqual(res_nb, res_wb)
4000
4001 @skipIfNoExecutable('gettext')
4002 @skipIfNoExecutable('xgettext')
4003 def test_introspect_custom_target_subdir_source_path(self):
4004 '''
4005 Test that introspection data for custom targets in subdirectories
4006 correctly resolves relative string source paths. Regression test for
4007 https://github.com/mesonbuild/meson/pull/14885
4008 '''
4009 testdir = os.path.join(self.framework_test_dir, '6 gettext')
4010 self.init(testdir)
4011 intro = self.introspect('--targets')
4012 # i18n.merge_file in data/data3/meson.build passes a raw string
4013 # 'test.desktop.in' as input, which should be resolved relative
4014 # to data/data3, not to the project root.
4015 for target in intro:
4016 if target['type'] == 'custom' and 'test4.desktop' in target['filename'][0]:
4017 sources = target['target_sources'][0]['sources']
4018 expected = os.path.join(testdir, 'data/data3/test.desktop.in')
4019 self.assertEqual(len(sources), 1)
4020 self.assertPathEqual(sources[0], expected)
4021 break
4022 else:
4023 self.fail('Could not find test4.desktop custom target')
4024
4025 def test_introspect_ast_source(self):
4026 testdir = os.path.join(self.unit_test_dir, '56 introspection')
4027 testfile = os.path.join(testdir, 'meson.build')
4028 res_nb = self.introspect_directory(testfile, ['--ast'] + self.meson_args)
4029
4030 node_counter = {}
4031
4032 def accept_node(json_node):
4033 self.assertIsInstance(json_node, dict)
4034 for i in ['lineno', 'colno', 'end_lineno', 'end_colno']:
4035 self.assertIn(i, json_node)
4036 self.assertIsInstance(json_node[i], int)
4037 self.assertIn('node', json_node)
4038 n = json_node['node']
4039 self.assertIsInstance(n, str)
4040 self.assertIn(n, nodes)
4041 if n not in node_counter:
4042 node_counter[n] = 0
4043 node_counter[n] = node_counter[n] + 1
4044 for nodeDesc in nodes[n]:
4045 key = nodeDesc[0]
4046 func = nodeDesc[1]
4047 self.assertIn(key, json_node)
4048 if func is None:
4049 tp = nodeDesc[2]
4050 self.assertIsInstance(json_node[key], tp)
4051 continue
4052 func(json_node[key])
4053
4054 def accept_node_list(node_list):
4055 self.assertIsInstance(node_list, list)
4056 for i in node_list:
4057 accept_node(i)
4058
4059 def accept_kwargs(kwargs):
4060 self.assertIsInstance(kwargs, list)
4061 for i in kwargs:
4062 self.assertIn('key', i)
4063 self.assertIn('val', i)
4064 accept_node(i['key'])
4065 accept_node(i['val'])
4066
4067 nodes = {
4068 'BooleanNode': [('value', None, bool)],
4069 'IdNode': [('value', None, str)],
4070 'NumberNode': [('value', None, int)],
4071 'StringNode': [('value', None, str)],
4072 'ContinueNode': [],
4073 'BreakNode': [],
4074 'ArgumentNode': [('positional', accept_node_list), ('kwargs', accept_kwargs)],
4075 'ArrayNode': [('args', accept_node)],
4076 'DictNode': [('args', accept_node)],
4077 'EmptyNode': [],
4078 'OrNode': [('left', accept_node), ('right', accept_node)],
4079 'AndNode': [('left', accept_node), ('right', accept_node)],
4080 'ComparisonNode': [('left', accept_node), ('right', accept_node), ('ctype', None, str)],
4081 'ArithmeticNode': [('left', accept_node), ('right', accept_node), ('op', None, str)],
4082 'NotNode': [('right', accept_node)],
4083 'CodeBlockNode': [('lines', accept_node_list)],
4084 'IndexNode': [('object', accept_node), ('index', accept_node)],
4085 'MethodNode': [('object', accept_node), ('args', accept_node), ('name', None, str)],
4086 'FunctionNode': [('args', accept_node), ('name', None, str)],
4087 'AssignmentNode': [('value', accept_node), ('var_name', None, str)],
4088 'PlusAssignmentNode': [('value', accept_node), ('var_name', None, str)],
4089 'ForeachClauseNode': [('items', accept_node), ('block', accept_node), ('varnames', None, list)],
4090 'IfClauseNode': [('ifs', accept_node_list), ('else', accept_node)],
4091 'IfNode': [('condition', accept_node), ('block', accept_node)],
4092 'UMinusNode': [('right', accept_node)],
4093 'TernaryNode': [('condition', accept_node), ('true', accept_node), ('false', accept_node)],
4094 }
4095
4096 accept_node(res_nb)
4097
4098 for n, c in [('ContinueNode', 2), ('BreakNode', 1), ('NotNode', 3)]:
4099 self.assertIn(n, node_counter)
4100 self.assertEqual(node_counter[n], c)
4101
4102 def test_introspect_dependencies_from_source(self):
4103 testdir = os.path.join(self.unit_test_dir, '56 introspection')
4104 testfile = os.path.join(testdir, 'meson.build')
4105 res_nb = self.introspect_directory(testfile, ['--scan-dependencies'] + self.meson_args)
4106 expected = [
4107 {
4108 'name': 'threads',
4109 'required': True,
4110 'version': [],
4111 'has_fallback': False,
4112 'conditional': False
4113 },
4114 {
4115 'name': 'zlib',
4116 'required': False,
4117 'version': [],
4118 'has_fallback': False,
4119 'conditional': False
4120 },
4121 {
4122 'name': 'bugDep1',
4123 'required': 'unknown',
4124 'version': [],
4125 'has_fallback': False,
4126 'conditional': False
4127 },
4128 {
4129 'name': 'somethingthatdoesnotexist',
4130 'required': True,
4131 'version': ['>=1.2.3'],
4132 'has_fallback': False,
4133 'conditional': True
4134 },
4135 {
4136 'name': 'look_i_have_a_fallback',
4137 'required': True,
4138 'version': ['>=1.0.0', '<=99.9.9'],
4139 'has_fallback': True,
4140 'conditional': True
4141 },
4142 {
4143 'conditional': False,
4144 'has_fallback': False,
4145 'name': 'unknown',
4146 'required': False,
4147 'version': 'unknown'
4148 },
4149 {
4150 'conditional': False,
4151 'has_fallback': False,
4152 'name': 'unknown',
4153 'required': False,
4154 'version': 'unknown'
4155 },
4156 ]
4157 self.maxDiff = None
4158 self.assertListEqual(res_nb, expected)
4159
4160 def test_unstable_coredata(self):
4161 testdir = os.path.join(self.common_test_dir, '1 trivial')
4162 self.init(testdir)
4163 # just test that the command does not fail (e.g. because it throws an exception)
4164 self._run([*self.meson_command, 'unstable-coredata', self.builddir])
4165
4166 @skip_if_no_cmake
4167 def test_cmake_prefix_path(self):
4168 testdir = os.path.join(self.unit_test_dir, '62 cmake_prefix_path')
4169 self.init(testdir, extra_args=['-Dcmake_prefix_path=' + os.path.join(testdir, 'prefix')])
4170
4171 @skip_if_no_cmake
4172 def test_cmake_parser(self):
4173 testdir = os.path.join(self.unit_test_dir, '63 cmake parser')
4174 self.init(testdir, extra_args=['-Dcmake_prefix_path=' + os.path.join(testdir, 'prefix')])
4175
4176 def test_alias_target(self):
4177 testdir = os.path.join(self.unit_test_dir, '64 alias target')
4178 self.init(testdir)
4179 self.build()
4180 self.assertPathDoesNotExist(os.path.join(self.builddir, 'prog' + exe_suffix))
4181 self.assertPathDoesNotExist(os.path.join(self.builddir, 'hello.txt'))
4182 self.run_target('build-all')
4183 self.assertPathExists(os.path.join(self.builddir, 'prog' + exe_suffix))
4184 self.assertPathExists(os.path.join(self.builddir, 'hello.txt'))
4185 out = self.run_target('aliased-run')
4186 self.assertIn('a run target was here', out)
4187
4188 def test_configure(self):
4189 testdir = os.path.join(self.common_test_dir, '2 cpp')
4190 self.init(testdir)
4191 self._run(self.mconf_command + [self.builddir])
4192
4193 def test_configure_with_augments(self):
4194 # A list-valued augment used to crash `meson configure <builddir>`.
4195 testdir = os.path.join(self.unit_test_dir, '47 reconfigure')
4196 self.init(testdir, extra_args=['-Dsub1:c_args=-DFOO'])
4197 out = self._run(self.mconf_command + [self.builddir])
4198 self.assertIn('sub1:c_args', out)
4199 self.assertIn('[-DFOO]', out)
4200
4201 def test_summary(self):
4202 testdir = os.path.join(self.unit_test_dir, '71 summary')
4203 out = self.init(testdir, extra_args=['-Denabled_opt=enabled', f'-Dpython={sys.executable}'])
4204 expected = textwrap.dedent(r'''
4205 Some Subproject 2.0
4206
4207 string : bar
4208 integer: 1
4209 boolean: true
4210
4211 subsub undefined
4212
4213 Something: Some value
4214
4215 My Project 1.0
4216
4217 Configuration
4218 Some boolean : false
4219 Another boolean: true
4220 Some string : Hello World
4221 A list : string
4222 1
4223 true
4224 empty list :
4225 enabled_opt : enabled
4226 A number : 1
4227 yes : YES
4228 no : NO
4229 comma list : a, b, c
4230
4231 Stuff
4232 missing prog : NO
4233 existing prog : ''' + ExternalProgram('python3', [sys.executable], silent=True).path + '''
4234 missing dep : NO
4235 external dep : YES 1.2.3
4236 internal dep : YES
4237 disabler : NO
4238
4239 Plugins
4240 long comma list: alpha, alphacolor, apetag, audiofx, audioparsers, auparse,
4241 autodetect, avi
4242
4243 Subprojects (for host machine)
4244 sub : YES
4245 sub2 : NO Problem encountered: This subproject failed
4246 subsub : YES (from sub2)
4247
4248 User defined options
4249 backend : ''' + self.backend_name + '''
4250 enabled_opt : enabled
4251 libdir : lib
4252 prefix : /usr
4253 python : ''' + sys.executable + '''
4254 ''')
4255 expected_lines = expected.split('\n')[1:]
4256 out_start = out.find(expected_lines[0])
4257 out_lines = out[out_start:].split('\n')[:len(expected_lines)]
4258 for e, o in zip(expected_lines, out_lines):
4259 if e.startswith(' external dep'):
4260 self.assertRegex(o, r'^ external dep : (YES [0-9.]*|NO)$')
4261 else:
4262 self.assertEqual(o, e)
4263
4264 def test_meson_compile(self):
4265 """Test the meson compile command."""
4266
4267 def get_exe_name(basename: str) -> str:
4268 if is_windows():
4269 return f'{basename}.exe'
4270 else:
4271 return basename
4272
4273 def get_shared_lib_name(basename: str) -> str:
4274 if mesonbuild.envconfig.detect_msys2_arch():
4275 return f'lib{basename}.dll'
4276 elif is_windows():
4277 return f'{basename}.dll'
4278 elif is_cygwin():
4279 return f'cyg{basename}.dll'
4280 elif is_osx():
4281 return f'lib{basename}.dylib'
4282 else:
4283 return f'lib{basename}.so'
4284
4285 def get_static_lib_name(basename: str) -> str:
4286 return f'lib{basename}.a'
4287
4288 # Base case (no targets or additional arguments)
4289
4290 testdir = os.path.join(self.common_test_dir, '1 trivial')
4291 self.init(testdir)
4292
4293 self._run([*self.meson_command, 'compile', '-C', self.builddir])
4294 self.assertPathExists(os.path.join(self.builddir, get_exe_name('trivialprog')))
4295
4296 # `--clean`
4297
4298 self._run([*self.meson_command, 'compile', '-C', self.builddir, '--clean'])
4299 self.assertPathDoesNotExist(os.path.join(self.builddir, get_exe_name('trivialprog')))
4300
4301 # Target specified in a project with unique names
4302
4303 testdir = os.path.join(self.common_test_dir, '6 linkshared')
4304 self.init(testdir, extra_args=['--wipe'])
4305 # Multiple targets and target type specified
4306 self._run([*self.meson_command, 'compile', '-C', self.builddir, 'mylib', 'mycpplib:shared_library'])
4307 # Check that we have a shared lib, but not an executable, i.e. check that target actually worked
4308 self.assertPathExists(os.path.join(self.builddir, get_shared_lib_name('mylib')))
4309 self.assertPathDoesNotExist(os.path.join(self.builddir, get_exe_name('prog')))
4310 self.assertPathExists(os.path.join(self.builddir, get_shared_lib_name('mycpplib')))
4311 self.assertPathDoesNotExist(os.path.join(self.builddir, get_exe_name('cppprog')))
4312
4313 # Target specified in a project with non unique names
4314
4315 testdir = os.path.join(self.common_test_dir, '185 same target name')
4316 self.init(testdir, extra_args=['--wipe'])
4317 self._run([*self.meson_command, 'compile', '-C', self.builddir, './foo'])
4318 self.assertPathExists(os.path.join(self.builddir, get_static_lib_name('foo')))
4319 self._run([*self.meson_command, 'compile', '-C', self.builddir, 'sub/foo'])
4320 self.assertPathExists(os.path.join(self.builddir, 'sub', get_static_lib_name('foo')))
4321
4322 # run_target
4323
4324 testdir = os.path.join(self.common_test_dir, '51 run target')
4325 self.init(testdir, extra_args=['--wipe'])
4326 out = self._run([*self.meson_command, 'compile', '-C', self.builddir, 'py3hi'])
4327 self.assertIn('I am Python3.', out)
4328
4329 # `--$BACKEND-args`
4330
4331 testdir = os.path.join(self.common_test_dir, '1 trivial')
4332 if self.backend is Backend.ninja:
4333 self.init(testdir, extra_args=['--wipe'])
4334 # Dry run - should not create a program
4335 self._run([*self.meson_command, 'compile', '-C', self.builddir, '--ninja-args=-n'])
4336 self.assertPathDoesNotExist(os.path.join(self.builddir, get_exe_name('trivialprog')))
4337 elif self.backend is Backend.vs:
4338 self.init(testdir, extra_args=['--wipe'])
4339 self._run([*self.meson_command, 'compile', '-C', self.builddir])
4340 # Explicitly clean the target through msbuild interface
4341 self._run([*self.meson_command, 'compile', '-C', self.builddir, '--vs-args=-t:{}:Clean'.format(re.sub(r'[\%\$\@\;\.\(\)\']', '_', get_exe_name('trivialprog')))])
4342 self.assertPathDoesNotExist(os.path.join(self.builddir, get_exe_name('trivialprog')))
4343
4344 def test_spurious_reconfigure_built_dep_file(self):
4345 testdir = os.path.join(self.unit_test_dir, '73 dep files')
4346
4347 # Regression test: Spurious reconfigure was happening when build
4348 # directory is inside source directory.
4349 # See https://gitlab.freedesktop.org/gstreamer/gst-build/-/issues/85.
4350 srcdir = os.path.join(self.builddir, 'srctree')
4351 shutil.copytree(testdir, srcdir)
4352 builddir = os.path.join(srcdir, '_build')
4353 self.change_builddir(builddir)
4354
4355 self.init(srcdir)
4356 self.build()
4357
4358 # During first configure the file did not exist so no dependency should
4359 # have been set. A rebuild should not trigger a reconfigure.
4360 self.clean()
4361 out = self.build()
4362 self.assertNotIn('Project configured', out)
4363
4364 self.init(srcdir, extra_args=['--reconfigure'])
4365
4366 # During the reconfigure the file did exist, but is inside build
4367 # directory, so no dependency should have been set. A rebuild should not
4368 # trigger a reconfigure.
4369 self.clean()
4370 out = self.build()
4371 self.assertNotIn('Project configured', out)
4372
4373 def _test_junit(self, case: str) -> None:
4374 try:
4375 import lxml.etree as et
4376 except ImportError:
4377 raise SkipTest('lxml required, but not found.')
4378
4379 schema = et.XMLSchema(et.parse(str(Path(self.src_root) / 'data' / 'schema.xsd')))
4380
4381 self.init(case)
4382 self.run_tests()
4383
4384 junit = et.parse(str(Path(self.builddir) / 'meson-logs' / 'testlog.junit.xml'))
4385 try:
4386 schema.assertValid(junit)
4387 except et.DocumentInvalid as e:
4388 self.fail(e.error_log)
4389
4390 def test_junit_valid_tap(self):
4391 self._test_junit(os.path.join(self.common_test_dir, '206 tap tests'))
4392
4393 def test_junit_valid_exitcode(self):
4394 self._test_junit(os.path.join(self.common_test_dir, '41 test args'))
4395
4396 def test_junit_valid_gtest(self):
4397 self._test_junit(os.path.join(self.framework_test_dir, '2 gtest'))
4398
4399 def test_link_language_linker(self):
4400 # TODO: there should be some way to query how we're linking things
4401 # without resorting to reading the ninja.build file
4402 if self.backend is not Backend.ninja:
4403 raise SkipTest('This test reads the ninja file')
4404
4405 testdir = os.path.join(self.common_test_dir, '225 link language')
4406 self.init(testdir)
4407
4408 build_ninja = os.path.join(self.builddir, 'build.ninja')
4409 with open(build_ninja, encoding='utf-8') as f:
4410 contents = f.read()
4411
4412 self.assertRegex(contents, r'build main(\.exe)?.*: c_LINKER')
4413 self.assertRegex(contents, r'build (lib|cyg)?mylib.*: c_LINKER')
4414
4415 def test_commands_documented(self):
4416 '''
4417 Test that all listed meson commands are documented in Commands.md.
4418 '''
4419
4420 # The docs directory is not in release tarballs.
4421 if not os.path.isdir('docs'):
4422 raise SkipTest('Doc directory does not exist.')
4423 doc_path = 'docs/markdown/Commands.md'
4424
4425 md = None
4426 with open(doc_path, encoding='utf-8') as f:
4427 md = f.read()
4428 self.assertIsNotNone(md)
4429
4430 ## Get command sections
4431
4432 section_pattern = re.compile(r'^### (.+)$', re.MULTILINE)
4433 md_command_section_matches = [i for i in section_pattern.finditer(md)]
4434 md_command_sections = dict()
4435 for i, s in enumerate(md_command_section_matches):
4436 section_end = len(md) if i == len(md_command_section_matches) - 1 else md_command_section_matches[i + 1].start()
4437 md_command_sections[s.group(1)] = (s.start(), section_end)
4438
4439 ## Validate commands
4440
4441 md_commands = {k for k,v in md_command_sections.items()}
4442 help_output = self._run(self.meson_command + ['--help'])
4443 # Python's argument parser might put the command list to its own line. Or it might not.
4444 self.assertTrue(help_output.startswith('usage: '))
4445 lines = help_output.split('\n')
4446 line1 = lines[0]
4447 line2 = lines[1]
4448 if '{' in line1:
4449 cmndline = line1
4450 else:
4451 self.assertIn('{', line2)
4452 cmndline = line2
4453 cmndstr = cmndline.split('{')[1]
4454 self.assertIn('}', cmndstr)
4455 help_commands = set(cmndstr.split('}')[0].split(','))
4456 help_commands.remove('fmt') # Remove the alias
4457 self.assertTrue(len(help_commands) > 0, 'Must detect some command names.')
4458
4459 self.assertEqual(md_commands | {'help'}, help_commands, f'Doc file: `{doc_path}`')
4460
4461 ## Validate that each section has proper placeholders
4462
4463 def get_data_pattern(command):
4464 return re.compile(
4465 r'{{ ' + command + r'_usage.inc }}[\r\n]'
4466 r'.*?'
4467 r'{{ ' + command + r'_arguments.inc }}[\r\n]',
4468 flags = re.MULTILINE|re.DOTALL)
4469
4470 for command in md_commands:
4471 m = get_data_pattern(command).search(md, pos=md_command_sections[command][0], endpos=md_command_sections[command][1])
4472 self.assertIsNotNone(m, f'Command `{command}` is missing placeholders for dynamic data. Doc file: `{doc_path}`')
4473
4474 def _check_coverage_files(self, types=('text', 'xml', 'html')):
4475 covdir = Path(self.builddir) / 'meson-logs'
4476 files = []
4477 if 'text' in types:
4478 files.append('coverage.txt')
4479 if 'xml' in types:
4480 files.append('coverage.xml')
4481 if 'html' in types:
4482 files.append('coveragereport/index.html')
4483 for f in files:
4484 self.assertTrue((covdir / f).is_file(), msg=f'{f} is not a file')
4485
4486 def test_coverage(self):
4487 if mesonbuild.envconfig.detect_msys2_arch():
4488 raise SkipTest('Skipped due to problems with coverage on MSYS2')
4489 gcovr_exe, gcovr_new_rootdir = mesonbuild.tooldetect.detect_gcovr()
4490 if not gcovr_exe:
4491 raise SkipTest('gcovr not found, or too old')
4492 testdir = os.path.join(self.common_test_dir, '1 trivial')
4493 env = get_fake_env(testdir, self.builddir, self.prefix)
4494 cc = detect_c_compiler(env, MachineChoice.HOST)
4495 if cc.get_id() == 'clang':
4496 if not mesonbuild.tooldetect.detect_llvm_cov():
4497 raise SkipTest('llvm-cov not found')
4498 if cc.get_id() == 'msvc':
4499 raise SkipTest('Test only applies to non-MSVC compilers')
4500 self.init(testdir, extra_args=['-Db_coverage=true'])
4501 self.build()
4502 self.run_tests()
4503 self.run_target('coverage')
4504 self._check_coverage_files()
4505
4506 def test_coverage_complex(self):
4507 if mesonbuild.envconfig.detect_msys2_arch():
4508 raise SkipTest('Skipped due to problems with coverage on MSYS2')
4509 gcovr_exe, gcovr_new_rootdir = mesonbuild.tooldetect.detect_gcovr()
4510 if not gcovr_exe:
4511 raise SkipTest('gcovr not found, or too old')
4512 testdir = os.path.join(self.common_test_dir, '105 generatorcustom')
4513 env = get_fake_env(testdir, self.builddir, self.prefix)
4514 cc = detect_c_compiler(env, MachineChoice.HOST)
4515 if cc.get_id() == 'clang':
4516 if not mesonbuild.tooldetect.detect_llvm_cov():
4517 raise SkipTest('llvm-cov not found')
4518 if cc.get_id() == 'msvc':
4519 raise SkipTest('Test only applies to non-MSVC compilers')
4520 self.init(testdir, extra_args=['-Db_coverage=true'])
4521 self.build()
4522 self.run_tests()
4523 self.run_target('coverage')
4524 self._check_coverage_files()
4525
4526 def test_coverage_html(self):
4527 if mesonbuild.envconfig.detect_msys2_arch():
4528 raise SkipTest('Skipped due to problems with coverage on MSYS2')
4529 gcovr_exe, gcovr_new_rootdir = mesonbuild.tooldetect.detect_gcovr()
4530 if not gcovr_exe:
4531 raise SkipTest('gcovr not found, or too old')
4532 testdir = os.path.join(self.common_test_dir, '1 trivial')
4533 env = get_fake_env(testdir, self.builddir, self.prefix)
4534 cc = detect_c_compiler(env, MachineChoice.HOST)
4535 if cc.get_id() == 'clang':
4536 if not mesonbuild.tooldetect.detect_llvm_cov():
4537 raise SkipTest('llvm-cov not found')
4538 if cc.get_id() == 'msvc':
4539 raise SkipTest('Test only applies to non-MSVC compilers')
4540 self.init(testdir, extra_args=['-Db_coverage=true'])
4541 self.build()
4542 self.run_tests()
4543 self.run_target('coverage-html')
4544 self._check_coverage_files(['html'])
4545
4546 def test_coverage_text(self):
4547 if mesonbuild.envconfig.detect_msys2_arch():
4548 raise SkipTest('Skipped due to problems with coverage on MSYS2')
4549 gcovr_exe, gcovr_new_rootdir = mesonbuild.tooldetect.detect_gcovr()
4550 if not gcovr_exe:
4551 raise SkipTest('gcovr not found, or too old')
4552 testdir = os.path.join(self.common_test_dir, '1 trivial')
4553 env = get_fake_env(testdir, self.builddir, self.prefix)
4554 cc = detect_c_compiler(env, MachineChoice.HOST)
4555 if cc.get_id() == 'clang':
4556 if not mesonbuild.tooldetect.detect_llvm_cov():
4557 raise SkipTest('llvm-cov not found')
4558 if cc.get_id() == 'msvc':
4559 raise SkipTest('Test only applies to non-MSVC compilers')
4560 self.init(testdir, extra_args=['-Db_coverage=true'])
4561 self.build()
4562 self.run_tests()
4563 self.run_target('coverage-text')
4564 self._check_coverage_files(['text'])
4565
4566 def test_coverage_xml(self):
4567 if mesonbuild.envconfig.detect_msys2_arch():
4568 raise SkipTest('Skipped due to problems with coverage on MSYS2')
4569 gcovr_exe, gcovr_new_rootdir = mesonbuild.tooldetect.detect_gcovr()
4570 if not gcovr_exe:
4571 raise SkipTest('gcovr not found, or too old')
4572 testdir = os.path.join(self.common_test_dir, '1 trivial')
4573 env = get_fake_env(testdir, self.builddir, self.prefix)
4574 cc = detect_c_compiler(env, MachineChoice.HOST)
4575 if cc.get_id() == 'clang':
4576 if not mesonbuild.tooldetect.detect_llvm_cov():
4577 raise SkipTest('llvm-cov not found')
4578 if cc.get_id() == 'msvc':
4579 raise SkipTest('Test only applies to non-MSVC compilers')
4580 self.init(testdir, extra_args=['-Db_coverage=true'])
4581 self.build()
4582 self.run_tests()
4583 self.run_target('coverage-xml')
4584 self._check_coverage_files(['xml'])
4585
4586 def test_coverage_escaping(self):
4587 if mesonbuild.envconfig.detect_msys2_arch():
4588 raise SkipTest('Skipped due to problems with coverage on MSYS2')
4589 gcovr_exe, gcovr_new_rootdir = mesonbuild.tooldetect.detect_gcovr()
4590 if not gcovr_exe:
4591 raise SkipTest('gcovr not found, or too old')
4592 testdir = os.path.join(self.common_test_dir, '243 escape++')
4593 env = get_fake_env(testdir, self.builddir, self.prefix)
4594 cc = detect_c_compiler(env, MachineChoice.HOST)
4595 if cc.get_id() == 'clang':
4596 if not mesonbuild.tooldetect.detect_llvm_cov():
4597 raise SkipTest('llvm-cov not found')
4598 if cc.get_id() == 'msvc':
4599 raise SkipTest('Test only applies to non-MSVC compilers')
4600 self.init(testdir, extra_args=['-Db_coverage=true'])
4601 self.build()
4602 self.run_tests()
4603 self.run_target('coverage')
4604 self._check_coverage_files()
4605
4606 def test_cross_file_constants(self):
4607 crossfile1 = UNIT_MACHINEFILE_DIR / 'constant1.txt'
4608 crossfile2 = UNIT_MACHINEFILE_DIR / 'constant2.txt'
4609 values = mesonbuild.machinefile.parse_machine_files([crossfile1,
4610 crossfile2],
4611 self.builddir)
4612 self.assertEqual(values['binaries']['c'], '/toolchain/gcc')
4613 self.assertEqual(values['properties']['c_args'],
4614 ['--sysroot=/toolchain/sysroot', '-DSOMETHING'])
4615 self.assertEqual(values['properties']['cpp_args'],
4616 ['--sysroot=/toolchain/sysroot', '-DSOMETHING', '-DSOMETHING_ELSE'])
4617 self.assertEqual(values['properties']['rel_to_src'], os.path.join(self.builddir, 'tool'))
4618 self.assertEqual(values['properties']['rel_to_file'], os.path.join(os.path.dirname(crossfile2), 'tool'))
4619 self.assertEqual(values['properties']['no_escaping'], os.path.join(f'@{os.path.dirname(crossfile2)}@', 'tool'))
4620
4621 @skipIf(is_windows(), 'Directory cleanup fails for some reason')
4622 def test_wrap_git(self):
4623 with tempfile.TemporaryDirectory() as tmpdir:
4624 srcdir = os.path.join(tmpdir, 'src')
4625 shutil.copytree(os.path.join(self.unit_test_dir, '80 wrap-git'), srcdir)
4626 upstream = os.path.join(srcdir, 'subprojects', 'wrap_git_upstream')
4627 upstream_uri = Path(upstream).as_uri()
4628 git_init(upstream)
4629 with open(os.path.join(srcdir, 'subprojects', 'wrap_git.wrap'), 'w', encoding='utf-8') as f:
4630 f.write(textwrap.dedent('''
4631 [wrap-git]
4632 url = {}
4633 patch_directory = wrap_git_builddef
4634 revision = master
4635 '''.format(upstream_uri)))
4636 out = self.init(srcdir)
4637 self.build()
4638 self.run_tests()
4639
4640 # Make sure the warning does not occur on the first init.
4641 out_of_date_warning = 'revision may be out of date'
4642 self.assertNotIn(out_of_date_warning, out)
4643
4644 # Change the wrap's revisions, reconfigure, and make sure it does
4645 # warn on the reconfigure.
4646 with open(os.path.join(srcdir, 'subprojects', 'wrap_git.wrap'), 'w', encoding='utf-8') as f:
4647 f.write(textwrap.dedent('''
4648 [wrap-git]
4649 url = {}
4650 patch_directory = wrap_git_builddef
4651 revision = not-master
4652 '''.format(upstream_uri)))
4653 out = self.init(srcdir, extra_args='--reconfigure')
4654 self.assertIn(out_of_date_warning, out)
4655
4656 def test_extract_objects_custom_target_no_warning(self):
4657 testdir = os.path.join(self.common_test_dir, '22 object extraction')
4658
4659 out = self.init(testdir)
4660 self.assertNotRegex(out, "WARNING:.*can't be converted to File object")
4661
4662 def test_multi_output_custom_target_no_warning(self):
4663 testdir = os.path.join(self.common_test_dir, '228 custom_target source')
4664
4665 out = self.init(testdir)
4666 self.assertNotRegex(out, 'WARNING:.*Using the first one.')
4667 self.build()
4668 self.run_tests()
4669
4670 def test_custom_target_index_as_test_prereq(self):
4671 if self.backend is not Backend.ninja:
4672 raise SkipTest('ninja backend needed for "meson test" to build test dependencies')
4673
4674 testdir = os.path.join(self.unit_test_dir, '132 custom target index test')
4675 self.init(testdir)
4676 self.run_tests()
4677
4678 @skipUnless(is_linux() and (re.search('^i.86$|^x86$|^x64$|^x86_64$|^amd64$', platform.processor()) is not None),
4679 'Requires ASM compiler for x86 or x86_64 platform currently only available on Linux CI runners')
4680 def test_nostdlib(self):
4681 testdir = os.path.join(self.unit_test_dir, '77 nostdlib')
4682 machinefile = os.path.join(self.builddir, 'machine.txt')
4683 with open(machinefile, 'w', encoding='utf-8') as f:
4684 f.write(textwrap.dedent('''
4685 [properties]
4686 c_stdlib = 'mylibc'
4687 '''))
4688
4689 # Test native C stdlib
4690 self.meson_native_files = [machinefile]
4691 self.init(testdir)
4692 self.build()
4693
4694 # Test cross C stdlib
4695 self.new_builddir()
4696 self.meson_native_files = []
4697 self.meson_cross_files = [machinefile]
4698 self.init(testdir)
4699 self.build()
4700
4701 def test_meson_version_compare(self):
4702 testdir = os.path.join(self.unit_test_dir, '81 meson version compare')
4703 out = self.init(testdir)
4704 self.assertNotRegex(out, r'WARNING')
4705
4706 def test_wrap_redirect(self):
4707 redirect_wrap = os.path.join(self.builddir, 'redirect.wrap')
4708 real_wrap = os.path.join(self.builddir, 'foo/subprojects/real.wrap')
4709 os.makedirs(os.path.dirname(real_wrap))
4710
4711 # Invalid redirect, filename must have .wrap extension
4712 with open(redirect_wrap, 'w', encoding='utf-8') as f:
4713 f.write(textwrap.dedent('''
4714 [wrap-redirect]
4715 filename = foo/subprojects/real.wrapper
4716 '''))
4717 with self.assertRaisesRegex(WrapException, "wrap-redirect filename 'foo/subprojects/real.wrapper' must be a .wrap file"):
4718 PackageDefinition.from_wrap_file(redirect_wrap)
4719
4720 # Invalid redirect, filename cannot be in parent directory
4721 with open(redirect_wrap, 'w', encoding='utf-8') as f:
4722 f.write(textwrap.dedent('''
4723 [wrap-redirect]
4724 filename = ../real.wrap
4725 '''))
4726 with self.assertRaisesRegex(WrapException, "wrap-redirect filename '../real.wrap' cannot contain '..'"):
4727 PackageDefinition.from_wrap_file(redirect_wrap)
4728
4729 # Invalid redirect, filename must be in foo/subprojects/real.wrap
4730 with open(redirect_wrap, 'w', encoding='utf-8') as f:
4731 f.write(textwrap.dedent('''
4732 [wrap-redirect]
4733 filename = foo/real.wrap
4734 '''))
4735 with self.assertRaisesRegex(WrapException, "wrap-redirect filename 'foo/real.wrap' must be in the form foo/subprojects/bar.wrap"):
4736 PackageDefinition.from_wrap_file(redirect_wrap)
4737
4738 # Correct redirect
4739 with open(redirect_wrap, 'w', encoding='utf-8') as f:
4740 f.write(textwrap.dedent('''
4741 [wrap-redirect]
4742 filename = foo/subprojects/real.wrap
4743 '''))
4744 with open(real_wrap, 'w', encoding='utf-8') as f:
4745 f.write(textwrap.dedent('''
4746 [wrap-git]
4747 url = http://invalid
4748 '''))
4749 wrap = PackageDefinition.from_wrap_file(redirect_wrap)
4750 self.assertEqual(wrap.get('url'), 'http://invalid')
4751
4752 @skip_if_no_cmake
4753 def test_nested_cmake_rebuild(self) -> None:
4754 # This checks a bug where if a non-meson project is used as a third
4755 # level (or deeper) subproject it doesn't cause a rebuild if the build
4756 # files for that project are changed
4757 testdir = os.path.join(self.unit_test_dir, '84 nested subproject regenerate depends')
4758 cmakefile = Path(testdir) / 'subprojects' / 'sub2' / 'CMakeLists.txt'
4759 self.init(testdir)
4760 self.build()
4761 with cmakefile.open('a', encoding='utf-8'):
4762 os.utime(str(cmakefile))
4763 self.assertReconfiguredBuildIsNoop()
4764
4765 def test_version_file(self):
4766 srcdir = os.path.join(self.common_test_dir, '2 cpp')
4767 self.init(srcdir)
4768 projinfo = self.introspect('--projectinfo')
4769 self.assertEqual(projinfo['version'], '1.0.0')
4770
4771 def test_cflags_cppflags(self):
4772 envs = {'CPPFLAGS': '-DCPPFLAG',
4773 'CFLAGS': '-DCFLAG',
4774 'CXXFLAGS': '-DCXXFLAG'}
4775 srcdir = os.path.join(self.unit_test_dir, '88 multiple envvars')
4776 self.init(srcdir, override_envvars=envs)
4777 self.build()
4778
4779 def test_build_b_options(self) -> None:
4780 # Currently (0.57) these do nothing, but they've always been allowed
4781 srcdir = os.path.join(self.common_test_dir, '2 cpp')
4782 self.init(srcdir, extra_args=['-Dbuild.b_lto=true'])
4783
4784 def test_install_skip_subprojects(self):
4785 testdir = os.path.join(self.unit_test_dir, '91 install skip subprojects')
4786 self.init(testdir)
4787 self.build()
4788
4789 main_expected = [
4790 '',
4791 'share',
4792 'include',
4793 'foo',
4794 'bin',
4795 'share/foo',
4796 'share/foo/foo.dat',
4797 'include/foo.h',
4798 'foo/foofile',
4799 'bin/foo' + exe_suffix,
4800 ]
4801 bar_expected = [
4802 'bar',
4803 'share/bar',
4804 'share/bar/bar.dat',
4805 'include/bar.h',
4806 'bin/bar' + exe_suffix,
4807 'bar/barfile'
4808 ]
4809 env = get_fake_env(testdir, self.builddir, self.prefix)
4810 cc = detect_c_compiler(env, MachineChoice.HOST)
4811 if cc.get_argument_syntax() == 'msvc':
4812 main_expected.append('bin/foo.pdb')
4813 bar_expected.append('bin/bar.pdb')
4814 prefix = destdir_join(self.installdir, self.prefix)
4815 main_expected = [Path(prefix, p) for p in main_expected]
4816 bar_expected = [Path(prefix, p) for p in bar_expected]
4817 all_expected = main_expected + bar_expected
4818
4819 def check_installed_files(extra_args, expected):
4820 args = ['install', '--destdir', self.installdir] + extra_args
4821 self._run(self.meson_command + args, workdir=self.builddir)
4822 all_files = [p for p in Path(self.installdir).rglob('*')]
4823 self.assertEqual(sorted(expected), sorted(all_files))
4824 windows_proof_rmtree(self.installdir)
4825
4826 check_installed_files([], all_expected)
4827 check_installed_files(['--skip-subprojects'], main_expected)
4828 check_installed_files(['--skip-subprojects', 'bar'], main_expected)
4829 check_installed_files(['--skip-subprojects', 'another'], all_expected)
4830
4831 def test_adding_subproject_to_configure_project(self) -> None:
4832 srcdir = os.path.join(self.unit_test_dir, '92 new subproject in configured project')
4833 self.init(srcdir)
4834 self.build()
4835 self.setconf('-Duse-sub=true')
4836 self.build()
4837
4838 def test_devenv(self):
4839 testdir = os.path.join(self.unit_test_dir, '90 devenv')
4840 self.init(testdir)
4841 self.build()
4842
4843 cmd = self.meson_command + ['devenv', '-C', self.builddir]
4844 script = os.path.join(testdir, 'test-devenv.py')
4845 app = os.path.join(self.builddir, 'app')
4846 self._run(cmd + python_command + [script])
4847 self.assertEqual('This is text.', self._run(cmd + [app]).strip())
4848
4849 cmd = self.meson_command + ['devenv', '-C', self.builddir, '--dump']
4850 o = self._run(cmd)
4851 expected = os.pathsep.join(['/prefix', '$TEST_C', '/suffix'])
4852 self.assertIn(f'TEST_C="{expected}"', o)
4853 self.assertIn('export TEST_C', o)
4854
4855 cmd = self.meson_command + ['devenv', '-C', self.builddir, '--dump', '--dump-format', 'sh']
4856 o = self._run(cmd)
4857 expected = os.pathsep.join(['/prefix', '$TEST_C', '/suffix'])
4858 self.assertIn(f'TEST_C="{expected}"', o)
4859 self.assertNotIn('export', o)
4860
4861 cmd = self.meson_command + ['devenv', '-C', self.builddir, '--dump', '--dump-format', 'vscode']
4862 o = self._run(cmd)
4863 expected = os.pathsep.join(['/prefix', '/suffix'])
4864 self.assertIn(f'TEST_C="{expected}"', o)
4865 self.assertNotIn('export', o)
4866
4867 fname = os.path.join(self.builddir, 'dump.env')
4868 cmd = self.meson_command + ['devenv', '-C', self.builddir, '--dump', fname]
4869 o = self._run(cmd)
4870 self.assertEqual(o, '')
4871 o = Path(fname).read_text(encoding='utf-8')
4872 expected = os.pathsep.join(['/prefix', '$TEST_C', '/suffix'])
4873 self.assertIn(f'TEST_C="{expected}"', o)
4874 self.assertIn('export TEST_C', o)
4875
4876 cmd = self.meson_command + ['devenv', '-C', self.builddir] + python_command + ['-c', 'import sys; sys.exit(42)']
4877 result = subprocess.run(cmd, encoding='utf-8')
4878 self.assertEqual(result.returncode, 42)
4879
4880 @skipIfNoExecutable('clang-format')
4881 def test_clang_format_check(self):
4882 if self.backend is not Backend.ninja:
4883 raise SkipTest(f'Skipping clang-format tests with {self.backend.name} backend')
4884
4885 testdir = os.path.join(self.unit_test_dir, '93 clangformat')
4886 newdir = os.path.join(self.builddir, 'testdir')
4887 shutil.copytree(testdir, newdir)
4888 self.new_builddir()
4889 self.init(newdir)
4890
4891 # Should reformat 1 file but not return error
4892 output = self.build('clang-format')
4893 self.assertEqual(1, output.count('File reformatted:'))
4894
4895 # Reset source tree then try again with clang-format-check, it should
4896 # return an error code this time.
4897 windows_proof_rmtree(newdir)
4898 shutil.copytree(testdir, newdir)
4899 with self.assertRaises(subprocess.CalledProcessError):
4900 output = self.build('clang-format-check')
4901 self.assertEqual(1, output.count('File reformatted:'))
4902
4903 # The check format should not touch any files. Thus
4904 # running format again has some work to do.
4905 output = self.build('clang-format')
4906 self.assertEqual(1, output.count('File reformatted:'))
4907 self.build('clang-format-check')
4908
4909 def test_custom_target_implicit_include(self):
4910 testdir = os.path.join(self.unit_test_dir, '94 custominc')
4911 self.init(testdir)
4912 self.build()
4913 compdb = self.get_compdb()
4914 matches = 0
4915 for c in compdb:
4916 if 'prog.c' in c['file']:
4917 self.assertNotIn('easytogrepfor', c['command'])
4918 matches += 1
4919 self.assertEqual(matches, 1)
4920 matches = 0
4921 for c in compdb:
4922 if 'prog2.c' in c['file']:
4923 self.assertIn('easytogrepfor', c['command'])
4924 matches += 1
4925 self.assertEqual(matches, 1)
4926
4927 def test_env_flags_to_linker(self) -> None:
4928 # Compilers that act as drivers should add their compiler flags to the
4929 # linker, those that do not shouldn't
4930 with mock.patch.dict(os.environ, {'CFLAGS': '-DCFLAG', 'LDFLAGS': '-flto'}):
4931 env = get_fake_env()
4932
4933 # Get the compiler so we know which compiler class to mock.
4934 cc = detect_compiler_for(env, 'c', MachineChoice.HOST, True, '')
4935
4936 # C does have a separate linking step. It can be done through the compiler
4937 # driver or not; act accordingly.
4938 if cc.USED_FOR_SEPARATE_LINKING_STEP:
4939 link_args = env.coredata.get_external_link_args(cc.for_machine, cc.language)
4940 self.assertEqual(sorted(link_args), sorted(['-DCFLAG', '-flto']))
4941 else:
4942 link_args = env.coredata.get_external_link_args(cc.for_machine, cc.language)
4943 self.assertEqual(sorted(link_args), sorted(['-flto']))
4944
4945 def test_install_tag(self) -> None:
4946 testdir = os.path.join(self.unit_test_dir, '98 install all targets')
4947 self.init(testdir)
4948 self.build()
4949
4950 env = get_fake_env(testdir, self.builddir, self.prefix)
4951 cc = detect_c_compiler(env, MachineChoice.HOST)
4952
4953 def shared_lib_name(name):
4954 if cc.get_id() in {'msvc', 'clang-cl'}:
4955 return f'bin/{name}.dll'
4956 elif is_windows():
4957 return f'bin/lib{name}.dll'
4958 elif is_cygwin():
4959 return f'bin/cyg{name}.dll'
4960 elif is_osx():
4961 return f'lib/lib{name}.dylib'
4962 return f'lib/lib{name}.so'
4963
4964 def exe_name(name):
4965 if is_windows() or is_cygwin():
4966 return f'{name}.exe'
4967 return name
4968
4969 installpath = Path(self.installdir)
4970
4971 expected_common = {
4972 installpath,
4973 Path(installpath, 'usr'),
4974 }
4975
4976 expected_devel = expected_common | {
4977 Path(installpath, 'usr/include'),
4978 Path(installpath, 'usr/include/bar-devel.h'),
4979 Path(installpath, 'usr/include/bar2-devel.h'),
4980 Path(installpath, 'usr/include/foo1-devel.h'),
4981 Path(installpath, 'usr/include/foo2-devel.h'),
4982 Path(installpath, 'usr/include/foo3-devel.h'),
4983 Path(installpath, 'usr/include/out-devel.h'),
4984 Path(installpath, 'usr/lib'),
4985 Path(installpath, 'usr/lib/libstatic.a'),
4986 Path(installpath, 'usr/lib/libboth.a'),
4987 Path(installpath, 'usr/lib/libboth2.a'),
4988 Path(installpath, 'usr/include/ct-header1.h'),
4989 Path(installpath, 'usr/include/ct-header3.h'),
4990 Path(installpath, 'usr/include/subdir-devel'),
4991 Path(installpath, 'usr/include/custom_files'),
4992 Path(installpath, 'usr/include/custom_files/data.txt'),
4993 }
4994
4995 if cc.get_id() in {'msvc', 'clang-cl'}:
4996 expected_devel |= {
4997 Path(installpath, 'usr/bin'),
4998 Path(installpath, 'usr/bin/app.pdb'),
4999 Path(installpath, 'usr/bin/app2.pdb'),
5000 Path(installpath, 'usr/bin/both.pdb'),
5001 Path(installpath, 'usr/bin/both2.pdb'),
5002 Path(installpath, 'usr/bin/bothcustom.pdb'),
5003 Path(installpath, 'usr/bin/shared.pdb'),
5004 Path(installpath, 'usr/bin/versioned_shared-1.pdb'),
5005 Path(installpath, 'usr/lib/both.lib'),
5006 Path(installpath, 'usr/lib/both2.lib'),
5007 Path(installpath, 'usr/lib/bothcustom.lib'),
5008 Path(installpath, 'usr/lib/shared.lib'),
5009 Path(installpath, 'usr/lib/versioned_shared.lib'),
5010 Path(installpath, 'usr/otherbin'),
5011 Path(installpath, 'usr/otherbin/app-otherdir.pdb'),
5012 }
5013 elif is_windows() or is_cygwin():
5014 expected_devel |= {
5015 Path(installpath, 'usr/lib/libboth.dll.a'),
5016 Path(installpath, 'usr/lib/libboth2.dll.a'),
5017 Path(installpath, 'usr/lib/libshared.dll.a'),
5018 Path(installpath, 'usr/lib/libbothcustom.dll.a'),
5019 Path(installpath, 'usr/lib/libversioned_shared.dll.a'),
5020 }
5021 else:
5022 expected_devel |= {
5023 Path(installpath, 'usr/' + shared_lib_name('versioned_shared')),
5024 }
5025
5026 expected_runtime = expected_common | {
5027 Path(installpath, 'usr/bin'),
5028 Path(installpath, 'usr/bin/' + exe_name('app')),
5029 Path(installpath, 'usr/otherbin'),
5030 Path(installpath, 'usr/otherbin/' + exe_name('app-otherdir')),
5031 Path(installpath, 'usr/bin/' + exe_name('app2')),
5032 Path(installpath, 'usr/' + shared_lib_name('shared')),
5033 Path(installpath, 'usr/' + shared_lib_name('both')),
5034 Path(installpath, 'usr/' + shared_lib_name('both2')),
5035 }
5036
5037 if is_windows() or is_cygwin():
5038 expected_runtime |= {
5039 Path(installpath, 'usr/' + shared_lib_name('versioned_shared-1')),
5040 }
5041 elif is_osx():
5042 expected_runtime |= {
5043 Path(installpath, 'usr/' + shared_lib_name('versioned_shared.1')),
5044 }
5045 else:
5046 expected_runtime |= {
5047 Path(installpath, 'usr/' + shared_lib_name('versioned_shared') + '.1'),
5048 Path(installpath, 'usr/' + shared_lib_name('versioned_shared') + '.1.2.3'),
5049 }
5050
5051 expected_custom = expected_common | {
5052 Path(installpath, 'usr/share'),
5053 Path(installpath, 'usr/share/bar-custom.txt'),
5054 Path(installpath, 'usr/share/foo-custom.h'),
5055 Path(installpath, 'usr/share/out1-custom.txt'),
5056 Path(installpath, 'usr/share/out2-custom.txt'),
5057 Path(installpath, 'usr/share/out3-custom.txt'),
5058 Path(installpath, 'usr/share/custom_files'),
5059 Path(installpath, 'usr/share/custom_files/data.txt'),
5060 Path(installpath, 'usr/share/excludes'),
5061 Path(installpath, 'usr/share/excludes/installed.txt'),
5062 Path(installpath, 'usr/lib'),
5063 Path(installpath, 'usr/lib/libbothcustom.a'),
5064 Path(installpath, 'usr/' + shared_lib_name('bothcustom')),
5065 }
5066
5067 if is_windows() or is_cygwin():
5068 expected_custom |= {Path(installpath, 'usr/bin')}
5069 else:
5070 expected_runtime |= {Path(installpath, 'usr/lib')}
5071
5072 expected_runtime_custom = expected_runtime | expected_custom
5073
5074 expected_all = expected_devel | expected_runtime | expected_custom | {
5075 Path(installpath, 'usr/share/foo-notag.h'),
5076 Path(installpath, 'usr/share/bar-notag.txt'),
5077 Path(installpath, 'usr/share/out1-notag.txt'),
5078 Path(installpath, 'usr/share/out2-notag.txt'),
5079 Path(installpath, 'usr/share/out3-notag.txt'),
5080 Path(installpath, 'usr/share/foo2.h'),
5081 Path(installpath, 'usr/share/out1.txt'),
5082 Path(installpath, 'usr/share/out2.txt'),
5083 Path(installpath, 'usr/share/subproject'),
5084 Path(installpath, 'usr/share/subproject/aaa.txt'),
5085 Path(installpath, 'usr/share/subproject/bbb.txt'),
5086 }
5087
5088 def do_install(tags, expected_files, expected_scripts):
5089 cmd = self.meson_command + ['install', '--dry-run', '--destdir', self.installdir]
5090 cmd += ['--tags', tags] if tags else []
5091 stdout = self._run(cmd, workdir=self.builddir)
5092 installed = self.read_install_logs()
5093 self.assertEqual(sorted(expected_files), sorted(installed))
5094 self.assertEqual(expected_scripts, stdout.count('Running custom install script'))
5095
5096 do_install('devel', expected_devel, 0)
5097 do_install('runtime', expected_runtime, 0)
5098 do_install('custom', expected_custom, 1)
5099 do_install('runtime,custom', expected_runtime_custom, 1)
5100 do_install(None, expected_all, 2)
5101
5102
5103 def test_install_script_dry_run(self):
5104 testdir = os.path.join(self.common_test_dir, '53 install script')
5105 self.init(testdir)
5106 self.build()
5107
5108 cmd = self.meson_command + ['install', '--dry-run', '--destdir', self.installdir]
5109 outputs = self._run(cmd, workdir=self.builddir)
5110
5111 installpath = Path(self.installdir)
5112 self.assertFalse((installpath / 'usr/diiba/daaba/file.dat').exists())
5113 self.assertIn("DRYRUN: Writing file file.dat", outputs)
5114
5115
5116 def test_introspect_install_plan(self):
5117 testdir = os.path.join(self.unit_test_dir, '98 install all targets')
5118 introfile = os.path.join(self.builddir, 'meson-info', 'intro-install_plan.json')
5119 self.init(testdir)
5120 self.assertPathExists(introfile)
5121 with open(introfile, encoding='utf-8') as fp:
5122 res = json.load(fp)
5123
5124 env = get_fake_env(testdir, self.builddir, self.prefix)
5125
5126 def output_name(name, type_):
5127 target = type_(name=name, subdir='',
5128 orig_for_machine=MachineChoice.HOST, sources=[],
5129 structured_sources=None,
5130 objects=[], environment=env, compilers=env.coredata.compilers[MachineChoice.HOST],
5131 build_project=BuildProject('', '', SubProject(''), MachineChoice.HOST, MachineChoice.HOST),
5132 kwargs={'native': MachineChoice.HOST})
5133 target.process_compilers_late()
5134 return target.filename
5135
5136 shared_lib_name = lambda name: output_name(name, SharedLibrary)
5137 static_lib_name = lambda name: output_name(name, StaticLibrary)
5138 exe_name = lambda name: output_name(name, Executable)
5139
5140 expected = {
5141 'targets': {
5142 f'{self.builddir}/out1-notag.txt': {
5143 'build_rpaths': [],
5144 'destination': '{datadir}/out1-notag.txt',
5145 'install_rpath': None,
5146 'tag': None,
5147 'subproject': None,
5148 },
5149 f'{self.builddir}/out2-notag.txt': {
5150 'build_rpaths': [],
5151 'destination': '{datadir}/out2-notag.txt',
5152 'install_rpath': None,
5153 'tag': None,
5154 'subproject': None,
5155 },
5156 f'{self.builddir}/libstatic.a': {
5157 'build_rpaths': [],
5158 'destination': '{libdir_static}/libstatic.a',
5159 'install_rpath': None,
5160 'tag': 'devel',
5161 'subproject': None,
5162 },
5163 f'{self.builddir}/' + exe_name('app'): {
5164 'build_rpaths': [],
5165 'destination': '{bindir}/' + exe_name('app'),
5166 'install_rpath': None,
5167 'tag': 'runtime',
5168 'subproject': None,
5169 },
5170 f'{self.builddir}/' + exe_name('app-otherdir'): {
5171 'build_rpaths': [],
5172 'destination': '{prefix}/otherbin/' + exe_name('app-otherdir'),
5173 'install_rpath': None,
5174 'tag': 'runtime',
5175 'subproject': None,
5176 },
5177 f'{self.builddir}/subdir/' + exe_name('app2'): {
5178 'build_rpaths': [],
5179 'destination': '{bindir}/' + exe_name('app2'),
5180 'install_rpath': None,
5181 'tag': 'runtime',
5182 'subproject': None,
5183 },
5184 f'{self.builddir}/' + shared_lib_name('shared'): {
5185 'build_rpaths': [],
5186 'destination': '{libdir_shared}/' + shared_lib_name('shared'),
5187 'install_rpath': None,
5188 'tag': 'runtime',
5189 'subproject': None,
5190 },
5191 f'{self.builddir}/' + shared_lib_name('both'): {
5192 'build_rpaths': [],
5193 'destination': '{libdir_shared}/' + shared_lib_name('both'),
5194 'install_rpath': None,
5195 'tag': 'runtime',
5196 'subproject': None,
5197 },
5198 f'{self.builddir}/' + static_lib_name('both'): {
5199 'build_rpaths': [],
5200 'destination': '{libdir_static}/' + static_lib_name('both'),
5201 'install_rpath': None,
5202 'tag': 'devel',
5203 'subproject': None,
5204 },
5205 f'{self.builddir}/' + shared_lib_name('bothcustom'): {
5206 'build_rpaths': [],
5207 'destination': '{libdir_shared}/' + shared_lib_name('bothcustom'),
5208 'install_rpath': None,
5209 'tag': 'custom',
5210 'subproject': None,
5211 },
5212 f'{self.builddir}/' + static_lib_name('bothcustom'): {
5213 'build_rpaths': [],
5214 'destination': '{libdir_static}/' + static_lib_name('bothcustom'),
5215 'install_rpath': None,
5216 'tag': 'custom',
5217 'subproject': None,
5218 },
5219 f'{self.builddir}/subdir/' + shared_lib_name('both2'): {
5220 'build_rpaths': [],
5221 'destination': '{libdir_shared}/' + shared_lib_name('both2'),
5222 'install_rpath': None,
5223 'tag': 'runtime',
5224 'subproject': None,
5225 },
5226 f'{self.builddir}/subdir/' + static_lib_name('both2'): {
5227 'build_rpaths': [],
5228 'destination': '{libdir_static}/' + static_lib_name('both2'),
5229 'install_rpath': None,
5230 'tag': 'devel',
5231 'subproject': None,
5232 },
5233 f'{self.builddir}/out1-custom.txt': {
5234 'build_rpaths': [],
5235 'destination': '{datadir}/out1-custom.txt',
5236 'install_rpath': None,
5237 'tag': 'custom',
5238 'subproject': None,
5239 },
5240 f'{self.builddir}/out2-custom.txt': {
5241 'build_rpaths': [],
5242 'destination': '{datadir}/out2-custom.txt',
5243 'install_rpath': None,
5244 'tag': 'custom',
5245 'subproject': None,
5246 },
5247 f'{self.builddir}/out3-custom.txt': {
5248 'build_rpaths': [],
5249 'destination': '{datadir}/out3-custom.txt',
5250 'install_rpath': None,
5251 'tag': 'custom',
5252 'subproject': None,
5253 },
5254 f'{self.builddir}/subdir/out1.txt': {
5255 'build_rpaths': [],
5256 'destination': '{datadir}/out1.txt',
5257 'install_rpath': None,
5258 'tag': None,
5259 'subproject': None,
5260 },
5261 f'{self.builddir}/subdir/out2.txt': {
5262 'build_rpaths': [],
5263 'destination': '{datadir}/out2.txt',
5264 'install_rpath': None,
5265 'tag': None,
5266 'subproject': None,
5267 },
5268 f'{self.builddir}/out-devel.h': {
5269 'build_rpaths': [],
5270 'destination': '{includedir}/out-devel.h',
5271 'install_rpath': None,
5272 'tag': 'devel',
5273 'subproject': None,
5274 },
5275 f'{self.builddir}/out3-notag.txt': {
5276 'build_rpaths': [],
5277 'destination': '{datadir}/out3-notag.txt',
5278 'install_rpath': None,
5279 'tag': None,
5280 'subproject': None,
5281 },
5282 },
5283 'configure': {
5284 f'{self.builddir}/foo-notag.h': {
5285 'destination': '{datadir}/foo-notag.h',
5286 'tag': None,
5287 'subproject': None,
5288 },
5289 f'{self.builddir}/foo2-devel.h': {
5290 'destination': '{includedir}/foo2-devel.h',
5291 'tag': 'devel',
5292 'subproject': None,
5293 },
5294 f'{self.builddir}/foo-custom.h': {
5295 'destination': '{datadir}/foo-custom.h',
5296 'tag': 'custom',
5297 'subproject': None,
5298 },
5299 f'{self.builddir}/subdir/foo2.h': {
5300 'destination': '{datadir}/foo2.h',
5301 'tag': None,
5302 'subproject': None,
5303 },
5304 },
5305 'data': {
5306 f'{testdir}/bar-notag.txt': {
5307 'destination': '{datadir}/bar-notag.txt',
5308 'tag': None,
5309 'subproject': None,
5310 },
5311 f'{testdir}/bar-devel.h': {
5312 'destination': '{includedir}/bar-devel.h',
5313 'tag': 'devel',
5314 'subproject': None,
5315 },
5316 f'{testdir}/bar-custom.txt': {
5317 'destination': '{datadir}/bar-custom.txt',
5318 'tag': 'custom',
5319 'subproject': None,
5320 },
5321 f'{testdir}/subdir/bar2-devel.h': {
5322 'destination': '{includedir}/bar2-devel.h',
5323 'tag': 'devel',
5324 'subproject': None,
5325 },
5326 f'{testdir}/subprojects/subproject/aaa.txt': {
5327 'destination': '{datadir}/subproject/aaa.txt',
5328 'tag': None,
5329 'subproject': 'subproject',
5330 },
5331 f'{testdir}/subprojects/subproject/bbb.txt': {
5332 'destination': '{datadir}/subproject/bbb.txt',
5333 'tag': 'data',
5334 'subproject': 'subproject',
5335 },
5336 },
5337 'headers': {
5338 f'{testdir}/foo1-devel.h': {
5339 'destination': '{includedir}/foo1-devel.h',
5340 'tag': 'devel',
5341 'subproject': None,
5342 },
5343 f'{testdir}/subdir/foo3-devel.h': {
5344 'destination': '{includedir}/foo3-devel.h',
5345 'tag': 'devel',
5346 'subproject': None,
5347 },
5348 },
5349 'install_subdirs': {
5350 f'{testdir}/custom_files': {
5351 'destination': '{datadir}/custom_files',
5352 'tag': 'custom',
5353 'subproject': None,
5354 'exclude_dirs': [],
5355 'exclude_files': [],
5356 },
5357 f'{testdir}/excludes': {
5358 'destination': '{datadir}/excludes',
5359 'tag': 'custom',
5360 'subproject': None,
5361 'exclude_dirs': ['excluded'],
5362 'exclude_files': ['excluded.txt'],
5363 }
5364 }
5365 }
5366
5367 fix_path = lambda path: os.path.sep.join(path.split('/'))
5368 expected_fixed = {
5369 data_type: {
5370 fix_path(source): {
5371 key: fix_path(value) if key == 'destination' else value
5372 for key, value in attributes.items()
5373 }
5374 for source, attributes in files.items()
5375 }
5376 for data_type, files in expected.items()
5377 }
5378
5379 for data_type, files in expected_fixed.items():
5380 for file, details in files.items():
5381 with self.subTest(key='{}.{}'.format(data_type, file)):
5382 self.assertEqual(res[data_type][file], details)
5383
5384 @skip_if_not_language('rust')
5385 @skipIfNoExecutable('rustdoc')
5386 def test_rustdoc(self) -> None:
5387 if self.backend is not Backend.ninja:
5388 raise unittest.SkipTest('Rust is only supported with ninja currently')
5389 try:
5390 with tempfile.TemporaryDirectory() as tmpdir:
5391 testdir = os.path.join(tmpdir, 'a')
5392 shutil.copytree(os.path.join(self.rust_test_dir, '9 unit tests'),
5393 testdir)
5394 self.init(testdir)
5395 self.build('rustdoc')
5396 except PermissionError:
5397 # When run under Windows CI, something (virus scanner?)
5398 # holds on to the git files so cleaning up the dir
5399 # fails sometimes.
5400 pass
5401
5402 @skip_if_not_language('rust')
5403 @skipIfNoExecutable('clippy-driver')
5404 def test_rust_clippy(self) -> None:
5405 if self.backend is not Backend.ninja:
5406 raise unittest.SkipTest('Rust is only supported with ninja currently')
5407 # When clippy is used, we should get an exception since a variable named
5408 # "foo" is used, but is on our denylist
5409 testdir = os.path.join(self.rust_test_dir, '1 basic')
5410 self.init(testdir)
5411 self.build('clippy')
5412
5413 self.wipe()
5414 self.init(testdir, extra_args=['--werror', '-Db_colorout=never'])
5415 with self.assertRaises(subprocess.CalledProcessError) as cm:
5416 self.build('clippy')
5417 self.assertTrue('error: use of a blacklisted/placeholder name `foo`' in cm.exception.stdout or
5418 'error: use of a disallowed/placeholder name `foo`' in cm.exception.stdout)
5419
5420 @skip_if_not_language('rust')
5421 @skipIfNoExecutable('clippy-driver')
5422 def test_rust_clippy_as_rustc(self) -> None:
5423 if self.backend is not Backend.ninja:
5424 raise unittest.SkipTest('Rust is only supported with ninja currently')
5425 # When clippy is used, we should get an exception since a variable named
5426 # "foo" is used, but is on our denylist
5427 testdir = os.path.join(self.rust_test_dir, '1 basic')
5428 self.init(testdir, extra_args=['--werror'], override_envvars={'RUSTC': 'clippy-driver'})
5429 with self.assertRaises(subprocess.CalledProcessError) as cm:
5430 self.build()
5431 self.assertTrue('error: use of a blacklisted/placeholder name `foo`' in cm.exception.stdout or
5432 'error: use of a disallowed/placeholder name `foo`' in cm.exception.stdout)
5433
5434 @skip_if_not_language('rust')
5435 def test_rust_test_warnings(self) -> None:
5436 if self.backend is not Backend.ninja:
5437 raise unittest.SkipTest('Rust is only supported with ninja currently')
5438 testdir = os.path.join(self.rust_test_dir, '9 unit tests')
5439 self.init(testdir, extra_args=['--fatal-meson-warnings'])
5440
5441 @skip_if_not_language('rust')
5442 def test_rust_rlib_linkage(self) -> None:
5443 if self.backend is not Backend.ninja:
5444 raise unittest.SkipTest('Rust is only supported with ninja currently')
5445 template = textwrap.dedent('''\
5446 use std::process::exit;
5447
5448 pub fn fun() {{
5449 exit({});
5450 }}
5451 ''')
5452
5453 testdir = os.path.join(self.unit_test_dir, '101 rlib linkage')
5454 gen_file = os.path.join(testdir, 'lib.rs')
5455 with open(gen_file, 'w', encoding='utf-8') as f:
5456 f.write(template.format(0))
5457 self.addCleanup(windows_proof_rm, gen_file)
5458
5459 self.init(testdir)
5460 self.build()
5461 self.run_tests()
5462
5463 with open(gen_file, 'w', encoding='utf-8') as f:
5464 f.write(template.format(39))
5465
5466 self.build()
5467 with self.assertRaises(subprocess.CalledProcessError) as cm:
5468 self.run_tests()
5469 self.assertEqual(cm.exception.returncode, 1)
5470 self.assertIn('exit status 39', cm.exception.stdout)
5471
5472 @skip_if_not_language('rust')
5473 def test_bindgen_drops_invalid(self) -> None:
5474 if self.backend is not Backend.ninja:
5475 raise unittest.SkipTest('Rust is only supported with ninja currently')
5476 testdir = os.path.join(self.rust_test_dir, '12 bindgen')
5477 env = get_fake_env(testdir, self.builddir, self.prefix)
5478 cc = detect_c_compiler(env, MachineChoice.HOST)
5479 # bindgen understands compiler args that clang understands, but not
5480 # flags by other compilers
5481 if cc.get_id() == 'gcc':
5482 bad_arg = '-fdse'
5483 elif cc.get_id() == 'msvc':
5484 bad_arg = '/fastfail'
5485 else:
5486 raise unittest.SkipTest('Test only supports GCC and MSVC')
5487 self.init(testdir, extra_args=[f"-Dc_args=['-DCMD_ARG', '{bad_arg}']"])
5488 intro = self.introspect(['--targets'])
5489 for i in intro:
5490 if i['type'] == 'custom' and i['id'].startswith('rustmod-bindgen'):
5491 args = i['target_sources'][0]['compiler']
5492 self.assertIn('-DCMD_ARG', args)
5493 self.assertIn('-DPROJECT_ARG', args)
5494 self.assertIn('-DGLOBAL_ARG', args)
5495 self.assertNotIn(bad_arg, args)
5496 self.assertNotIn('-mtls-dialect=gnu2', args)
5497 self.assertNotIn('/fp:fast', args)
5498 return
5499
5500 def test_custom_target_name(self):
5501 testdir = os.path.join(self.unit_test_dir, '99 custom target name')
5502 self.init(testdir)
5503 out = self.build()
5504 if self.backend is Backend.ninja:
5505 self.assertIn('Generating file.txt with a custom command', out)
5506 self.assertIn('Generating subdir/file.txt with a custom command', out)
5507
5508 def test_symlinked_subproject(self):
5509 testdir = os.path.join(self.unit_test_dir, '107 subproject symlink')
5510 subproject_dir = os.path.join(testdir, 'subprojects')
5511 subproject = os.path.join(testdir, 'symlinked_subproject')
5512 symlinked_subproject = os.path.join(testdir, 'subprojects', 'symlinked_subproject')
5513 if not os.path.exists(subproject_dir):
5514 os.mkdir(subproject_dir)
5515 try:
5516 os.symlink(subproject, symlinked_subproject)
5517 except OSError:
5518 raise SkipTest("Symlinks are not available on this machine")
5519 self.addCleanup(os.remove, symlinked_subproject)
5520
5521 self.init(testdir)
5522 self.build()
5523
5524 def test_configure_same_noop(self):
5525 testdir = os.path.join(self.unit_test_dir, '109 configure same noop')
5526 args = [
5527 '-Dstring=val',
5528 '-Dboolean=true',
5529 '-Dcombo=two',
5530 '-Dinteger=7',
5531 '-Darray=[\'three\']',
5532 '-Dfeature=disabled',
5533 '--buildtype=plain',
5534 '--prefix=/abc',
5535 ]
5536 self.init(testdir, extra_args=args)
5537
5538 filename = Path(self.privatedir) / 'coredata.dat'
5539
5540 olddata = filename.read_bytes()
5541 oldmtime = os.path.getmtime(filename)
5542
5543 for opt in ('-Dstring=val', '--buildtype=plain', '-Dfeature=disabled', '-Dprefix=/abc'):
5544 self.setconf([opt])
5545 newdata = filename.read_bytes()
5546 newmtime = os.path.getmtime(filename)
5547 self.assertEqual(oldmtime, newmtime)
5548 self.assertEqual(olddata, newdata)
5549 olddata = newdata
5550 oldmtime = newmtime
5551
5552 for opt in ('-Dstring=abc', '--buildtype=release', '-Dfeature=enabled', '-Dprefix=/def'):
5553 self.setconf([opt])
5554 newdata = filename.read_bytes()
5555 newmtime = os.path.getmtime(filename)
5556 self.assertGreater(newmtime, oldmtime)
5557 self.assertNotEqual(olddata, newdata)
5558 olddata = newdata
5559 oldmtime = newmtime
5560
5561 def test_link_language_promotion(self):
5562 if self.backend is Backend.vs:
5563 raise SkipTest('target introspection is lacking linker details')
5564 testdir = os.path.join(self.unit_test_dir, '134 promote link_language')
5565 self.init(testdir)
5566 cintrospection = self.introspect('--compilers')
5567 clinker = cintrospection['host']['c']['linker_exelist']
5568
5569 tintrospection = self.introspect('--targets')
5570 consumer = next(t for t in tintrospection if t['name'] == 'consumer')
5571 linker_src = next(s for s in consumer['target_sources'] if 'linker' in s)
5572
5573 self.assertEqual(clinker, linker_src['linker'])
5574
5575 def __test_multi_stds(self, test_c: bool = True, test_objc: bool = False) -> None:
5576 assert test_c or test_objc, 'must test something'
5577 testdir = os.path.join(self.unit_test_dir, '115 c cpp stds')
5578 self.init(testdir, extra_args=[f'-Dwith-c={str(test_c).lower()}',
5579 f'-Dwith-objc={str(test_objc).lower()}'])
5580 # Invalid values should fail whatever compiler we have
5581 with self.assertRaises(subprocess.CalledProcessError):
5582 self.setconf('-Dc_std=invalid')
5583 with self.assertRaises(subprocess.CalledProcessError):
5584 self.setconf('-Dc_std=c89,invalid')
5585 with self.assertRaises(subprocess.CalledProcessError):
5586 self.setconf('-Dc_std=c++11')
5587 env = get_fake_env()
5588 if test_c:
5589 cc = detect_c_compiler(env, MachineChoice.HOST)
5590 if test_objc:
5591 objc = detect_compiler_for(env, 'objc', MachineChoice.HOST, True, '')
5592 assert objc is not None
5593 if test_c and cc.get_argument_syntax() != objc.get_argument_syntax():
5594 # The test doesn't work correctly in this case because we can
5595 # end up with incompatible stds, like gnu89 with cl.exe for C
5596 # and clang.exe for ObjC
5597 return
5598 if not test_c:
5599 cc = objc
5600
5601 if cc.get_id() in {'msvc', 'clang-cl'}:
5602 # default_option should have selected those
5603 self.assertEqual(self.getconf('c_std'), 'c89')
5604 self.assertEqual(self.getconf('cpp_std'), 'vc++11')
5605 # This is deprecated but works for C
5606 self.setconf('-Dc_std=gnu99')
5607 self.assertEqual(self.getconf('c_std'), 'c99')
5608 # C++ however never accepted that fallback
5609 with self.assertRaises(subprocess.CalledProcessError):
5610 self.setconf('-Dcpp_std=gnu++11')
5611 # The first supported std should be selected
5612 self.setconf('-Dcpp_std=gnu++11,vc++11,c++11')
5613 self.assertEqual(self.getconf('cpp_std'), 'vc++11')
5614 elif cc.get_id() in {'gcc', 'clang'}:
5615 # default_option should have selected those
5616 self.assertEqual(self.getconf('c_std'), 'gnu89')
5617 self.assertEqual(self.getconf('cpp_std'), 'gnu++98')
5618 # The first supported std should be selected
5619 self.setconf('-Dcpp_std=c++11,gnu++11,vc++11')
5620 self.assertEqual(self.getconf('cpp_std'), 'c++11')
5621
5622 def test_c_cpp_stds(self) -> None:
5623 self.__test_multi_stds()
5624
5625 @skip_if_not_language('objc')
5626 @skip_if_not_language('objcpp')
5627 def test_objc_objcpp_stds(self) -> None:
5628 self.__test_multi_stds(test_c=False, test_objc=True)
5629
5630 @skip_if_not_language('objc')
5631 @skip_if_not_language('objcpp')
5632 def test_c_cpp_objc_objcpp_stds(self) -> None:
5633 self.__test_multi_stds(test_objc=True)
5634
5635 def test_slice(self):
5636 testdir = os.path.join(self.unit_test_dir, '128 test slice')
5637 self.init(testdir)
5638 self.build()
5639
5640 for arg, expectation in {'1/1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
5641 '1/2': [1, 3, 5, 7, 9],
5642 '2/2': [2, 4, 6, 8, 10],
5643 '1/10': [1],
5644 '2/10': [2],
5645 '10/10': [10],
5646 }.items():
5647 output = self._run(self.mtest_command + ['--slice=' + arg])
5648 tests = sorted([
5649 int(x) for x in re.findall(r'^[ 0-9]+/[0-9]+ test_slice:test-([0-9]*)', output, flags=re.MULTILINE)
5650 ])
5651 self.assertEqual(tests, expectation)
5652
5653 for arg, expectation in {'': 'error: argument --slice: value does not conform to format \'SLICE/NUM_SLICES\'',
5654 '0': 'error: argument --slice: value does not conform to format \'SLICE/NUM_SLICES\'',
5655 '0/1': 'error: argument --slice: SLICE is not a positive integer',
5656 'a/1': 'error: argument --slice: SLICE is not an integer',
5657 '1/0': 'error: argument --slice: NUM_SLICES is not a positive integer',
5658 '1/a': 'error: argument --slice: NUM_SLICES is not an integer',
5659 '2/1': 'error: argument --slice: SLICE exceeds NUM_SLICES',
5660 '1/11': 'ERROR: number of slices (11) exceeds number of tests (10)',
5661 }.items():
5662 with self.assertRaises(subprocess.CalledProcessError) as cm:
5663 self._run(self.mtest_command + ['--slice=' + arg])
5664 self.assertIn(expectation, cm.exception.output)
5665
5666 def test_rsp_support(self):
5667 env = get_fake_env()
5668 cc = detect_c_compiler(env, MachineChoice.HOST)
5669 has_rsp = cc.linker.id in {
5670 'ld.bfd', 'ld.eld', 'ld.gold', 'ld.lld', 'ld.mold', 'ld.qcld', 'ld.wasm',
5671 'link', 'lld-link', 'mwldarm', 'mwldeppc', 'optlink', 'xilink',
5672 }
5673 self.assertEqual(cc.linker.get_accepts_rsp(), has_rsp)
5674
5675 def test_nonexisting_bargs(self):
5676 testdir = os.path.join(self.unit_test_dir, '116 empty project')
5677 args = ['-Db_ndebug=if_release']
5678 self.init(testdir, extra_args=args)
5679
5680 def test_wipe_with_args(self):
5681 testdir = os.path.join(self.common_test_dir, '1 trivial')
5682 self.init(testdir, extra_args=['-Dc_args=-DSOMETHING'])
5683 self.init(testdir, extra_args=['--wipe'])
5684
5685 def test_interactive_tap(self):
5686 testdir = os.path.join(self.unit_test_dir, '124 interactive tap')
5687 self.init(testdir, extra_args=['--wrap-mode=forcefallback'])
5688 output = self._run(self.mtest_command + ['--interactive'])
5689 self.assertRegex(output, r'Ok:\s*0')
5690 self.assertRegex(output, r'Fail:\s*0')
5691 self.assertRegex(output, r'Ignored:\s*1')
5692
5693 @skip_if_not_language('fortran')
5694 def test_fortran_cross_target_module_dep(self) -> None:
5695 if self.backend is not Backend.ninja:
5696 raise SkipTest('Test is only relavent on the ninja backend')
5697 testdir = os.path.join(self.fortran_test_dir, '8 module names')
5698 self.init(testdir, extra_args=['-Dunittest=true'])
5699
5700 # Find the correct output to compile, regardless of what compiler is being used
5701 comp = self.get_compdb()
5702 entry = first(comp, lambda e: e['file'].endswith('lib.f90'))
5703 assert entry is not None, 'for mypy'
5704 output = entry['output']
5705
5706 self.build(output, extra_args=['-j1'])
5707
5708 @skip_if_not_language('fortran')
5709 def test_fortran_new_module_in_dep(self) -> None:
5710 if self.backend is not Backend.ninja:
5711 raise SkipTest('Test is only relavent on the ninja backend')
5712 testdir = self.copy_srcdir(os.path.join(self.fortran_test_dir, '8 module names'))
5713 self.init(testdir, extra_args=['-Dunittest=true'])
5714 self.build()
5715
5716 with open(os.path.join(testdir, 'mod1.f90'), 'a', encoding='utf-8') as f:
5717 f.write(textwrap.dedent("""\
5718 module MyMod3
5719 implicit none
5720
5721 integer, parameter :: myModVal3 =1
5722
5723 end module MyMod3
5724 """))
5725
5726 with open(os.path.join(testdir, 'test.f90'), 'w', encoding='utf-8') as f:
5727 f.write(textwrap.dedent("""\
5728 program main
5729 use MyMod2
5730 use MyMod3
5731 implicit none
5732
5733 call showvalues()
5734 print*, "MyModValu3 = ", myModVal3
5735
5736 end program
5737 """))
5738
5739 # Find the correct output to compile, regardless of what compiler is being used
5740 comp = self.get_compdb()
5741 entry = first(comp, lambda e: e['file'].endswith('lib.f90'))
5742 assert entry is not None, 'for mypy'
5743 output = entry['output']
5744
5745 self.build(output, extra_args=['-j1'])
5746
5747 def test_run_command_output(self):
5748 '''
5749 Test that run_command will output to stdout/stderr if `check: false`.
5750 '''
5751 testdir = os.path.join(self.common_test_dir, '33 run program')
5752
5753 # inprocess=False uses BasePlatformTests::_run, which by default
5754 # redirects all stderr to stdout, so we look for the expected stderr
5755 # in the merged stdout.
5756 # inprocess=True captures stderr and stdout separately, but doesn't
5757 # return stderr (only printing it on failure) so unless we change the
5758 # function signature we can't get at the stderr output
5759 out = self.init(testdir, inprocess=False)
5760 # No output at all
5761 self.assertTrue('stdout|capture:false,console:false' not in out)
5762 self.assertTrue('stderr|capture:false,console:false' not in out)
5763 # Output not captured, but printed
5764 self.assertTrue('stdout|capture:false,console:true' in out)
5765 self.assertTrue('stderr|capture:false,console:true' in out)
5766 # Output captured, but not printed
5767 self.assertTrue('stdout|capture:true,console:false' not in out)
5768 self.assertTrue('stderr|capture:true,console:false' not in out)
5769 # Output captured and printed
5770 self.assertTrue('stdout|capture:true,console:true' in out)
5771 self.assertTrue('stderr|capture:true,console:true' in out)