Debian Codegraph @

unittests/internaltests.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2016-2021 The Meson development team
3
4 from configparser import ConfigParser
5 from pathlib import Path
6 from unittest import mock
7 import argparse
8 import contextlib
9 import io
10 import json
11 import operator
12 import os
13 import pickle
14 import stat
15 import subprocess
16 import tempfile
17 import textwrap
18 import typing as T
19 import unittest
20
21 import mesonbuild.mlog
22 import mesonbuild.depfile
23 import mesonbuild.dependencies.base
24 import mesonbuild.dependencies.factory
25 import mesonbuild.envconfig
26 import mesonbuild.environment
27 import mesonbuild.modules.gnome
28 import mesonbuild.scripts.env2mfile
29 from mesonbuild import coredata
30 from mesonbuild.compilers.c import ClangCCompiler, GnuCCompiler, VisualStudioCCompiler
31 from mesonbuild.compilers.compilers import Compiler, CompileCheckMode, ManyInOneLinkerOptionStyle
32 from mesonbuild.compilers.cpp import VisualStudioCPPCompiler
33 from mesonbuild.compilers.d import DmdDCompiler
34 from mesonbuild.compilers.detect import detect_c_compiler
35 from mesonbuild.compilers.mixins.visualstudio import MSVCCompiler, ClangClCompiler
36 from mesonbuild.linkers import linkers
37 from mesonbuild.interpreterbase import typed_pos_args, InvalidArguments, ObjectHolder
38 from mesonbuild.interpreterbase import typed_pos_args, InvalidArguments, typed_kwargs, ContainerTypeInfo, KwargInfo
39 from mesonbuild.mesonlib import (
40 LibType, MachineChoice, PerMachine, SimpleABC, Version, is_windows, is_osx,
41 is_cygwin, is_openbsd, search_version, MesonException, EnvironmentException, python_command,
42 version_check_to_range,
43 )
44 from mesonbuild.options import OptionKey
45 from mesonbuild.interpreter.type_checking import in_set_validator, NoneType
46 from mesonbuild.dependencies.pkgconfig import PkgConfigDependency, PkgConfigInterface, PkgConfigCLI
47 from mesonbuild.programs import ExternalProgram
48 import mesonbuild.modules.pkgconfig
49 from mesonbuild import utils
50
51 from run_tests import get_fake_env, get_fake_options
52
53 from .helpers import *
54
55 class InternalTests(unittest.TestCase):
56
57 def test_cmake_skip_compiler_test_invalid(self):
58 properties = mesonbuild.envconfig.Properties({'cmake_skip_compiler_test': True})
59 with self.assertRaisesRegex(
60 EnvironmentException,
61 '"True" is not a valid value for cmake_skip_compiler_test'):
62 properties.get_cmake_skip_compiler_test()
63
64 def test_machine_info_is_ohos(self):
65 def machine(system: str, subsystem: str) -> mesonbuild.envconfig.MachineInfo:
66 return mesonbuild.envconfig.MachineInfo(
67 system=system, cpu_family='aarch64', cpu='aarch64',
68 endian='little', kernel='linux', subsystem=subsystem)
69
70 # OHOS is modelled as an Android subsystem.
71 ohos = machine('android', 'ohos')
72 self.assertTrue(ohos.is_ohos())
73 self.assertTrue(ohos.is_android())
74
75 # Plain Android is not OHOS.
76 self.assertFalse(machine('android', 'android').is_ohos())
77 # A non-Android system with an 'ohos' subsystem is not OHOS either.
78 self.assertFalse(machine('linux', 'ohos').is_ohos())
79
80 def test_version_number(self):
81 self.assertEqual(search_version('foobar 1.2.3'), '1.2.3')
82 self.assertEqual(search_version('1.2.3'), '1.2.3')
83 self.assertEqual(search_version('foobar 2016.10.28 1.2.3'), '1.2.3')
84 self.assertEqual(search_version('2016.10.28 1.2.3'), '1.2.3')
85 self.assertEqual(search_version('foobar 2016.10.128'), '2016.10.128')
86 self.assertEqual(search_version('2016.10.128'), '2016.10.128')
87 self.assertEqual(search_version('2016.10'), '2016.10')
88 self.assertEqual(search_version('2016.10 1.2.3'), '1.2.3')
89 self.assertEqual(search_version('oops v1.2.3'), '1.2.3')
90 self.assertEqual(search_version('2016.oops 1.2.3'), '1.2.3')
91 self.assertEqual(search_version('2016.x'), 'unknown version')
92 self.assertEqual(search_version(r'something version is \033[32;2m1.2.0\033[0m.'), '1.2.0')
93
94 self.assertEqual(search_version(r'''(FooBar LLVM-Linux 5.0.0) clang version 21.9.0
95 Target: riscv64-unknown-linux-gnu
96 Thread model: posix'''), '21.9.0')
97
98 # Literal output of mvn
99 self.assertEqual(search_version(r'''\
100 \033[1mApache Maven 3.8.1 (05c21c65bdfed0f71a2f2ada8b84da59348c4c5d)\033[0m
101 Maven home: /nix/store/g84a9wnid2h1d3z2wfydy16dky73wh7i-apache-maven-3.8.1/maven
102 Java version: 11.0.10, vendor: Oracle Corporation, runtime: /nix/store/afsnl4ahmm9svvl7s1a0cj41vw4nkmz4-openjdk-11.0.10+9/lib/openjdk
103 Default locale: en_US, platform encoding: UTF-8
104 OS name: "linux", version: "5.12.17", arch: "amd64", family: "unix"'''),
105 '3.8.1')
106
107 def test_simple_abc(self):
108 from abc import abstractmethod
109
110 # The whole point is for isinstance() to stay on the C fast path
111 self.assertNotIn('__instancecheck__', vars(SimpleABC))
112 self.assertNotIn('__subclasscheck__', vars(SimpleABC))
113
114 class A(metaclass=SimpleABC):
115 @abstractmethod
116 def foo(self): ...
117
118 class B(A, metaclass=SimpleABC):
119 def foo(self):
120 return 1
121
122 @abstractmethod
123 def bar(self): ...
124
125 class C(B):
126 def foo(self):
127 return 2
128
129 class D(B):
130 def bar(self):
131 return 3
132
133 self.assertEqual(A.__abstractmethods__, frozenset({'foo'}))
134 with self.assertRaises(TypeError):
135 A()
136
137 self.assertEqual(B.__abstractmethods__, frozenset({'bar'}))
138 self.assertTrue(issubclass(B, A))
139 with self.assertRaises(TypeError):
140 B()
141
142 self.assertEqual(C.__abstractmethods__, frozenset({'bar'}))
143 self.assertTrue(issubclass(C, A))
144 self.assertTrue(issubclass(C, B))
145 with self.assertRaises(TypeError):
146 # subclass inheriting SimpleABC
147 C()
148
149 self.assertEqual(D.__abstractmethods__, frozenset())
150 self.assertTrue(issubclass(D, A))
151 self.assertTrue(issubclass(D, B))
152 self.assertTrue(issubclass(D, D))
153 self.assertIsInstance(D(), A)
154 self.assertIsInstance(D(), B)
155 self.assertIsInstance(D(), D)
156
157 def test_mode_symbolic_to_bits(self):
158 modefunc = mesonbuild.mesonlib.FileMode.perms_s_to_bits
159 self.assertEqual(modefunc('---------'), 0)
160 self.assertEqual(modefunc('r--------'), stat.S_IRUSR)
161 self.assertEqual(modefunc('---r-----'), stat.S_IRGRP)
162 self.assertEqual(modefunc('------r--'), stat.S_IROTH)
163 self.assertEqual(modefunc('-w-------'), stat.S_IWUSR)
164 self.assertEqual(modefunc('----w----'), stat.S_IWGRP)
165 self.assertEqual(modefunc('-------w-'), stat.S_IWOTH)
166 self.assertEqual(modefunc('--x------'), stat.S_IXUSR)
167 self.assertEqual(modefunc('-----x---'), stat.S_IXGRP)
168 self.assertEqual(modefunc('--------x'), stat.S_IXOTH)
169 self.assertEqual(modefunc('--S------'), stat.S_ISUID)
170 self.assertEqual(modefunc('-----S---'), stat.S_ISGID)
171 self.assertEqual(modefunc('--------T'), stat.S_ISVTX)
172 self.assertEqual(modefunc('--s------'), stat.S_ISUID | stat.S_IXUSR)
173 self.assertEqual(modefunc('-----s---'), stat.S_ISGID | stat.S_IXGRP)
174 self.assertEqual(modefunc('--------t'), stat.S_ISVTX | stat.S_IXOTH)
175 self.assertEqual(modefunc('rwx------'), stat.S_IRWXU)
176 self.assertEqual(modefunc('---rwx---'), stat.S_IRWXG)
177 self.assertEqual(modefunc('------rwx'), stat.S_IRWXO)
178 # We could keep listing combinations exhaustively but that seems
179 # tedious and pointless. Just test a few more.
180 self.assertEqual(modefunc('rwxr-xr-x'),
181 stat.S_IRWXU |
182 stat.S_IRGRP | stat.S_IXGRP |
183 stat.S_IROTH | stat.S_IXOTH)
184 self.assertEqual(modefunc('rw-r--r--'),
185 stat.S_IRUSR | stat.S_IWUSR |
186 stat.S_IRGRP |
187 stat.S_IROTH)
188 self.assertEqual(modefunc('rwsr-x---'),
189 stat.S_IRWXU | stat.S_ISUID |
190 stat.S_IRGRP | stat.S_IXGRP)
191
192 def test_compiler_args_class_none_flush(self):
193 cc = ClangCCompiler([], [], 'fake', MachineChoice.HOST, get_fake_env())
194 a = cc.compiler_args(['-I.'])
195 #first we are checking if the tree construction deduplicates the correct -I argument
196 a += ['-I..']
197 a += ['-I./tests/']
198 a += ['-I./tests2/']
199 #think this here as assertion, we cannot apply it, otherwise the CompilerArgs would already flush the changes:
200 # assertEqual(a, ['-I.', '-I./tests2/', '-I./tests/', '-I..', '-I.'])
201 a += ['-I.']
202 a += ['-I.', '-I./tests/']
203 self.assertEqual(a, ['-I.', '-I./tests/', '-I./tests2/', '-I..'])
204
205 #then we are checking that when CompilerArgs already have a build container list, that the deduplication is taking the correct one
206 a += ['-I.', '-I./tests2/']
207 self.assertEqual(a, ['-I.', '-I./tests2/', '-I./tests/', '-I..'])
208
209 def test_compiler_args_class_d(self):
210 d = DmdDCompiler([], 'fake', MachineChoice.HOST, get_fake_env(), 'arch')
211 # check include order is kept when deduplicating
212 a = d.compiler_args(['-Ifirst', '-Isecond', '-Ithird'])
213 a += ['-Ifirst']
214 self.assertEqual(a, ['-Ifirst', '-Isecond', '-Ithird'])
215
216 def test_compiler_args_class_clike(self):
217 cc = ClangCCompiler([], [], 'fake', MachineChoice.HOST, get_fake_env())
218 # Test that empty initialization works
219 a = cc.compiler_args()
220 self.assertEqual(a, [])
221 # Test that list initialization works
222 a = cc.compiler_args(['-I.', '-I..'])
223 self.assertEqual(a, ['-I.', '-I..'])
224 # Test that there is no de-dup on initialization
225 self.assertEqual(cc.compiler_args(['-I.', '-I.']), ['-I.', '-I.'])
226
227 ## Test that appending works
228 a.append('-I..')
229 self.assertEqual(a, ['-I..', '-I.'])
230 a.append('-O3')
231 self.assertEqual(a, ['-I..', '-I.', '-O3'])
232
233 ## Test that in-place addition works
234 a += ['-O2', '-O2']
235 self.assertEqual(a, ['-I..', '-I.', '-O3', '-O2', '-O2'])
236 # Test that removal works
237 a.remove('-O2')
238 self.assertEqual(a, ['-I..', '-I.', '-O3', '-O2'])
239 # Test that de-dup happens on addition
240 a += ['-Ifoo', '-Ifoo']
241 self.assertEqual(a, ['-Ifoo', '-I..', '-I.', '-O3', '-O2'])
242
243 # .extend() is just +=, so we don't test it
244
245 ## Test that addition works
246 # Test that adding a list with just one old arg works and yields the same array
247 a = a + ['-Ifoo']
248 self.assertEqual(a, ['-Ifoo', '-I..', '-I.', '-O3', '-O2'])
249 # Test that adding a list with one arg new and one old works
250 a = a + ['-Ifoo', '-Ibaz']
251 self.assertEqual(a, ['-Ifoo', '-Ibaz', '-I..', '-I.', '-O3', '-O2'])
252 # Test that adding args that must be prepended and appended works
253 a = a + ['-Ibar', '-Wall']
254 self.assertEqual(a, ['-Ibar', '-Ifoo', '-Ibaz', '-I..', '-I.', '-O3', '-O2', '-Wall'])
255
256 ## Test that reflected addition works
257 # Test that adding to a list with just one old arg works and yields the same array
258 a = ['-Ifoo'] + a
259 self.assertEqual(a, ['-Ibar', '-Ifoo', '-Ibaz', '-I..', '-I.', '-O3', '-O2', '-Wall'])
260 # Test that adding to a list with just one new arg that is not pre-pended works
261 a = ['-Werror'] + a
262 self.assertEqual(a, ['-Ibar', '-Ifoo', '-Ibaz', '-I..', '-I.', '-Werror', '-O3', '-O2', '-Wall'])
263 # Test that adding to a list with two new args preserves the order
264 a = ['-Ldir', '-Lbah'] + a
265 self.assertEqual(a, ['-Ibar', '-Ifoo', '-Ibaz', '-I..', '-I.', '-Ldir', '-Lbah', '-Werror', '-O3', '-O2', '-Wall'])
266 # Test that adding to a list with old args does nothing
267 a = ['-Ibar', '-Ibaz', '-Ifoo'] + a
268 self.assertEqual(a, ['-Ibar', '-Ifoo', '-Ibaz', '-I..', '-I.', '-Ldir', '-Lbah', '-Werror', '-O3', '-O2', '-Wall'])
269
270 ## Test that adding libraries works
271 l = cc.compiler_args(['-Lfoodir', '-lfoo'])
272 self.assertEqual(l, ['-Lfoodir', '-lfoo'])
273 # Adding a library and a libpath appends both correctly
274 l += ['-Lbardir', '-lbar']
275 self.assertEqual(l, ['-Lbardir', '-Lfoodir', '-lfoo', '-lbar'])
276 # Adding the same library again does nothing
277 l += ['-lbar']
278 self.assertEqual(l, ['-Lbardir', '-Lfoodir', '-lfoo', '-lbar'])
279
280 ## Test that 'direct' append and extend works
281 l = cc.compiler_args(['-Lfoodir', '-lfoo'])
282 self.assertEqual(l, ['-Lfoodir', '-lfoo'])
283 # Direct-adding a library and a libpath appends both correctly
284 l.extend_direct(['-Lbardir', '-lbar'])
285 self.assertEqual(l, ['-Lfoodir', '-lfoo', '-Lbardir', '-lbar'])
286 # Direct-adding the same library again still adds it
287 l.append_direct('-lbar')
288 self.assertEqual(l, ['-Lfoodir', '-lfoo', '-Lbardir', '-lbar', '-lbar'])
289 # Direct-adding with absolute path deduplicates
290 abspath = str(Path('/libbaz.a').resolve())
291 l.append_direct(abspath)
292 self.assertEqual(l, ['-Lfoodir', '-lfoo', '-Lbardir', '-lbar', '-lbar', abspath])
293 # Adding libbaz again does nothing
294 l.append_direct(abspath)
295 self.assertEqual(l, ['-Lfoodir', '-lfoo', '-Lbardir', '-lbar', '-lbar', abspath])
296
297
298 def test_compiler_args_class_visualstudio(self):
299 env = get_fake_env()
300 linker = linkers.MSVCDynamicLinker(env, MachineChoice.HOST, [])
301 # Version just needs to be > 19.0.0
302 cc = VisualStudioCPPCompiler([], [], '20.00', MachineChoice.HOST, env, 'x64', linker=linker)
303
304 a = cc.compiler_args(cc.get_always_args())
305 self.assertEqual(a.to_native(copy=True), ['/nologo', '/utf-8', '/Zc:__cplusplus'])
306
307 # Ensure /source-charset: removes /utf-8
308 a.append('/source-charset:utf-8')
309 self.assertEqual(a.to_native(copy=True), ['/nologo', '/Zc:__cplusplus', '/source-charset:utf-8'])
310
311 # Ensure /execution-charset: removes /utf-8
312 a = cc.compiler_args(cc.get_always_args() + ['/execution-charset:utf-8'])
313 self.assertEqual(a.to_native(copy=True), ['/nologo', '/Zc:__cplusplus', '/execution-charset:utf-8'])
314
315 # Ensure /validate-charset- removes /utf-8
316 a = cc.compiler_args(cc.get_always_args() + ['/validate-charset-'])
317 self.assertEqual(a.to_native(copy=True), ['/nologo', '/Zc:__cplusplus', '/validate-charset-'])
318
319 # /showIncludes is needed for build dependency tracking in Ninja
320 # See: https://ninja-build.org/manual.html#_deps
321 a = cc.compiler_args(cc.get_show_dep_args())
322 self.assertEqual(a.to_native(copy=True), ['/showIncludes'])
323
324
325 def test_clike_sanity_check_drops_link_only_args_when_compile_only(self):
326 # When cross-compiling without an exe wrapper, CLikeCompiler's sanity
327 # check only compiles and never links because we can't run the
328 # executable. Therefore, it doesn't make sense for link-only arguments
329 # to be added on the command line. Some compilers warn about unused
330 # command line arguments.
331 env = get_fake_env()
332 linker = linkers.MoldDynamicLinker([], env, MachineChoice.HOST, '-Wl,', [])
333 cc = ClangCCompiler([], [], '14.0.0', MachineChoice.HOST, env, linker=linker)
334 cc.is_cross = True
335
336 with mock.patch.object(env, 'has_exe_wrapper', return_value=False), \
337 mock.patch.object(cc, '_get_basic_compiler_args', return_value=([], ['-fake-cross-link-arg'])), \
338 mock.patch.object(Compiler, '_sanity_check_compile_args', return_value=([], ['-Lfake-ldflags-arg'])):
339 _, largs = cc._sanity_check_compile_args('foo.c', 'foo.exe')
340
341 self.assertEqual(largs, [])
342
343
344 def test_msvc_unix_args_to_native(self):
345 # joined
346 self.assertEqual(MSVCCompiler.unix_args_to_native(['-isystemfoo']), ['/Ifoo'])
347 self.assertEqual(MSVCCompiler.unix_args_to_native(['-idirafterfoo']), ['/Ifoo'])
348 self.assertEqual(MSVCCompiler.unix_args_to_native(['-iquotefoo']), ['/Ifoo'])
349
350 # with = separator
351 self.assertEqual(MSVCCompiler.unix_args_to_native(['-isystem=foo']), ['/Ifoo'])
352 self.assertEqual(MSVCCompiler.unix_args_to_native(['-idirafter=foo']), ['/Ifoo'])
353 self.assertEqual(MSVCCompiler.unix_args_to_native(['-iquote=foo']), ['/Ifoo'])
354
355 # as separate argument
356 self.assertEqual(MSVCCompiler.unix_args_to_native(['-isystem', 'foo']), ['/Ifoo'])
357 self.assertEqual(MSVCCompiler.unix_args_to_native(['-idirafter', 'foo']), ['/Ifoo'])
358 self.assertEqual(MSVCCompiler.unix_args_to_native(['-iquote', 'foo']), ['/Ifoo'])
359
360 def test_clangcl_unix_args_to_native(self):
361 # joined
362 self.assertEqual(ClangClCompiler.unix_args_to_native(['-isystemfoo']), ['/clang:-isystemfoo'])
363 self.assertEqual(ClangClCompiler.unix_args_to_native(['-idirafterfoo']), ['/clang:-idirafterfoo'])
364 self.assertEqual(ClangClCompiler.unix_args_to_native(['-iquotefoo']), ['/clang:-iquotefoo'])
365
366 # with = separator
367 self.assertEqual(ClangClCompiler.unix_args_to_native(['-isystem=foo']), ['/clang:-isystemfoo'])
368 self.assertEqual(ClangClCompiler.unix_args_to_native(['-idirafter=foo']), ['/clang:-idirafterfoo'])
369 self.assertEqual(ClangClCompiler.unix_args_to_native(['-iquote=foo']), ['/clang:-iquotefoo'])
370
371 # as separate argument
372 self.assertEqual(ClangClCompiler.unix_args_to_native(['-isystem', 'foo']), ['/clang:-isystemfoo'])
373 self.assertEqual(ClangClCompiler.unix_args_to_native(['-idirafter', 'foo']), ['/clang:-idirafterfoo'])
374 self.assertEqual(ClangClCompiler.unix_args_to_native(['-iquote', 'foo']), ['/clang:-iquotefoo'])
375
376 def _fake_msvc_cc(self, cflags='-DCFLAG', ldflags='/SUBSYSTEM:CONSOLE'):
377 with mock.patch.dict(os.environ, {'CFLAGS': cflags, 'LDFLAGS': ldflags}):
378 env = get_fake_env()
379 env.add_lang_args('c', VisualStudioCCompiler, MachineChoice.HOST)
380 linker = linkers.MSVCDynamicLinker(env, MachineChoice.HOST, [])
381 return VisualStudioCCompiler([], [], '20.00', MachineChoice.HOST, env, 'x64', linker=linker)
382
383 def _fake_gnu_cc(self, cflags='-DCFLAG', ldflags='-Wl,-O1',
384 linker_cls=linkers.GnuBFDDynamicLinker):
385 with mock.patch.dict(os.environ, {'CFLAGS': cflags, 'LDFLAGS': ldflags}):
386 env = get_fake_env()
387 env.add_lang_args('c', GnuCCompiler, MachineChoice.HOST)
388 linker = linker_cls([], env, MachineChoice.HOST,
389 ManyInOneLinkerOptionStyle('-Wl,', ','), [])
390 return GnuCCompiler([], [], 'fake', MachineChoice.HOST, env, linker=linker)
391
392 def assertAfterLink(self, args: T.List[str], flag: str) -> None:
393 '''Assert that a linker-only flag is passed exactly once, after /link.'''
394 self.assertEqual(args.count(flag), 1, f'{flag} not passed exactly once in {args}')
395 self.assertIn('/link', args)
396 self.assertLess(args.index('/link'), args.index(flag), f'{flag} passed before /link in {args}')
397
398 def test_sanity_check_args_msvc(self):
399 cc = self._fake_msvc_cc()
400 args, largs = cc._sanity_check_compile_args('t.c', 't.exe')
401 # external link args are passed once, and after /link
402 self.assertAfterLink(largs, '/SUBSYSTEM:CONSOLE')
403 self.assertNotIn('/SUBSYSTEM:CONSOLE', args)
404 # so are the linker's own always args
405 self.assertAfterLink(largs, '/release')
406 self.assertNotIn('/release', args)
407 # external compile args are passed to the compiler, not to the linker
408 self.assertNotIn('-DCFLAG', largs)
409 self.assertEqual(args.count('-DCFLAG'), 1, args)
410 self.assertIn('/Fet.exe', args)
411
412 def test_sanity_check_args_gnu(self):
413 cc = self._fake_gnu_cc()
414 args, largs = cc._sanity_check_compile_args('t.c', 't.exe')
415 # external args must reach the probe, but only once
416 self.assertEqual(args.count('-DCFLAG'), 1, args)
417 self.assertEqual((args + largs).count('-Wl,-O1'), 1, (args, largs))
418 self.assertIn('-Wl,-O1', largs)
419
420 def test_compiler_check_args_msvc(self):
421 cc = self._fake_msvc_cc()
422 args = cc.build_wrapper_args(None, None, CompileCheckMode.LINK).to_native()
423 # linker-only flags belong after /link, not on the compiler command line
424 self.assertAfterLink(args, '/release')
425 self.assertAfterLink(args, '/SUBSYSTEM:CONSOLE')
426 args = cc.build_wrapper_args(None, None, CompileCheckMode.COMPILE).to_native()
427 self.assertNotIn('/release', args)
428 self.assertNotIn('/link', args)
429
430 def test_compiler_check_args_os2(self):
431 # the linker's always args (-Zomf on OS/2) must reach link mode checks
432 cc = self._fake_gnu_cc(linker_cls=linkers.OS2OmfDynamicLinker)
433 args = cc.build_wrapper_args(None, None, CompileCheckMode.LINK)
434 self.assertEqual(list(args).count('-Zomf'), 1, args)
435 self.assertNotIn('-Zomf', cc.build_wrapper_args(None, None, CompileCheckMode.COMPILE))
436
437 def test_find_library_args_msvc(self):
438 cc = self._fake_msvc_cc()
439
440 def fake_links(code, *, extra_args=None, **kwargs):
441 args = cc.build_wrapper_args(extra_args, None, CompileCheckMode.LINK).to_native()
442 self.assertAfterLink(args, '/release')
443 return (True, False)
444
445 with mock.patch.object(cc, 'links', fake_links):
446 cc.find_library('foo', [])
447
448 def test_compiler_args_class_gnuld(self):
449 ## Test --start/end-group
450 env = get_fake_env()
451 linker = linkers.GnuBFDDynamicLinker([], env, MachineChoice.HOST, ManyInOneLinkerOptionStyle('-Wl,', ','), [])
452 gcc = GnuCCompiler([], [], 'fake', MachineChoice.HOST, env, linker=linker)
453 ## Ensure that the fake compiler is never called by overriding the relevant function
454 gcc.get_default_include_dirs = lambda: ['/usr/include', '/usr/share/include', '/usr/local/include']
455 ## Test that 'direct' append and extend works
456 l = gcc.compiler_args(['-Lfoodir', '-lfoo'])
457 self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-lfoo'])
458 # Direct-adding a library and a libpath appends both correctly
459 l.extend_direct(['-Lbardir', '-lbar'])
460 self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-Wl,--start-group', '-lfoo', '-Lbardir', '-lbar', '-Wl,--end-group'])
461 # Direct-adding the same library again still adds it
462 l.append_direct('-lbar')
463 self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-Wl,--start-group', '-lfoo', '-Lbardir', '-lbar', '-lbar', '-Wl,--end-group'])
464 # Direct-adding with absolute path deduplicates
465 abspath = str(Path('/libbaz.a').resolve())
466 l.append_direct(abspath)
467 self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-Wl,--start-group', '-lfoo', '-Lbardir', '-lbar', '-lbar', abspath, '-Wl,--end-group'])
468 # Adding libbaz again does nothing
469 l.append_direct(abspath)
470 self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-Wl,--start-group', '-lfoo', '-Lbardir', '-lbar', '-lbar', abspath, '-Wl,--end-group'])
471 # Adding a non-library argument doesn't include it in the group
472 l += ['-Lfoo', '-Wl,--export-dynamic']
473 self.assertEqual(l.to_native(copy=True), ['-Lfoo', '-Lfoodir', '-Wl,--start-group', '-lfoo', '-Lbardir', '-lbar', '-lbar', abspath, '-Wl,--end-group', '-Wl,--export-dynamic'])
474 # -Wl,-lfoo is detected as a library and gets added to the group
475 l.append('-Wl,-ldl')
476 self.assertEqual(l.to_native(copy=True), ['-Lfoo', '-Lfoodir', '-Wl,--start-group', '-lfoo', '-Lbardir', '-lbar', '-lbar', abspath, '-Wl,--export-dynamic', '-Wl,-ldl', '-Wl,--end-group'])
477
478 def test_compiler_args_remove_system(self):
479 ## Test --start/end-group
480 env = get_fake_env()
481 linker = linkers.GnuBFDDynamicLinker([], env, MachineChoice.HOST, ManyInOneLinkerOptionStyle('-Wl,', ','), [])
482 gcc = GnuCCompiler([], [], 'fake', MachineChoice.HOST, env, linker=linker)
483 ## Ensure that the fake compiler is never called by overriding the relevant function
484 gcc.get_default_include_dirs = lambda: ['/usr/include', '/usr/share/include', '/usr/local/include']
485 ## Test that 'direct' append and extend works
486 l = gcc.compiler_args(['-Lfoodir', '-lfoo'])
487 self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-lfoo'])
488 ## Test that to_native removes all system includes
489 l += ['-isystem/usr/include', '-isystem=/usr/share/include', '-DSOMETHING_IMPORTANT=1', '-isystem', '/usr/local/include']
490 self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-lfoo', '-DSOMETHING_IMPORTANT=1'])
491
492 def test_string_templates_substitution(self):
493 dictfunc = mesonbuild.mesonlib.get_filenames_templates_dict
494 substfunc = mesonbuild.mesonlib.substitute_values
495 ME = mesonbuild.mesonlib.MesonException
496
497 # Identity
498 self.assertEqual(dictfunc([], []), {})
499
500 # One input, no outputs
501 inputs = ['bar/foo.c.in']
502 outputs = []
503 ret = dictfunc(inputs, outputs)
504 d = {'@INPUT@': inputs, '@INPUT0@': inputs[0],
505 '@PLAINNAME0@': 'foo.c.in', '@BASENAME0@': 'foo.c',
506 '@PLAINNAME@': 'foo.c.in', '@BASENAME@': 'foo.c'}
507 # Check dictionary
508 self.assertEqual(ret, d)
509 # Check substitutions
510 cmd = ['some', 'ordinary', 'strings']
511 self.assertEqual(substfunc(cmd, d), cmd)
512 cmd = ['@[email protected]', 'ordinary', 'strings']
513 self.assertEqual(substfunc(cmd, d), [inputs[0] + '.out'] + cmd[1:])
514 cmd = ['@[email protected]', '@[email protected]', 'strings']
515 self.assertEqual(substfunc(cmd, d),
516 [inputs[0] + '.out'] + [d['@PLAINNAME@'] + '.ok'] + cmd[2:])
517 cmd = ['@INPUT@', '@[email protected]', 'strings']
518 self.assertEqual(substfunc(cmd, d),
519 inputs + [d['@BASENAME@'] + '.hah'] + cmd[2:])
520 cmd = ['@OUTPUT@']
521 self.assertRaises(ME, substfunc, cmd, d)
522
523 # One input, one output
524 inputs = ['bar/foo.c.in']
525 outputs = ['out.c']
526 ret = dictfunc(inputs, outputs)
527 d = {'@INPUT@': inputs, '@INPUT0@': inputs[0],
528 '@PLAINNAME0@': 'foo.c.in', '@BASENAME0@': 'foo.c',
529 '@PLAINNAME@': 'foo.c.in', '@BASENAME@': 'foo.c',
530 '@OUTPUT@': outputs, '@OUTPUT0@': outputs[0], '@OUTDIR@': '.'}
531 # Check dictionary
532 self.assertEqual(ret, d)
533 # Check substitutions
534 cmd = ['some', 'ordinary', 'strings']
535 self.assertEqual(substfunc(cmd, d), cmd)
536 cmd = ['@INPUT@ @OUTPUT@']
537 self.assertEqual(substfunc(cmd, d),
538 [f'{inputs[0]} {outputs[0]}'])
539 cmd = ['@[email protected]', '@OUTPUT@', 'strings']
540 self.assertEqual(substfunc(cmd, d),
541 [inputs[0] + '.out'] + outputs + cmd[2:])
542 cmd = ['@[email protected]', '@[email protected]', '@OUTPUT0@']
543 self.assertEqual(substfunc(cmd, d),
544 [inputs[0] + '.out', d['@PLAINNAME@'] + '.ok'] + outputs)
545 cmd = ['@INPUT@', '@[email protected]', 'strings']
546 self.assertEqual(substfunc(cmd, d),
547 inputs + [d['@BASENAME@'] + '.hah'] + cmd[2:])
548
549 # One input, one output with a subdir
550 outputs = ['dir/out.c']
551 ret = dictfunc(inputs, outputs)
552 d = {'@INPUT@': inputs, '@INPUT0@': inputs[0],
553 '@PLAINNAME0@': 'foo.c.in', '@BASENAME0@': 'foo.c',
554 '@PLAINNAME@': 'foo.c.in', '@BASENAME@': 'foo.c',
555 '@OUTPUT@': outputs, '@OUTPUT0@': outputs[0], '@OUTDIR@': 'dir'}
556 # Check dictionary
557 self.assertEqual(ret, d)
558
559 # Two inputs, no outputs
560 inputs = ['bar/foo.c.in', 'baz/foo.c.in']
561 outputs = []
562 ret = dictfunc(inputs, outputs)
563 d = {'@INPUT@': inputs, '@INPUT0@': inputs[0], '@INPUT1@': inputs[1],
564 '@PLAINNAME0@': 'foo.c.in', '@PLAINNAME1@': 'foo.c.in',
565 '@BASENAME0@': 'foo.c', '@BASENAME1@': 'foo.c'}
566 # Check dictionary
567 self.assertEqual(ret, d)
568 # Check substitutions
569 cmd = ['some', 'ordinary', 'strings']
570 self.assertEqual(substfunc(cmd, d), cmd)
571 cmd = ['@INPUT@', 'ordinary', 'strings']
572 self.assertEqual(substfunc(cmd, d), inputs + cmd[1:])
573 cmd = ['@[email protected]', 'ordinary', 'strings']
574 self.assertEqual(substfunc(cmd, d), [inputs[0] + '.out'] + cmd[1:])
575 cmd = ['@[email protected]', '@[email protected]', 'strings']
576 self.assertEqual(substfunc(cmd, d), [inputs[0] + '.out', inputs[1] + '.ok'] + cmd[2:])
577 cmd = ['@INPUT0@', '@INPUT1@', 'strings']
578 self.assertEqual(substfunc(cmd, d), inputs + cmd[2:])
579 # Many inputs, can't use @INPUT@ like this
580 cmd = ['@[email protected]', 'ordinary', 'strings']
581 self.assertRaises(ME, substfunc, cmd, d)
582 # Not enough inputs
583 cmd = ['@[email protected]', 'ordinary', 'strings']
584 self.assertRaises(ME, substfunc, cmd, d)
585 # Too many inputs
586 cmd = ['@PLAINNAME@']
587 self.assertRaises(ME, substfunc, cmd, d)
588 cmd = ['@BASENAME@']
589 self.assertRaises(ME, substfunc, cmd, d)
590 # No outputs
591 cmd = ['@OUTPUT@']
592 self.assertRaises(ME, substfunc, cmd, d)
593 cmd = ['@OUTPUT0@']
594 self.assertRaises(ME, substfunc, cmd, d)
595 cmd = ['@OUTDIR@']
596 self.assertRaises(ME, substfunc, cmd, d)
597
598 # Two inputs, one output
599 outputs = ['dir/out.c']
600 ret = dictfunc(inputs, outputs)
601 d = {'@INPUT@': inputs, '@INPUT0@': inputs[0], '@INPUT1@': inputs[1],
602 '@PLAINNAME0@': 'foo.c.in', '@PLAINNAME1@': 'foo.c.in',
603 '@BASENAME0@': 'foo.c', '@BASENAME1@': 'foo.c',
604 '@OUTPUT@': outputs, '@OUTPUT0@': outputs[0], '@OUTDIR@': 'dir'}
605 # Check dictionary
606 self.assertEqual(ret, d)
607 # Check substitutions
608 cmd = ['some', 'ordinary', 'strings']
609 self.assertEqual(substfunc(cmd, d), cmd)
610 cmd = ['@OUTPUT@', 'ordinary', 'strings']
611 self.assertEqual(substfunc(cmd, d), outputs + cmd[1:])
612 cmd = ['@[email protected]', 'ordinary', 'strings']
613 self.assertEqual(substfunc(cmd, d), [outputs[0] + '.out'] + cmd[1:])
614 cmd = ['@[email protected]', '@[email protected]', 'strings']
615 self.assertEqual(substfunc(cmd, d), [outputs[0] + '.out', inputs[1] + '.ok'] + cmd[2:])
616 # Many inputs, can't use @INPUT@ like this
617 cmd = ['@[email protected]', 'ordinary', 'strings']
618 self.assertRaises(ME, substfunc, cmd, d)
619 # Not enough inputs
620 cmd = ['@[email protected]', 'ordinary', 'strings']
621 self.assertRaises(ME, substfunc, cmd, d)
622 # Not enough outputs
623 cmd = ['@[email protected]', 'ordinary', 'strings']
624 self.assertRaises(ME, substfunc, cmd, d)
625
626 # Two inputs, two outputs
627 outputs = ['dir/out.c', 'dir/out2.c']
628 ret = dictfunc(inputs, outputs)
629 d = {'@INPUT@': inputs, '@INPUT0@': inputs[0], '@INPUT1@': inputs[1],
630 '@PLAINNAME0@': 'foo.c.in', '@PLAINNAME1@': 'foo.c.in',
631 '@BASENAME0@': 'foo.c', '@BASENAME1@': 'foo.c',
632 '@OUTPUT@': outputs, '@OUTPUT0@': outputs[0], '@OUTPUT1@': outputs[1],
633 '@OUTDIR@': 'dir'}
634 # Check dictionary
635 self.assertEqual(ret, d)
636 # Check substitutions
637 cmd = ['some', 'ordinary', 'strings']
638 self.assertEqual(substfunc(cmd, d), cmd)
639 cmd = ['@OUTPUT@', 'ordinary', 'strings']
640 self.assertEqual(substfunc(cmd, d), outputs + cmd[1:])
641 cmd = ['@OUTPUT0@', '@OUTPUT1@', 'strings']
642 self.assertEqual(substfunc(cmd, d), outputs + cmd[2:])
643 cmd = ['@[email protected]', '@[email protected]', '@OUTDIR@']
644 self.assertEqual(substfunc(cmd, d), [outputs[0] + '.out', inputs[1] + '.ok', 'dir'])
645 # Many inputs, can't use @INPUT@ like this
646 cmd = ['@[email protected]', 'ordinary', 'strings']
647 self.assertRaises(ME, substfunc, cmd, d)
648 # Not enough inputs
649 cmd = ['@[email protected]', 'ordinary', 'strings']
650 self.assertRaises(ME, substfunc, cmd, d)
651 # Not enough outputs
652 cmd = ['@[email protected]', 'ordinary', 'strings']
653 self.assertRaises(ME, substfunc, cmd, d)
654 # Many outputs, can't use @OUTPUT@ like this
655 cmd = ['@[email protected]', 'ordinary', 'strings']
656 self.assertRaises(ME, substfunc, cmd, d)
657
658 def test_needs_exe_wrapper_override(self):
659 config = ConfigParser()
660 config['binaries'] = {
661 'c': '\'/usr/bin/gcc\'',
662 }
663 config['host_machine'] = {
664 'system': '\'linux\'',
665 'cpu_family': '\'arm\'',
666 'cpu': '\'armv7\'',
667 'endian': '\'little\'',
668 }
669 # Can not be used as context manager because we need to
670 # open it a second time and this is not possible on
671 # Windows.
672 configfile = tempfile.NamedTemporaryFile(mode='w+', delete=False, encoding='utf-8')
673 configfilename = configfile.name
674 config.write(configfile)
675 configfile.flush()
676 configfile.close()
677 opts = get_fake_options()
678 opts.cross_file = (configfilename,)
679 env = get_fake_env(opts=opts)
680 detected_value = env.need_exe_wrapper()
681 os.unlink(configfilename)
682
683 desired_value = not detected_value
684 config['properties'] = {
685 'needs_exe_wrapper': 'true' if desired_value else 'false'
686 }
687
688 configfile = tempfile.NamedTemporaryFile(mode='w+', delete=False, encoding='utf-8')
689 configfilename = configfile.name
690 config.write(configfile)
691 configfile.close()
692 opts = get_fake_options()
693 opts.cross_file = (configfilename,)
694 env = get_fake_env(opts=opts)
695 forced_value = env.need_exe_wrapper()
696 os.unlink(configfilename)
697
698 self.assertEqual(forced_value, desired_value)
699
700 def test_listify(self):
701 listify = mesonbuild.mesonlib.listify
702 # Test sanity
703 self.assertEqual([1], listify(1))
704 self.assertEqual([], listify([]))
705 self.assertEqual([1], listify([1]))
706 # Test flattening
707 self.assertEqual([1, 2, 3], listify([1, [2, 3]]))
708 self.assertEqual([1, 2, 3], listify([1, [2, [3]]]))
709 self.assertEqual([1, [2, [3]]], listify([1, [2, [3]]], flatten=False))
710 # Test flattening and unholdering
711 class TestHeldObj(mesonbuild.mesonlib.HoldableObject):
712 def __init__(self, val: int) -> None:
713 self._val = val
714 class MockInterpreter:
715 def __init__(self) -> None:
716 self.subproject = ''
717 self.environment = None
718 heldObj1 = TestHeldObj(1)
719 holder1 = ObjectHolder(heldObj1, MockInterpreter())
720 self.assertEqual([holder1], listify(holder1))
721 self.assertEqual([holder1], listify([holder1]))
722 self.assertEqual([holder1, 2], listify([holder1, 2]))
723 self.assertEqual([holder1, 2, 3], listify([holder1, 2, [3]]))
724
725 def test_extract_as_list(self):
726 extract = mesonbuild.mesonlib.extract_as_list
727 # Test sanity
728 kwargs = {'sources': [1, 2, 3]}
729 self.assertEqual([1, 2, 3], extract(kwargs, 'sources'))
730 self.assertEqual(kwargs, {'sources': [1, 2, 3]})
731 self.assertEqual([1, 2, 3], extract(kwargs, 'sources', pop=True))
732 self.assertEqual(kwargs, {})
733
734 class TestHeldObj(mesonbuild.mesonlib.HoldableObject):
735 pass
736 class MockInterpreter:
737 def __init__(self) -> None:
738 self.subproject = ''
739 self.environment = None
740 heldObj = TestHeldObj()
741
742 # Test unholding
743 holder3 = ObjectHolder(heldObj, MockInterpreter())
744 kwargs = {'sources': [1, 2, holder3]}
745 self.assertEqual(kwargs, {'sources': [1, 2, holder3]})
746
747 # flatten nested lists
748 kwargs = {'sources': [1, [2, [3]]]}
749 self.assertEqual([1, 2, 3], extract(kwargs, 'sources'))
750
751 def _test_all_naming(self, cc, patterns, platform):
752 shr = patterns[platform]['shared']
753 stc = patterns[platform]['static']
754 shrstc = shr + tuple(x for x in stc if x not in shr)
755 stcshr = stc + tuple(x for x in shr if x not in stc)
756 p = cc.get_library_naming(LibType.SHARED)
757 self.assertEqual(p, shr)
758 p = cc.get_library_naming(LibType.STATIC)
759 self.assertEqual(p, stc)
760 p = cc.get_library_naming(LibType.PREFER_STATIC)
761 self.assertEqual(p, stcshr)
762 p = cc.get_library_naming(LibType.PREFER_SHARED)
763 self.assertEqual(p, shrstc)
764 # Test find library by mocking up openbsd
765 if platform != 'openbsd':
766 return
767 with tempfile.TemporaryDirectory() as tmpdir:
768 for i in ['libfoo.so.6.0', 'libfoo.so.5.0', 'libfoo.so.54.0', 'libfoo.so.66a.0b', 'libfoo.so.70.0.so.1',
769 'libbar.so.7.10', 'libbar.so.7.9', 'libbar.so.7.9.3']:
770 libpath = Path(tmpdir) / i
771 src = libpath.with_suffix('.c')
772 with src.open('w', encoding='utf-8') as f:
773 f.write('int meson_foobar (void) { return 0; }')
774 subprocess.check_call(['gcc', str(src), '-o', str(libpath), '-shared'])
775
776 found = cc._find_library_real('foo', [tmpdir], 'int main(void) { return 0; }', LibType.PREFER_SHARED, lib_prefix_warning=True, ignore_system_dirs=False)
777 self.assertEqual(os.path.basename(found[0]), 'libfoo.so.54.0')
778 found = cc._find_library_real('bar', [tmpdir], 'int main(void) { return 0; }', LibType.PREFER_SHARED, lib_prefix_warning=True, ignore_system_dirs=False)
779 self.assertEqual(os.path.basename(found[0]), 'libbar.so.7.10')
780
781 def test_find_library_patterns(self):
782 '''
783 Unit test for the library search patterns used by find_library()
784 '''
785 unix_static = ('lib{}.a', '{}.a')
786 msvc_static = ('lib{}.a', 'lib{}.lib', '{}.a', '{}.lib')
787 # This is the priority list of pattern matching for library searching
788 patterns = {'openbsd': {'shared': ('lib{}.so', '{}.so', 'lib{}.so.[0-9]*.[0-9]*', '{}.so.[0-9]*.[0-9]*'),
789 'static': unix_static},
790 'linux': {'shared': ('lib{}.so', '{}.so'),
791 'static': unix_static},
792 'darwin': {'shared': ('lib{}.dylib', 'lib{}.so', '{}.dylib', '{}.so'),
793 'static': unix_static},
794 'cygwin': {'shared': ('cyg{}.dll', 'cyg{}.dll.a', 'lib{}.dll',
795 'lib{}.dll.a', '{}.dll', '{}.dll.a'),
796 'static': ('cyg{}.a',) + unix_static},
797 'windows-msvc': {'shared': ('lib{}.lib', '{}.lib'),
798 'static': msvc_static},
799 'windows-mingw': {'shared': ('lib{}.dll.a', 'lib{}.lib', 'lib{}.dll',
800 '{}.dll.a', '{}.lib', '{}.dll'),
801 'static': msvc_static}}
802 env = get_fake_env()
803 cc = detect_c_compiler(env, MachineChoice.HOST)
804 if is_osx():
805 self._test_all_naming(cc, patterns, 'darwin')
806 elif is_cygwin():
807 self._test_all_naming(cc, patterns, 'cygwin')
808 elif is_windows():
809 if cc.get_argument_syntax() == 'msvc':
810 self._test_all_naming(cc, patterns, 'windows-msvc')
811 else:
812 self._test_all_naming(cc, patterns, 'windows-mingw')
813 elif is_openbsd():
814 self._test_all_naming(cc, patterns, 'openbsd')
815 else:
816 self._test_all_naming(cc, patterns, 'linux')
817 env.machines.host.system = 'openbsd'
818 self._test_all_naming(cc, patterns, 'openbsd')
819 env.machines.host.system = 'darwin'
820 self._test_all_naming(cc, patterns, 'darwin')
821 env.machines.host.system = 'cygwin'
822 self._test_all_naming(cc, patterns, 'cygwin')
823 env.machines.host.system = 'windows'
824 self._test_all_naming(cc, patterns, 'windows-mingw')
825
826 self._test_find_library_undefined(cc)
827
828 def _test_find_library_undefined(self, cc):
829 '''
830 find_library checks if its argument both exists and can be
831 linked against, but it must tolerate underlinked static
832 libraries.
833
834 https://github.com/mesonbuild/meson/issues/15601
835 '''
836 def create_static_lib_with_undefined(name):
837 src = name.with_suffix('.c')
838 out = name.with_suffix('.o')
839 with src.open('w', encoding='utf-8') as f:
840 f.write('extern int get_cookie();')
841 f.write('int meson_foobar (void) { return get_cookie(); }')
842 # use of x86_64 is hardcoded in run_tests.py:get_fake_env()
843 if is_osx():
844 subprocess.check_call(['clang', '-c', str(src), '-o', str(out), '-arch', 'x86_64'])
845 else:
846 subprocess.check_call(['gcc', '-c', str(src), '-o', str(out)])
847 subprocess.check_call(['ar', 'csr', str(name), str(out)])
848
849 def create_static_lib_empty(name):
850 with name.open('w', encoding='utf-8') as f:
851 f.write("garbage")
852
853 # The test relies on some open-coded toolchain invocations for
854 # library creation in create_static_lib_with_undefined.
855 if is_windows() or is_cygwin():
856 return
857
858 with tempfile.TemporaryDirectory() as tmpdir:
859 p1 = Path(tmpdir)
860 create_static_lib_with_undefined(p1 / 'libfoo.a')
861
862 code = 'int meson_foobar (void); int main(void) { return meson_foobar(); }'
863
864 # Check that we always tolerate undefined references in a static
865 # library regardless of the library type.
866 for type in (LibType.STATIC, LibType.PREFER_STATIC, LibType.PREFER_SHARED):
867 found = cc._find_library_real('foo', [tmpdir],
868 code,
869 type, lib_prefix_warning=True, ignore_system_dirs=False)
870 self.assertEqual(os.path.basename(found[0]), 'libfoo.a')
871
872 # Check that we reject broken static libraries unless we were
873 # told to only find a static library.
874 create_static_lib_empty(p1 / 'libbar.a')
875
876 # We have a broken static library *and* we indicated we want a static
877 # library, so we don't perform a link test.
878 found = cc._find_library_real('bar', [tmpdir],
879 code,
880 LibType.STATIC, lib_prefix_warning=True, ignore_system_dirs=False)
881 self.assertEqual(os.path.basename(found[0]), 'libbar.a')
882
883 # We have a broken static library we're testing against but we only said
884 # we'd prefer static, not that it must be static: the heuristic
885 # says it likely isn't a special toolchain library, so we perform a
886 # link test.
887 found = cc._find_library_real('bar', [tmpdir],
888 code,
889 LibType.PREFER_STATIC, lib_prefix_warning=True, ignore_system_dirs=False)
890 self.assertIsNone(found, 'Unexpectedly found a library with PREFER_STATIC, link test expected to reject it')
891
892 # We have a broken static library we're testing against but we only said
893 # we'd prefer shared, not that it must be shared: the heuristic
894 # says it likely isn't a special toolchain library, so we perform a
895 # link test.
896 found = cc._find_library_real('bar', [tmpdir],
897 code,
898 LibType.PREFER_SHARED, lib_prefix_warning=True, ignore_system_dirs=False)
899 self.assertIsNone(found, 'Unexpectedly found a library with PREFER_SHARED, link test expected to reject it')
900
901 # We asked for a shared library and we only got a broken
902 # static one. We only tolerate them being broken if people
903 # explicitly ask for it w/ static: true, so we perform a link
904 # test.
905 found = cc._find_library_real('bar', [tmpdir],
906 code,
907 LibType.SHARED, lib_prefix_warning=True, ignore_system_dirs=False)
908 self.assertIsNone(found, 'Unexpectedly found a library with SHARED')
909
910 @skipIfNoPkgconfig
911 def test_pkgconfig_parse_libs(self):
912 '''
913 Unit test for parsing of pkg-config output to search for libraries
914
915 https://github.com/mesonbuild/meson/issues/3951
916 '''
917 def create_static_lib(name):
918 src = name.with_suffix('.c')
919 out = name.with_suffix('.o')
920 with src.open('w', encoding='utf-8') as f:
921 f.write('int meson_foobar (void) { return 0; }')
922 # use of x86_64 is hardcoded in run_tests.py:get_fake_env()
923 if is_osx():
924 subprocess.check_call(['clang', '-c', str(src), '-o', str(out), '-arch', 'x86_64'])
925 else:
926 subprocess.check_call(['gcc', '-c', str(src), '-o', str(out)])
927 subprocess.check_call(['ar', 'csr', str(name), str(out)])
928
929 # The test relies on some open-coded toolchain invocations for
930 # library creation in create_static_lib.
931 if is_windows() or is_cygwin():
932 return
933
934 with tempfile.TemporaryDirectory() as tmpdir:
935 pkgbin = ExternalProgram('pkg-config', command=['pkg-config'], silent=True)
936 env = get_fake_env()
937 compiler = detect_c_compiler(env, MachineChoice.HOST)
938 env.coredata.compilers.host = {'c': compiler}
939 p1 = Path(tmpdir) / '1'
940 p2 = Path(tmpdir) / '2'
941 p1.mkdir()
942 p2.mkdir()
943 # libfoo.a is in one prefix
944 create_static_lib(p1 / 'libfoo.a')
945 # libbar.a is in both prefixes
946 create_static_lib(p1 / 'libbar.a')
947 create_static_lib(p2 / 'libbar.a')
948 # Ensure that we never statically link to these
949 create_static_lib(p1 / 'libpthread.a')
950 create_static_lib(p1 / 'libm.a')
951 create_static_lib(p1 / 'libc.a')
952 create_static_lib(p1 / 'libdl.a')
953 create_static_lib(p1 / 'librt.a')
954
955 class FakeInstance(PkgConfigCLI):
956 def _call_pkgbin(self, args, env=None):
957 if '--libs' not in args:
958 return 0, '', ''
959 if args[-1] == 'foo':
960 return 0, f'-L{p2.as_posix()} -lfoo -L{p1.as_posix()} -lbar', ''
961 if args[-1] == 'bar':
962 return 0, f'-L{p2.as_posix()} -lbar', ''
963 if args[-1] == 'internal':
964 return 0, f'-L{p1.as_posix()} -lpthread -lm -lc -lrt -ldl', ''
965
966 with mock.patch.object(PkgConfigInterface, 'instance') as instance_method:
967 instance_method.return_value = FakeInstance(env, MachineChoice.HOST, silent=True)
968 kwargs = {'required': True, 'silent': True, 'native': MachineChoice.HOST}
969 foo_dep = PkgConfigDependency('foo', env, kwargs)
970 self.assertEqual(foo_dep.get_link_args(),
971 [(p1 / 'libfoo.a').as_posix(), (p2 / 'libbar.a').as_posix()])
972 bar_dep = PkgConfigDependency('bar', env, kwargs)
973 self.assertEqual(bar_dep.get_link_args(), [(p2 / 'libbar.a').as_posix()])
974 internal_dep = PkgConfigDependency('internal', env, kwargs)
975 if compiler.get_argument_syntax() == 'msvc':
976 self.assertEqual(internal_dep.get_link_args(), [])
977 else:
978 link_args = internal_dep.get_link_args()
979 for link_arg in link_args:
980 for lib in ('pthread', 'm', 'c', 'dl', 'rt'):
981 self.assertNotIn(f'lib{lib}.a', link_arg, msg=link_args)
982
983 def test_program_version(self) -> None:
984 with tempfile.TemporaryDirectory() as tmpdir:
985 script_path = Path(tmpdir) / 'script.py'
986 script_path.write_text('import sys\nprint(sys.argv[1])\n', encoding='utf-8')
987 script_path.chmod(0o755)
988
989 inputs: list[tuple[str, str | None]] = [
990 ('', None),
991 ('1', None),
992 ('1.2.4', '1.2.4'),
993 ('1 1.2.4', '1.2.4'),
994 ('foo version 1.2.4', '1.2.4'),
995 ('foo 1.2.4.', '1.2.4'),
996 ('foo 1.2.4', '1.2.4'),
997 ('foo 1.2.4 bar', '1.2.4'),
998 ('foo 10.0.0', '10.0.0'),
999 ('50 5.4.0', '5.4.0'),
1000 ('This is perl 5, version 40, subversion 0 (v5.40.0)', '5.40.0'),
1001 ('git version 2.48.0.rc1', '2.48.0'),
1002 ]
1003
1004 for output, expected in inputs:
1005 prog = ExternalProgram('script', command=python_command + [str(script_path), output], silent=True)
1006
1007 with self.subTest(output=output, expected=expected):
1008 if expected is None:
1009 with self.assertRaisesRegex(MesonException, 'Could not find a version number'):
1010 prog.get_version()
1011 else:
1012 self.assertEqual(prog.get_version(), expected)
1013
1014 def test_version_compare(self):
1015 comparefunc = mesonbuild.mesonlib.version_compare_many
1016 for (a, b, result) in [
1017 ('0.99.beta19', '>= 0.99.beta14', True),
1018 ]:
1019 self.assertEqual(comparefunc(a, b)[0], result)
1020
1021 for (a, b, op) in [
1022 # examples from https://fedoraproject.org/wiki/Archive:Tools/RPM/VersionComparison
1023 ("1.0010", "1.9", operator.gt),
1024 ("1.05", "1.5", operator.eq),
1025 ("1.0", "1", operator.gt),
1026 ("2.50", "2.5", operator.gt),
1027 ("fc4", "fc.4", operator.eq),
1028 ("FC5", "fc4", operator.lt),
1029 ("2a", "2.0", operator.lt),
1030 ("1.0", "1.fc4", operator.gt),
1031 ("3.0.0_fc", "3.0.0.fc", operator.eq),
1032 # from RPM tests
1033 ("1.0", "1.0", operator.eq),
1034 ("1.0", "2.0", operator.lt),
1035 ("2.0", "1.0", operator.gt),
1036 ("2.0.1", "2.0.1", operator.eq),
1037 ("2.0", "2.0.1", operator.lt),
1038 ("2.0.1", "2.0", operator.gt),
1039 ("2.0.1a", "2.0.1a", operator.eq),
1040 ("2.0.1a", "2.0.1", operator.gt),
1041 ("2.0.1", "2.0.1a", operator.lt),
1042 ("5.5p1", "5.5p1", operator.eq),
1043 ("5.5p1", "5.5p2", operator.lt),
1044 ("5.5p2", "5.5p1", operator.gt),
1045 ("5.5p10", "5.5p10", operator.eq),
1046 ("5.5p1", "5.5p10", operator.lt),
1047 ("5.5p10", "5.5p1", operator.gt),
1048 ("10xyz", "10.1xyz", operator.lt),
1049 ("10.1xyz", "10xyz", operator.gt),
1050 ("xyz10", "xyz10", operator.eq),
1051 ("xyz10", "xyz10.1", operator.lt),
1052 ("xyz10.1", "xyz10", operator.gt),
1053 ("xyz.4", "xyz.4", operator.eq),
1054 ("xyz.4", "8", operator.lt),
1055 ("8", "xyz.4", operator.gt),
1056 ("xyz.4", "2", operator.lt),
1057 ("2", "xyz.4", operator.gt),
1058 ("5.5p2", "5.6p1", operator.lt),
1059 ("5.6p1", "5.5p2", operator.gt),
1060 ("5.6p1", "6.5p1", operator.lt),
1061 ("6.5p1", "5.6p1", operator.gt),
1062 ("6.0.rc1", "6.0", operator.gt),
1063 ("6.0", "6.0.rc1", operator.lt),
1064 ("10b2", "10a1", operator.gt),
1065 ("10a2", "10b2", operator.lt),
1066 ("1.0aa", "1.0aa", operator.eq),
1067 ("1.0a", "1.0aa", operator.lt),
1068 ("1.0aa", "1.0a", operator.gt),
1069 ("10.0001", "10.0001", operator.eq),
1070 ("10.0001", "10.1", operator.eq),
1071 ("10.1", "10.0001", operator.eq),
1072 ("10.0001", "10.0039", operator.lt),
1073 ("10.0039", "10.0001", operator.gt),
1074 ("4.999.9", "5.0", operator.lt),
1075 ("5.0", "4.999.9", operator.gt),
1076 ("20101121", "20101121", operator.eq),
1077 ("20101121", "20101122", operator.lt),
1078 ("20101122", "20101121", operator.gt),
1079 ("2_0", "2_0", operator.eq),
1080 ("2.0", "2_0", operator.eq),
1081 ("2_0", "2.0", operator.eq),
1082 ("a", "a", operator.eq),
1083 ("a+", "a+", operator.eq),
1084 ("a+", "a_", operator.eq),
1085 ("a_", "a+", operator.eq),
1086 ("+a", "+a", operator.eq),
1087 ("+a", "_a", operator.eq),
1088 ("_a", "+a", operator.eq),
1089 ("+_", "+_", operator.eq),
1090 ("_+", "+_", operator.eq),
1091 ("_+", "_+", operator.eq),
1092 ("+", "_", operator.eq),
1093 ("_", "+", operator.eq),
1094 # other tests
1095 ('0.99.beta19', '0.99.beta14', operator.gt),
1096 ("1.0.0", "2.0.0", operator.lt),
1097 (".0.0", "2.0.0", operator.lt),
1098 ("alpha", "beta", operator.lt),
1099 ("1.0", "1.0.0", operator.lt),
1100 ("2.456", "2.1000", operator.lt),
1101 ("2.1000", "3.111", operator.lt),
1102 ("2.001", "2.1", operator.eq),
1103 ("2.34", "2.34", operator.eq),
1104 ("6.1.2", "6.3.8", operator.lt),
1105 ("1.7.3.0", "2.0.0", operator.lt),
1106 ("2.24.51", "2.25", operator.lt),
1107 ("2.1.5+20120813+gitdcbe778", "2.1.5", operator.gt),
1108 ("3.4.1", "3.4b1", operator.gt),
1109 ("041206", "200090325", operator.lt),
1110 ("0.6.2+git20130413", "0.6.2", operator.gt),
1111 ("2.6.0+bzr6602", "2.6.0", operator.gt),
1112 ("2.6.0", "2.6b2", operator.gt),
1113 ("2.6.0+bzr6602", "2.6b2x", operator.gt),
1114 ("0.6.7+20150214+git3a710f9", "0.6.7", operator.gt),
1115 ("15.8b", "15.8.0.1", operator.lt),
1116 ("1.2rc1", "1.2.0", operator.lt),
1117 ]:
1118 ver_a = Version(a)
1119 ver_b = Version(b)
1120 if op is operator.eq:
1121 for o, name in [(op, 'eq'), (operator.ge, 'ge'), (operator.le, 'le')]:
1122 self.assertTrue(o(ver_a, ver_b), f'{ver_a} {name} {ver_b}')
1123 if op is operator.lt:
1124 for o, name in [(op, 'lt'), (operator.le, 'le'), (operator.ne, 'ne')]:
1125 self.assertTrue(o(ver_a, ver_b), f'{ver_a} {name} {ver_b}')
1126 for o, name in [(operator.gt, 'gt'), (operator.ge, 'ge'), (operator.eq, 'eq')]:
1127 self.assertFalse(o(ver_a, ver_b), f'{ver_a} {name} {ver_b}')
1128 if op is operator.gt:
1129 for o, name in [(op, 'gt'), (operator.ge, 'ge'), (operator.ne, 'ne')]:
1130 self.assertTrue(o(ver_a, ver_b), f'{ver_a} {name} {ver_b}')
1131 for o, name in [(operator.lt, 'lt'), (operator.le, 'le'), (operator.eq, 'eq')]:
1132 self.assertFalse(o(ver_a, ver_b), f'{ver_a} {name} {ver_b}')
1133
1134 def test_split_args(self):
1135 split_args = mesonbuild.mesonlib.split_args
1136 join_args = mesonbuild.mesonlib.join_args
1137 if is_windows():
1138 test_data = [
1139 # examples from https://docs.microsoft.com/en-us/cpp/c-language/parsing-c-command-line-arguments
1140 (r'"a b c" d e', ['a b c', 'd', 'e'], True),
1141 (r'"ab\"c" "\\" d', ['ab"c', '\\', 'd'], False),
1142 (r'a\\\b d"e f"g h', [r'a\\\b', 'de fg', 'h'], False),
1143 (r'a\\\"b c d', [r'a\"b', 'c', 'd'], False),
1144 (r'a\\\\"b c" d e', [r'a\\b c', 'd', 'e'], False),
1145 # other basics
1146 (r'""', [''], True),
1147 (r'a b c d "" e', ['a', 'b', 'c', 'd', '', 'e'], True),
1148 (r"'a b c' d e", ["'a", 'b', "c'", 'd', 'e'], True),
1149 (r"'a&b&c' d e", ["'a&b&c'", 'd', 'e'], True),
1150 (r"a & b & c d e", ['a', '&', 'b', '&', 'c', 'd', 'e'], True),
1151 (r"'a & b & c d e'", ["'a", '&', 'b', '&', 'c', 'd', "e'"], True),
1152 ('a b\nc\rd \n\re', ['a', 'b', 'c', 'd', 'e'], False),
1153 # more illustrative tests
1154 (r'cl test.cpp /O1 /Fe:test.exe', ['cl', 'test.cpp', '/O1', '/Fe:test.exe'], True),
1155 (r'cl "test.cpp /O1 /Fe:test.exe"', ['cl', 'test.cpp /O1 /Fe:test.exe'], True),
1156 (r'cl /DNAME=\"Bob\" test.cpp', ['cl', '/DNAME="Bob"', 'test.cpp'], False),
1157 (r'cl "/DNAME=\"Bob\"" test.cpp', ['cl', '/DNAME="Bob"', 'test.cpp'], True),
1158 (r'cl /DNAME=\"Bob, Alice\" test.cpp', ['cl', '/DNAME="Bob,', 'Alice"', 'test.cpp'], False),
1159 (r'cl "/DNAME=\"Bob, Alice\"" test.cpp', ['cl', '/DNAME="Bob, Alice"', 'test.cpp'], True),
1160 (r'cl C:\path\with\backslashes.cpp', ['cl', r'C:\path\with\backslashes.cpp'], True),
1161 (r'cl C:\\path\\with\\double\\backslashes.cpp', ['cl', r'C:\\path\\with\\double\\backslashes.cpp'], True),
1162 (r'cl "C:\\path\\with\\double\\backslashes.cpp"', ['cl', r'C:\\path\\with\\double\\backslashes.cpp'], False),
1163 (r'cl C:\path with spaces\test.cpp', ['cl', r'C:\path', 'with', r'spaces\test.cpp'], False),
1164 (r'cl "C:\path with spaces\test.cpp"', ['cl', r'C:\path with spaces\test.cpp'], True),
1165 (r'cl /DPATH="C:\path\with\backslashes test.cpp', ['cl', r'/DPATH=C:\path\with\backslashes test.cpp'], False),
1166 (r'cl /DPATH=\"C:\\ends\\with\\backslashes\\\" test.cpp', ['cl', r'/DPATH="C:\\ends\\with\\backslashes\"', 'test.cpp'], False),
1167 (r'cl /DPATH="C:\\ends\\with\\backslashes\\" test.cpp', ['cl', '/DPATH=C:\\\\ends\\\\with\\\\backslashes\\', 'test.cpp'], False),
1168 (r'cl "/DNAME=\"C:\\ends\\with\\backslashes\\\"" test.cpp', ['cl', r'/DNAME="C:\\ends\\with\\backslashes\"', 'test.cpp'], True),
1169 (r'cl "/DNAME=\"C:\\ends\\with\\backslashes\\\\"" test.cpp', ['cl', r'/DNAME="C:\\ends\\with\\backslashes\\ test.cpp'], False),
1170 (r'cl "/DNAME=\"C:\\ends\\with\\backslashes\\\\\"" test.cpp', ['cl', r'/DNAME="C:\\ends\\with\\backslashes\\"', 'test.cpp'], True),
1171 ]
1172 else:
1173 test_data = [
1174 (r"'a b c' d e", ['a b c', 'd', 'e'], True),
1175 (r"a/b/c d e", ['a/b/c', 'd', 'e'], True),
1176 (r"a\b\c d e", [r'abc', 'd', 'e'], False),
1177 (r"a\\b\\c d e", [r'a\b\c', 'd', 'e'], False),
1178 (r'"a b c" d e', ['a b c', 'd', 'e'], False),
1179 (r'"a\\b\\c\\" d e', ['a\\b\\c\\', 'd', 'e'], False),
1180 (r"'a\b\c\' d e", ['a\\b\\c\\', 'd', 'e'], True),
1181 (r"'a&b&c' d e", ['a&b&c', 'd', 'e'], True),
1182 (r"a & b & c d e", ['a', '&', 'b', '&', 'c', 'd', 'e'], False),
1183 (r"'a & b & c d e'", ['a & b & c d e'], True),
1184 (r"abd'e f'g h", [r'abde fg', 'h'], False),
1185 ('a b\nc\rd \n\re', ['a', 'b', 'c', 'd', 'e'], False),
1186
1187 ('g++ -DNAME="Bob" test.cpp', ['g++', '-DNAME=Bob', 'test.cpp'], False),
1188 ("g++ '-DNAME=\"Bob\"' test.cpp", ['g++', '-DNAME="Bob"', 'test.cpp'], True),
1189 ('g++ -DNAME="Bob, Alice" test.cpp', ['g++', '-DNAME=Bob, Alice', 'test.cpp'], False),
1190 ("g++ '-DNAME=\"Bob, Alice\"' test.cpp", ['g++', '-DNAME="Bob, Alice"', 'test.cpp'], True),
1191 ]
1192
1193 for (cmd, expected, roundtrip) in test_data:
1194 self.assertEqual(split_args(cmd), expected)
1195 if roundtrip:
1196 self.assertEqual(join_args(expected), cmd)
1197
1198 def test_quote_arg(self):
1199 split_args = mesonbuild.mesonlib.split_args
1200 quote_arg = mesonbuild.mesonlib.quote_arg
1201 if is_windows():
1202 test_data = [
1203 ('', '""'),
1204 ('arg1', 'arg1'),
1205 ('/option1', '/option1'),
1206 ('/Ovalue', '/Ovalue'),
1207 ('/OBob&Alice', '/OBob&Alice'),
1208 ('/Ovalue with spaces', r'"/Ovalue with spaces"'),
1209 (r'/O"value with spaces"', r'"/O\"value with spaces\""'),
1210 (r'/OC:\path with spaces\test.exe', r'"/OC:\path with spaces\test.exe"'),
1211 ('/LIBPATH:C:\\path with spaces\\ends\\with\\backslashes\\', r'"/LIBPATH:C:\path with spaces\ends\with\backslashes\\"'),
1212 ('/LIBPATH:"C:\\path with spaces\\ends\\with\\backslashes\\\\"', r'"/LIBPATH:\"C:\path with spaces\ends\with\backslashes\\\\\""'),
1213 (r'/DMSG="Alice said: \"Let\'s go\""', r'"/DMSG=\"Alice said: \\\"Let\'s go\\\"\""'),
1214 ]
1215 else:
1216 test_data = [
1217 ('arg1', 'arg1'),
1218 ('--option1', '--option1'),
1219 ('-O=value', '-O=value'),
1220 ('-O=Bob&Alice', "'-O=Bob&Alice'"),
1221 ('-O=value with spaces', "'-O=value with spaces'"),
1222 ('-O="value with spaces"', '\'-O=\"value with spaces\"\''),
1223 ('-O=/path with spaces/test', '\'-O=/path with spaces/test\''),
1224 ('-DMSG="Alice said: \\"Let\'s go\\""', "'-DMSG=\"Alice said: \\\"Let'\"'\"'s go\\\"\"'"),
1225 ]
1226
1227 for (arg, expected) in test_data:
1228 self.assertEqual(quote_arg(arg), expected)
1229 self.assertEqual(split_args(expected)[0], arg)
1230
1231 def test_depfile(self):
1232 for (f, target, expdeps) in [
1233 # empty, unknown target
1234 ([''], 'unknown', set()),
1235 # simple target & deps
1236 (['meson/foo.o : foo.c foo.h'], 'meson/foo.o', set({'foo.c', 'foo.h'})),
1237 (['meson/foo.o: foo.c foo.h'], 'foo.c', set()),
1238 # get all deps
1239 (['meson/foo.o: foo.c foo.h',
1240 'foo.c: gen.py'], 'meson/foo.o', set({'foo.c', 'foo.h', 'gen.py'})),
1241 (['meson/foo.o: foo.c foo.h',
1242 'foo.c: gen.py'], 'foo.c', set({'gen.py'})),
1243 # linue continuation, multiple targets
1244 (['foo.o \\', 'foo.h: bar'], 'foo.h', set({'bar'})),
1245 (['foo.o \\', 'foo.h: bar'], 'foo.o', set({'bar'})),
1246 # \\ handling
1247 (['foo: Program\\ F\\iles\\\\X'], 'foo', set({'Program Files\\X'})),
1248 # $ handling
1249 (['f$o.o: c/b'], 'f$o.o', set({'c/b'})),
1250 (['f$$o.o: c/b'], 'f$o.o', set({'c/b'})),
1251 # cycles
1252 (['a: b', 'b: a'], 'a', set({'a', 'b'})),
1253 (['a: b', 'b: a'], 'b', set({'a', 'b'})),
1254 ]:
1255 d = mesonbuild.depfile.DepFile(f)
1256 deps = d.get_all_dependencies(target)
1257 self.assertEqual(sorted(deps), sorted(expdeps))
1258
1259 def test_log_once(self):
1260 f = io.StringIO()
1261 with mock.patch('mesonbuild.mlog._logger.log_file', f), \
1262 mock.patch('mesonbuild.mlog._logger.logged_once', set()):
1263 mesonbuild.mlog.log('foo', once=True)
1264 mesonbuild.mlog.log('foo', once=True)
1265 actual = f.getvalue().strip()
1266 self.assertEqual(actual, 'foo', actual)
1267
1268 def test_log_once_ansi(self):
1269 f = io.StringIO()
1270 with mock.patch('mesonbuild.mlog._logger.log_file', f), \
1271 mock.patch('mesonbuild.mlog._logger.logged_once', set()):
1272 mesonbuild.mlog.log(mesonbuild.mlog.bold('foo'), once=True)
1273 mesonbuild.mlog.log(mesonbuild.mlog.bold('foo'), once=True)
1274 actual = f.getvalue().strip()
1275 self.assertEqual(actual.count('foo'), 1, actual)
1276
1277 mesonbuild.mlog.log('foo', once=True)
1278 actual = f.getvalue().strip()
1279 self.assertEqual(actual.count('foo'), 1, actual)
1280
1281 f.truncate()
1282
1283 mesonbuild.mlog.warning('bar', once=True)
1284 mesonbuild.mlog.warning('bar', once=True)
1285 actual = f.getvalue().strip()
1286 self.assertEqual(actual.count('bar'), 1, actual)
1287
1288 def test_sort_libpaths(self):
1289 sort_libpaths = mesonbuild.dependencies.base.sort_libpaths
1290 self.assertEqual(sort_libpaths(
1291 ['/home/mesonuser/.local/lib', '/usr/local/lib', '/usr/lib'],
1292 ['/home/mesonuser/.local/lib/pkgconfig', '/usr/local/lib/pkgconfig']),
1293 ['/home/mesonuser/.local/lib', '/usr/local/lib', '/usr/lib'])
1294 self.assertEqual(sort_libpaths(
1295 ['/usr/local/lib', '/home/mesonuser/.local/lib', '/usr/lib'],
1296 ['/home/mesonuser/.local/lib/pkgconfig', '/usr/local/lib/pkgconfig']),
1297 ['/home/mesonuser/.local/lib', '/usr/local/lib', '/usr/lib'])
1298 self.assertEqual(sort_libpaths(
1299 ['/usr/lib', '/usr/local/lib', '/home/mesonuser/.local/lib'],
1300 ['/home/mesonuser/.local/lib/pkgconfig', '/usr/local/lib/pkgconfig']),
1301 ['/home/mesonuser/.local/lib', '/usr/local/lib', '/usr/lib'])
1302 self.assertEqual(sort_libpaths(
1303 ['/usr/lib', '/usr/local/lib', '/home/mesonuser/.local/lib'],
1304 ['/home/mesonuser/.local/lib/pkgconfig', '/usr/local/libdata/pkgconfig']),
1305 ['/home/mesonuser/.local/lib', '/usr/local/lib', '/usr/lib'])
1306
1307 def test_dependency_factory_order(self):
1308 b = mesonbuild.dependencies.base
1309 F = mesonbuild.dependencies.factory
1310 with tempfile.TemporaryDirectory() as tmpdir:
1311 with chdir(tmpdir):
1312 env = get_fake_env()
1313 env.scratch_dir = tmpdir
1314
1315 f = F.DependencyFactory(
1316 'test_dep',
1317 methods=[b.DependencyMethods.PKGCONFIG, b.DependencyMethods.CMAKE]
1318 )
1319 actual = [m() for m in f(env, {'required': False, 'native': MachineChoice.HOST})]
1320 self.assertListEqual([m.type_name for m in actual], ['pkgconfig', 'cmake'])
1321
1322 f = F.DependencyFactory(
1323 'test_dep',
1324 methods=[b.DependencyMethods.CMAKE, b.DependencyMethods.PKGCONFIG]
1325 )
1326 actual = [m() for m in f(env, {'required': False, 'native': MachineChoice.HOST})]
1327 self.assertListEqual([m.type_name for m in actual], ['cmake', 'pkgconfig'])
1328
1329 def test_validate_json(self) -> None:
1330 """Validate the json schema for the test cases."""
1331 try:
1332 from fastjsonschema import compile, JsonSchemaValueException as JsonSchemaFailure
1333 fast = True
1334 except ImportError:
1335 try:
1336 from jsonschema import validate, ValidationError as JsonSchemaFailure
1337 fast = False
1338 except:
1339 if IS_CI:
1340 raise
1341 raise unittest.SkipTest('neither Python fastjsonschema nor jsonschema module not found.')
1342
1343 with open('data/test.schema.json', 'r', encoding='utf-8') as f:
1344 data = json.loads(f.read())
1345
1346 if fast:
1347 schema_validator = compile(data)
1348 else:
1349 schema_validator = lambda x: validate(x, schema=data)
1350
1351 errors: T.List[T.Tuple[Path, Exception]] = []
1352 for p in Path('test cases').glob('**/test.json'):
1353 try:
1354 schema_validator(json.loads(p.read_text(encoding='utf-8')))
1355 except JsonSchemaFailure as e:
1356 errors.append((p.resolve(), e))
1357
1358 for f, e in errors:
1359 print(f'Failed to validate: "{f}"')
1360 print(str(e))
1361
1362 self.assertFalse(errors)
1363
1364 def test_typed_pos_args_types(self) -> None:
1365 @typed_pos_args('foo', str, int, bool)
1366 def _(obj, node, args: T.Tuple[str, int, bool], kwargs) -> None:
1367 self.assertIsInstance(args, tuple)
1368 self.assertIsInstance(args[0], str)
1369 self.assertIsInstance(args[1], int)
1370 self.assertIsInstance(args[2], bool)
1371
1372 _(None, mock.Mock(), ['string', 1, False], None)
1373
1374 def test_typed_pos_args_types_invalid(self) -> None:
1375 @typed_pos_args('foo', str, int, bool)
1376 def _(obj, node, args: T.Tuple[str, int, bool], kwargs) -> None:
1377 self.assertTrue(False) # should not be reachable
1378
1379 with self.assertRaises(InvalidArguments) as cm:
1380 _(None, mock.Mock(), ['string', 1.0, False], None)
1381 self.assertEqual(str(cm.exception), 'foo argument 2 was of type "float" but should have been "int"')
1382
1383 def test_typed_pos_args_types_wrong_number(self) -> None:
1384 @typed_pos_args('foo', str, int, bool)
1385 def _(obj, node, args: T.Tuple[str, int, bool], kwargs) -> None:
1386 self.assertTrue(False) # should not be reachable
1387
1388 with self.assertRaises(InvalidArguments) as cm:
1389 _(None, mock.Mock(), ['string', 1], None)
1390 self.assertEqual(str(cm.exception), 'foo takes exactly 3 arguments, but got 2.')
1391
1392 with self.assertRaises(InvalidArguments) as cm:
1393 _(None, mock.Mock(), ['string', 1, True, True], None)
1394 self.assertEqual(str(cm.exception), 'foo takes exactly 3 arguments, but got 4.')
1395
1396 def test_typed_pos_args_varargs(self) -> None:
1397 @typed_pos_args('foo', str, varargs=str)
1398 def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None:
1399 self.assertIsInstance(args, tuple)
1400 self.assertIsInstance(args[0], str)
1401 self.assertIsInstance(args[1], list)
1402 self.assertIsInstance(args[1][0], str)
1403 self.assertIsInstance(args[1][1], str)
1404
1405 _(None, mock.Mock(), ['string', 'var', 'args'], None)
1406
1407 def test_typed_pos_args_varargs_not_given(self) -> None:
1408 @typed_pos_args('foo', str, varargs=str)
1409 def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None:
1410 self.assertIsInstance(args, tuple)
1411 self.assertIsInstance(args[0], str)
1412 self.assertIsInstance(args[1], list)
1413 self.assertEqual(args[1], [])
1414
1415 _(None, mock.Mock(), ['string'], None)
1416
1417 def test_typed_pos_args_varargs_invalid(self) -> None:
1418 @typed_pos_args('foo', str, varargs=str)
1419 def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None:
1420 self.assertTrue(False) # should not be reachable
1421
1422 with self.assertRaises(InvalidArguments) as cm:
1423 _(None, mock.Mock(), ['string', 'var', 'args', 0], None)
1424 self.assertEqual(str(cm.exception), 'foo argument 4 was of type "int" but should have been "str"')
1425
1426 def test_typed_pos_args_varargs_invalid_multiple_types(self) -> None:
1427 @typed_pos_args('foo', str, varargs=(str, list))
1428 def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None:
1429 self.assertTrue(False) # should not be reachable
1430
1431 with self.assertRaises(InvalidArguments) as cm:
1432 _(None, mock.Mock(), ['string', 'var', 'args', 0], None)
1433 self.assertEqual(str(cm.exception), 'foo argument 4 was of type "int" but should have been one of: "str", "list"')
1434
1435 def test_typed_pos_args_max_varargs(self) -> None:
1436 @typed_pos_args('foo', str, varargs=str, max_varargs=5)
1437 def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None:
1438 self.assertIsInstance(args, tuple)
1439 self.assertIsInstance(args[0], str)
1440 self.assertIsInstance(args[1], list)
1441 self.assertIsInstance(args[1][0], str)
1442 self.assertIsInstance(args[1][1], str)
1443
1444 _(None, mock.Mock(), ['string', 'var', 'args'], None)
1445
1446 def test_typed_pos_args_max_varargs_exceeded(self) -> None:
1447 @typed_pos_args('foo', str, varargs=str, max_varargs=1)
1448 def _(obj, node, args: T.Tuple[str, T.Tuple[str, ...]], kwargs) -> None:
1449 self.assertTrue(False) # should not be reachable
1450
1451 with self.assertRaises(InvalidArguments) as cm:
1452 _(None, mock.Mock(), ['string', 'var', 'args'], None)
1453 self.assertEqual(str(cm.exception), 'foo takes between 1 and 2 arguments, but got 3.')
1454
1455 def test_typed_pos_args_min_varargs(self) -> None:
1456 @typed_pos_args('foo', varargs=str, max_varargs=2, min_varargs=1)
1457 def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None:
1458 self.assertIsInstance(args, tuple)
1459 self.assertIsInstance(args[0], list)
1460 self.assertIsInstance(args[0][0], str)
1461 self.assertIsInstance(args[0][1], str)
1462
1463 _(None, mock.Mock(), ['string', 'var'], None)
1464
1465 def test_typed_pos_args_min_varargs_not_met(self) -> None:
1466 @typed_pos_args('foo', str, varargs=str, min_varargs=1)
1467 def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None:
1468 self.assertTrue(False) # should not be reachable
1469
1470 with self.assertRaises(InvalidArguments) as cm:
1471 _(None, mock.Mock(), ['string'], None)
1472 self.assertEqual(str(cm.exception), 'foo takes at least 2 arguments, but got 1.')
1473
1474 def test_typed_pos_args_min_and_max_varargs_exceeded(self) -> None:
1475 @typed_pos_args('foo', str, varargs=str, min_varargs=1, max_varargs=2)
1476 def _(obj, node, args: T.Tuple[str, T.Tuple[str, ...]], kwargs) -> None:
1477 self.assertTrue(False) # should not be reachable
1478
1479 with self.assertRaises(InvalidArguments) as cm:
1480 _(None, mock.Mock(), ['string', 'var', 'args', 'bar'], None)
1481 self.assertEqual(str(cm.exception), 'foo takes between 2 and 3 arguments, but got 4.')
1482
1483 def test_typed_pos_args_min_and_max_varargs_not_met(self) -> None:
1484 @typed_pos_args('foo', str, varargs=str, min_varargs=1, max_varargs=2)
1485 def _(obj, node, args: T.Tuple[str, T.Tuple[str, ...]], kwargs) -> None:
1486 self.assertTrue(False) # should not be reachable
1487
1488 with self.assertRaises(InvalidArguments) as cm:
1489 _(None, mock.Mock(), ['string'], None)
1490 self.assertEqual(str(cm.exception), 'foo takes between 2 and 3 arguments, but got 1.')
1491
1492 def test_typed_pos_args_variadic_and_optional(self) -> None:
1493 @typed_pos_args('foo', str, optargs=[str], varargs=str, min_varargs=0)
1494 def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None:
1495 self.assertTrue(False) # should not be reachable
1496
1497 with self.assertRaises(AssertionError) as cm:
1498 _(None, mock.Mock(), ['string'], None)
1499 self.assertEqual(
1500 str(cm.exception),
1501 'varargs and optargs not supported together as this would be ambiguous')
1502
1503 def test_typed_pos_args_min_optargs_not_met(self) -> None:
1504 @typed_pos_args('foo', str, str, optargs=[str])
1505 def _(obj, node, args: T.Tuple[str, T.Optional[str]], kwargs) -> None:
1506 self.assertTrue(False) # should not be reachable
1507
1508 with self.assertRaises(InvalidArguments) as cm:
1509 _(None, mock.Mock(), ['string'], None)
1510 self.assertEqual(str(cm.exception), 'foo takes at least 2 arguments, but got 1.')
1511
1512 def test_typed_pos_args_min_optargs_max_exceeded(self) -> None:
1513 @typed_pos_args('foo', str, optargs=[str])
1514 def _(obj, node, args: T.Tuple[str, T.Optional[str]], kwargs) -> None:
1515 self.assertTrue(False) # should not be reachable
1516
1517 with self.assertRaises(InvalidArguments) as cm:
1518 _(None, mock.Mock(), ['string', '1', '2'], None)
1519 self.assertEqual(str(cm.exception), 'foo takes at most 2 arguments, but got 3.')
1520
1521 def test_typed_pos_args_optargs_not_given(self) -> None:
1522 @typed_pos_args('foo', str, optargs=[str])
1523 def _(obj, node, args: T.Tuple[str, T.Optional[str]], kwargs) -> None:
1524 self.assertEqual(len(args), 2)
1525 self.assertIsInstance(args[0], str)
1526 self.assertEqual(args[0], 'string')
1527 self.assertIsNone(args[1])
1528
1529 _(None, mock.Mock(), ['string'], None)
1530
1531 def test_typed_pos_args_optargs_some_given(self) -> None:
1532 @typed_pos_args('foo', str, optargs=[str, int])
1533 def _(obj, node, args: T.Tuple[str, T.Optional[str], T.Optional[int]], kwargs) -> None:
1534 self.assertEqual(len(args), 3)
1535 self.assertIsInstance(args[0], str)
1536 self.assertEqual(args[0], 'string')
1537 self.assertIsInstance(args[1], str)
1538 self.assertEqual(args[1], '1')
1539 self.assertIsNone(args[2])
1540
1541 _(None, mock.Mock(), ['string', '1'], None)
1542
1543 def test_typed_pos_args_optargs_all_given(self) -> None:
1544 @typed_pos_args('foo', str, optargs=[str])
1545 def _(obj, node, args: T.Tuple[str, T.Optional[str]], kwargs) -> None:
1546 self.assertEqual(len(args), 2)
1547 self.assertIsInstance(args[0], str)
1548 self.assertEqual(args[0], 'string')
1549 self.assertIsInstance(args[1], str)
1550
1551 _(None, mock.Mock(), ['string', '1'], None)
1552
1553 def test_typed_kwarg_basic(self) -> None:
1554 @typed_kwargs(
1555 'testfunc',
1556 KwargInfo('input', str, default='')
1557 )
1558 def _(obj, node, args: T.Tuple, kwargs: T.Dict[str, str]) -> None:
1559 self.assertIsInstance(kwargs['input'], str)
1560 self.assertEqual(kwargs['input'], 'foo')
1561
1562 _(None, mock.Mock(), [], {'input': 'foo'})
1563
1564 def test_typed_kwarg_missing_required(self) -> None:
1565 @typed_kwargs(
1566 'testfunc',
1567 KwargInfo('input', str, required=True),
1568 )
1569 def _(obj, node, args: T.Tuple, kwargs: T.Dict[str, str]) -> None:
1570 self.assertTrue(False) # should be unreachable
1571
1572 with self.assertRaises(InvalidArguments) as cm:
1573 _(None, mock.Mock(), [], {})
1574 self.assertEqual(str(cm.exception), 'testfunc is missing required keyword argument "input"')
1575
1576 def test_typed_kwarg_missing_optional(self) -> None:
1577 @typed_kwargs(
1578 'testfunc',
1579 KwargInfo('input', (str, type(None))),
1580 )
1581 def _(obj, node, args: T.Tuple, kwargs: T.Dict[str, T.Optional[str]]) -> None:
1582 self.assertIsNone(kwargs['input'])
1583
1584 _(None, mock.Mock(), [], {})
1585
1586 def test_typed_kwarg_default(self) -> None:
1587 @typed_kwargs(
1588 'testfunc',
1589 KwargInfo('input', str, default='default'),
1590 )
1591 def _(obj, node, args: T.Tuple, kwargs: T.Dict[str, str]) -> None:
1592 self.assertEqual(kwargs['input'], 'default')
1593
1594 _(None, mock.Mock(), [], {})
1595
1596 def test_typed_kwarg_container_valid(self) -> None:
1597 @typed_kwargs(
1598 'testfunc',
1599 KwargInfo('input', ContainerTypeInfo(list, str), default=[], required=True),
1600 )
1601 def _(obj, node, args: T.Tuple, kwargs: T.Dict[str, T.List[str]]) -> None:
1602 self.assertEqual(kwargs['input'], ['str'])
1603
1604 _(None, mock.Mock(), [], {'input': ['str']})
1605
1606 def test_typed_kwarg_container_invalid(self) -> None:
1607 @typed_kwargs(
1608 'testfunc',
1609 KwargInfo('input', ContainerTypeInfo(list, str), required=True),
1610 )
1611 def _(obj, node, args: T.Tuple, kwargs: T.Dict[str, T.List[str]]) -> None:
1612 self.assertTrue(False) # should be unreachable
1613
1614 with self.assertRaises(InvalidArguments) as cm:
1615 _(None, mock.Mock(), [], {'input': {}})
1616 self.assertEqual(str(cm.exception), "testfunc keyword argument 'input' was of type dict[] but should have been array[str]")
1617
1618 def test_typed_kwarg_contained_invalid(self) -> None:
1619 @typed_kwargs(
1620 'testfunc',
1621 KwargInfo('input', ContainerTypeInfo(dict, str), required=True),
1622 )
1623 def _(obj, node, args: T.Tuple, kwargs: T.Dict[str, T.Dict[str, str]]) -> None:
1624 self.assertTrue(False) # should be unreachable
1625
1626 with self.assertRaises(InvalidArguments) as cm:
1627 _(None, mock.Mock(), [], {'input': {'key': 1, 'bar': 2}})
1628 self.assertEqual(str(cm.exception), "testfunc keyword argument 'input' was of type dict[int] but should have been dict[str]")
1629
1630 def test_typed_kwarg_container_listify(self) -> None:
1631 @typed_kwargs(
1632 'testfunc',
1633 KwargInfo('input', ContainerTypeInfo(list, str), default=[], listify=True),
1634 )
1635 def _(obj, node, args: T.Tuple, kwargs: T.Dict[str, T.List[str]]) -> None:
1636 self.assertEqual(kwargs['input'], ['str'])
1637
1638 _(None, mock.Mock(), [], {'input': 'str'})
1639
1640 def test_typed_kwarg_container_default_copy(self) -> None:
1641 default: T.List[str] = []
1642 @typed_kwargs(
1643 'testfunc',
1644 KwargInfo('input', ContainerTypeInfo(list, str), listify=True, default=default),
1645 )
1646 def _(obj, node, args: T.Tuple, kwargs: T.Dict[str, T.List[str]]) -> None:
1647 self.assertIsNot(kwargs['input'], default)
1648
1649 _(None, mock.Mock(), [], {})
1650
1651 def test_typed_kwarg_container_pairs(self) -> None:
1652 @typed_kwargs(
1653 'testfunc',
1654 KwargInfo('input', ContainerTypeInfo(list, str, pairs=True), listify=True),
1655 )
1656 def _(obj, node, args: T.Tuple, kwargs: T.Dict[str, T.List[str]]) -> None:
1657 self.assertEqual(kwargs['input'], ['a', 'b'])
1658
1659 _(None, mock.Mock(), [], {'input': ['a', 'b']})
1660
1661 with self.assertRaises(MesonException) as cm:
1662 _(None, mock.Mock(), [], {'input': ['a']})
1663 self.assertEqual(str(cm.exception), "testfunc keyword argument 'input' was of type array[str] but should have been array[str] that has even size")
1664
1665 def test_typed_kwarg_since(self) -> None:
1666 @typed_kwargs(
1667 'testfunc',
1668 KwargInfo('input', str, since='1.0', since_message='It\'s awesome, use it',
1669 deprecated='2.0', deprecated_message='It\'s terrible, don\'t use it')
1670 )
1671 def _(obj, node, args: T.Tuple, kwargs: T.Dict[str, str]) -> None:
1672 self.assertIsInstance(kwargs['input'], str)
1673 self.assertEqual(kwargs['input'], 'foo')
1674
1675 with self.subTest('use before available'), \
1676 mock.patch('sys.stdout', io.StringIO()) as out, \
1677 mock.patch('mesonbuild.mesonlib.project_meson_versions', {'': version_check_to_range(['>=0.1'])}):
1678 # With Meson 0.1 it should trigger the "introduced" warning but not the "deprecated" warning
1679 _(None, mock.Mock(subproject=''), [], {'input': 'foo'})
1680 self.assertRegex(out.getvalue(), r'WARNING:.*introduced.*input arg in testfunc. It\'s awesome, use it')
1681 self.assertNotRegex(out.getvalue(), r'WARNING:.*deprecated.*input arg in testfunc. It\'s terrible, don\'t use it')
1682
1683 with self.subTest('no warnings should be triggered'), \
1684 mock.patch('sys.stdout', io.StringIO()) as out, \
1685 mock.patch('mesonbuild.mesonlib.project_meson_versions', {'': version_check_to_range(['>=1.5'])}):
1686 # With Meson 1.5 it shouldn't trigger any warning
1687 _(None, mock.Mock(subproject=''), [], {'input': 'foo'})
1688 self.assertNotRegex(out.getvalue(), r'WARNING:.*')
1689
1690 with self.subTest('use after deprecated'), \
1691 mock.patch('sys.stdout', io.StringIO()) as out, \
1692 mock.patch('mesonbuild.mesonlib.project_meson_versions', {'': version_check_to_range(['>=2.0'])}):
1693 # With Meson 2.0 it should trigger the "deprecated" warning but not the "introduced" warning
1694 _(None, mock.Mock(subproject=''), [], {'input': 'foo'})
1695 self.assertRegex(out.getvalue(), r'WARNING:.*deprecated.*input arg in testfunc. It\'s terrible, don\'t use it')
1696 self.assertNotRegex(out.getvalue(), r'WARNING:.*introduced.*input arg in testfunc. It\'s awesome, use it')
1697
1698 def test_typed_kwarg_validator(self) -> None:
1699 @typed_kwargs(
1700 'testfunc',
1701 KwargInfo('input', str, default='', validator=lambda x: 'invalid!' if x != 'foo' else None)
1702 )
1703 def _(obj, node, args: T.Tuple, kwargs: T.Dict[str, str]) -> None:
1704 pass
1705
1706 # Should be valid
1707 _(None, mock.Mock(), tuple(), dict(input='foo'))
1708
1709 with self.assertRaises(MesonException) as cm:
1710 _(None, mock.Mock(), tuple(), dict(input='bar'))
1711 self.assertEqual(str(cm.exception), "testfunc keyword argument \"input\" invalid!")
1712
1713 def test_typed_kwarg_convertor(self) -> None:
1714 @typed_kwargs(
1715 'testfunc',
1716 KwargInfo('native', bool, default=False, convertor=lambda n: MachineChoice.BUILD if n else MachineChoice.HOST)
1717 )
1718 def _(obj, node, args: T.Tuple, kwargs: T.Dict[str, MachineChoice]) -> None:
1719 assert isinstance(kwargs['native'], MachineChoice)
1720
1721 _(None, mock.Mock(), tuple(), dict(native=True))
1722
1723 @mock.patch('mesonbuild.mesonlib.project_meson_versions', {'': version_check_to_range(['>=1.0'])})
1724 def test_typed_kwarg_since_values(self) -> None:
1725 @typed_kwargs(
1726 'testfunc',
1727 KwargInfo('input', ContainerTypeInfo(list, str), listify=True, default=[], deprecated_values={'foo': '0.9'}, since_values={'bar': '1.1'}),
1728 KwargInfo('output', ContainerTypeInfo(dict, str), default={}, deprecated_values={'foo': '0.9', 'foo2': ('0.9', 'don\'t use it')}, since_values={'bar': '1.1', 'bar2': ('1.1', 'use this')}),
1729 KwargInfo('install_dir', (bool, str, NoneType), deprecated_values={False: '0.9'}),
1730 KwargInfo(
1731 'mode',
1732 (str, type(None)),
1733 validator=in_set_validator({'clean', 'build', 'rebuild', 'deprecated', 'since'}),
1734 deprecated_values={'deprecated': '1.0'},
1735 since_values={'since': '1.1'}),
1736 KwargInfo('dict', (ContainerTypeInfo(list, str), ContainerTypeInfo(dict, str)), default={},
1737 since_values={list: '1.9'}),
1738 KwargInfo('new_dict', (ContainerTypeInfo(list, str), ContainerTypeInfo(dict, str)), default={},
1739 since_values={dict: '1.1'}),
1740 KwargInfo('foo', (str, int, ContainerTypeInfo(list, str), ContainerTypeInfo(dict, str), ContainerTypeInfo(list, int)), default={},
1741 since_values={str: '1.1', ContainerTypeInfo(list, str): '1.2', ContainerTypeInfo(dict, str): '1.3'},
1742 deprecated_values={int: '0.8', ContainerTypeInfo(list, int): '0.9'}),
1743 KwargInfo('tuple', (ContainerTypeInfo(list, (str, int))), default=[], listify=True,
1744 since_values={ContainerTypeInfo(list, str): '1.1', ContainerTypeInfo(list, int): '1.2'}),
1745 )
1746 def _(obj, node, args: T.Tuple, kwargs: T.Dict[str, str]) -> None:
1747 pass
1748
1749 with self.subTest('deprecated array string value'), mock.patch('sys.stdout', io.StringIO()) as out:
1750 _(None, mock.Mock(subproject=''), [], {'input': ['foo']})
1751 self.assertRegex(out.getvalue(), r"""WARNING:.Project targets '>= 1.0'.*deprecated since '0.9': "testfunc" keyword argument "input" value "foo".*""")
1752
1753 with self.subTest('new array string value'), mock.patch('sys.stdout', io.StringIO()) as out:
1754 _(None, mock.Mock(subproject=''), [], {'input': ['bar']})
1755 self.assertRegex(out.getvalue(), r"""WARNING:.Project targets '>= 1.0'.*introduced in '1.1': "testfunc" keyword argument "input" value "bar".*""")
1756
1757 with self.subTest('deprecated dict string value'), mock.patch('sys.stdout', io.StringIO()) as out:
1758 _(None, mock.Mock(subproject=''), [], {'output': {'foo': 'a'}})
1759 self.assertRegex(out.getvalue(), r"""WARNING:.Project targets '>= 1.0'.*deprecated since '0.9': "testfunc" keyword argument "output" value "foo".*""")
1760
1761 with self.subTest('deprecated dict string value with msg'), mock.patch('sys.stdout', io.StringIO()) as out:
1762 _(None, mock.Mock(subproject=''), [], {'output': {'foo2': 'a'}})
1763 self.assertRegex(out.getvalue(), r"""WARNING:.Project targets '>= 1.0'.*deprecated since '0.9': "testfunc" keyword argument "output" value "foo2" in dict keys. don't use it.*""")
1764
1765 with self.subTest('new dict string value'), mock.patch('sys.stdout', io.StringIO()) as out:
1766 _(None, mock.Mock(subproject=''), [], {'output': {'bar': 'b'}})
1767 self.assertRegex(out.getvalue(), r"""WARNING:.Project targets '>= 1.0'.*introduced in '1.1': "testfunc" keyword argument "output" value "bar".*""")
1768
1769 with self.subTest('new dict string value with msg'), mock.patch('sys.stdout', io.StringIO()) as out:
1770 _(None, mock.Mock(subproject=''), [], {'output': {'bar2': 'a'}})
1771 self.assertRegex(out.getvalue(), r"""WARNING:.Project targets '>= 1.0'.*introduced in '1.1': "testfunc" keyword argument "output" value "bar2" in dict keys. use this.*""")
1772
1773 with self.subTest('new string type'), mock.patch('sys.stdout', io.StringIO()) as out:
1774 _(None, mock.Mock(subproject=''), [], {'foo': 'foo'})
1775 self.assertRegex(out.getvalue(), r"""WARNING: Project targets '>= 1.0'.*introduced in '1.1': "testfunc" keyword argument "foo" of type str.*""")
1776
1777 with self.subTest('new array of string type'), mock.patch('sys.stdout', io.StringIO()) as out:
1778 _(None, mock.Mock(subproject=''), [], {'foo': ['foo']})
1779 self.assertRegex(out.getvalue(), r"""WARNING: Project targets '>= 1.0'.*introduced in '1.2': "testfunc" keyword argument "foo" of type array\[str\].*""")
1780
1781 with self.subTest('new dict of string type'), mock.patch('sys.stdout', io.StringIO()) as out:
1782 _(None, mock.Mock(subproject=''), [], {'foo': {'plop': 'foo'}})
1783 self.assertRegex(out.getvalue(), r"""WARNING: Project targets '>= 1.0'.*introduced in '1.3': "testfunc" keyword argument "foo" of type dict\[str\].*""")
1784
1785 with self.subTest('deprecated int value'), mock.patch('sys.stdout', io.StringIO()) as out:
1786 _(None, mock.Mock(subproject=''), [], {'foo': 1})
1787 self.assertRegex(out.getvalue(), r"""WARNING:.Project targets '>= 1.0'.*deprecated since '0.8': "testfunc" keyword argument "foo" of type int.*""")
1788
1789 with self.subTest('deprecated array int value'), mock.patch('sys.stdout', io.StringIO()) as out:
1790 _(None, mock.Mock(subproject=''), [], {'foo': [1]})
1791 self.assertRegex(out.getvalue(), r"""WARNING:.Project targets '>= 1.0'.*deprecated since '0.9': "testfunc" keyword argument "foo" of type array\[int\].*""")
1792
1793 with self.subTest('new list[str] value'), mock.patch('sys.stdout', io.StringIO()) as out:
1794 _(None, mock.Mock(subproject=''), [], {'tuple': ['foo', 42]})
1795 self.assertRegex(out.getvalue(), r"""WARNING: Project targets '>= 1.0'.*introduced in '1.1': "testfunc" keyword argument "tuple" of type array\[str\].*""")
1796 self.assertRegex(out.getvalue(), r"""WARNING: Project targets '>= 1.0'.*introduced in '1.2': "testfunc" keyword argument "tuple" of type array\[int\].*""")
1797
1798 with self.subTest('deprecated array string value'), mock.patch('sys.stdout', io.StringIO()) as out:
1799 _(None, mock.Mock(subproject=''), [], {'input': 'foo'})
1800 self.assertRegex(out.getvalue(), r"""WARNING:.Project targets '>= 1.0'.*deprecated since '0.9': "testfunc" keyword argument "input" value "foo".*""")
1801
1802 with self.subTest('new array string value'), mock.patch('sys.stdout', io.StringIO()) as out:
1803 _(None, mock.Mock(subproject=''), [], {'input': 'bar'})
1804 self.assertRegex(out.getvalue(), r"""WARNING:.Project targets '>= 1.0'.*introduced in '1.1': "testfunc" keyword argument "input" value "bar".*""")
1805
1806 with self.subTest('non string union'), mock.patch('sys.stdout', io.StringIO()) as out:
1807 _(None, mock.Mock(subproject=''), [], {'install_dir': False})
1808 self.assertRegex(out.getvalue(), r"""WARNING:.Project targets '>= 1.0'.*deprecated since '0.9': "testfunc" keyword argument "install_dir" value "False".*""")
1809
1810 with self.subTest('deprecated string union'), mock.patch('sys.stdout', io.StringIO()) as out:
1811 _(None, mock.Mock(subproject=''), [], {'mode': 'deprecated'})
1812 self.assertRegex(out.getvalue(), r"""WARNING:.Project targets '>= 1.0'.*deprecated since '1.0': "testfunc" keyword argument "mode" value "deprecated".*""")
1813
1814 with self.subTest('new string union'), mock.patch('sys.stdout', io.StringIO()) as out:
1815 _(None, mock.Mock(subproject=''), [], {'mode': 'since'})
1816 self.assertRegex(out.getvalue(), r"""WARNING:.Project targets '>= 1.0'.*introduced in '1.1': "testfunc" keyword argument "mode" value "since".*""")
1817
1818 with self.subTest('new container'), mock.patch('sys.stdout', io.StringIO()) as out:
1819 _(None, mock.Mock(subproject=''), [], {'dict': ['a=b']})
1820 self.assertRegex(out.getvalue(), r"""WARNING:.Project targets '>= 1.0'.*introduced in '1.9': "testfunc" keyword argument "dict" of type list.*""")
1821
1822 with self.subTest('new container set to default'), mock.patch('sys.stdout', io.StringIO()) as out:
1823 _(None, mock.Mock(subproject=''), [], {'new_dict': {}})
1824 self.assertRegex(out.getvalue(), r"""WARNING:.Project targets '>= 1.0'.*introduced in '1.1': "testfunc" keyword argument "new_dict" of type dict.*""")
1825
1826 with self.subTest('new container default'), mock.patch('sys.stdout', io.StringIO()) as out:
1827 _(None, mock.Mock(subproject=''), [], {})
1828 self.assertNotRegex(out.getvalue(), r"""WARNING:.Project targets '>= 1.0'.*introduced in '1.1': "testfunc" keyword argument "new_dict" of type dict.*""")
1829
1830 def test_typed_kwarg_evolve(self) -> None:
1831 k = KwargInfo('foo', str, required=True, default='foo')
1832 v = k.evolve(default='bar')
1833 self.assertEqual(k.name, 'foo')
1834 self.assertEqual(k.name, v.name)
1835 self.assertEqual(k.types, str)
1836 self.assertEqual(k.types, v.types)
1837 self.assertEqual(k.required, True)
1838 self.assertEqual(k.required, v.required)
1839 self.assertEqual(k.default, 'foo')
1840 self.assertEqual(v.default, 'bar')
1841
1842 def test_typed_kwarg_default_type(self) -> None:
1843 @typed_kwargs(
1844 'testfunc',
1845 KwargInfo('no_default', (str, ContainerTypeInfo(list, str), NoneType)),
1846 KwargInfo('str_default', (str, ContainerTypeInfo(list, str)), default=''),
1847 KwargInfo('list_default', (str, ContainerTypeInfo(list, str)), default=['']),
1848 )
1849 def _(obj, node, args: T.Tuple, kwargs: T.Dict[str, str]) -> None:
1850 self.assertEqual(kwargs['no_default'], None)
1851 self.assertEqual(kwargs['str_default'], '')
1852 self.assertEqual(kwargs['list_default'], [''])
1853 _(None, mock.Mock(), [], {})
1854
1855 def test_typed_kwarg_invalid_default_type(self) -> None:
1856 @typed_kwargs(
1857 'testfunc',
1858 KwargInfo('invalid_default', (str, ContainerTypeInfo(list, str), NoneType), default=42),
1859 )
1860 def _(obj, node, args: T.Tuple, kwargs: T.Dict[str, str]) -> None:
1861 pass
1862 self.assertRaises(AssertionError, _, None, mock.Mock(), [], {})
1863
1864 def test_typed_kwarg_container_in_tuple(self) -> None:
1865 @typed_kwargs(
1866 'testfunc',
1867 KwargInfo('input', (str, ContainerTypeInfo(list, str))),
1868 )
1869 def _(obj, node, args: T.Tuple, kwargs: T.Dict[str, str]) -> None:
1870 self.assertEqual(kwargs['input'], args[0])
1871 _(None, mock.Mock(), [''], {'input': ''})
1872 _(None, mock.Mock(), [['']], {'input': ['']})
1873 self.assertRaises(InvalidArguments, _, None, mock.Mock(), [], {'input': 42})
1874
1875 def test_detect_cpu_family(self) -> None:
1876 """Test the various cpu families that we detect and normalize.
1877
1878 This is particularly useful as both documentation, and to keep testing
1879 platforms that are less common.
1880 """
1881
1882 @contextlib.contextmanager
1883 def mock_trial(value: str) -> T.Iterable[None]:
1884 """Mock all of the ways we could get the trial at once."""
1885 mocked = mock.Mock(return_value=value)
1886
1887 with mock.patch('mesonbuild.envconfig.detect_windows_arch', mocked), \
1888 mock.patch('mesonbuild.envconfig.platform.processor', mocked), \
1889 mock.patch('mesonbuild.envconfig.platform.machine', mocked):
1890 yield
1891
1892 cases = [
1893 ('x86', 'x86'),
1894 ('i386', 'x86'),
1895 ('bepc', 'x86'), # Haiku
1896 ('earm', 'arm'), # NetBSD
1897 ('arm', 'arm'),
1898 ('ppc64', 'ppc64'),
1899 ('powerpc64', 'ppc64'),
1900 ('powerpc', 'ppc'),
1901 ('ppc', 'ppc'),
1902 ('macppc', 'ppc'),
1903 ('power macintosh', 'ppc'),
1904 ('mips64el', 'mips'),
1905 ('mips64', 'mips'),
1906 ('mips', 'mips'),
1907 ('mipsel', 'mips'),
1908 ('ip30', 'mips'),
1909 ('ip35', 'mips'),
1910 ('parisc64', 'parisc'),
1911 ('sun4u', 'sparc64'),
1912 ('sun4v', 'sparc64'),
1913 ('amd64', 'x86_64'),
1914 ('x64', 'x86_64'),
1915 ('i86pc', 'x86_64'), # Solaris
1916 ('aarch64', 'aarch64'),
1917 ('aarch64_be', 'aarch64'),
1918 ]
1919
1920 cc = ClangCCompiler([], [], 'fake', MachineChoice.HOST, get_fake_env())
1921
1922 with mock.patch('mesonbuild.envconfig.any_compiler_has_define', mock.Mock(return_value=False)):
1923 for test, expected in cases:
1924 with self.subTest(test, has_define=False), mock_trial(test):
1925 actual = mesonbuild.envconfig.detect_cpu_family({'c': cc})
1926 self.assertEqual(actual, expected)
1927
1928 with mock.patch('mesonbuild.envconfig.any_compiler_has_define', mock.Mock(return_value=True)):
1929 for test, expected in [('x86_64', 'x86'), ('aarch64', 'arm'), ('ppc', 'ppc64'), ('mips64', 'mips64')]:
1930 with self.subTest(test, has_define=True), mock_trial(test):
1931 actual = mesonbuild.envconfig.detect_cpu_family({'c': cc})
1932 self.assertEqual(actual, expected)
1933
1934 # machine_info_can_run calls detect_cpu_family with no compilers at all
1935 with mock.patch(
1936 'mesonbuild.envconfig.any_compiler_has_define',
1937 mock.Mock(side_effect=AssertionError('Should not be called')),
1938 ):
1939 for test, expected in [('mips64', 'mips64')]:
1940 with self.subTest(test, has_compiler=False), mock_trial(test):
1941 actual = mesonbuild.envconfig.detect_cpu_family({})
1942 self.assertEqual(actual, expected)
1943
1944 def test_detect_cpu(self) -> None:
1945
1946 @contextlib.contextmanager
1947 def mock_trial(value: str) -> T.Iterable[None]:
1948 """Mock all of the ways we could get the trial at once."""
1949 mocked = mock.Mock(return_value=value)
1950
1951 with mock.patch('mesonbuild.envconfig.detect_windows_arch', mocked), \
1952 mock.patch('mesonbuild.envconfig.platform.processor', mocked), \
1953 mock.patch('mesonbuild.envconfig.platform.machine', mocked):
1954 yield
1955
1956 cases = [
1957 ('amd64', 'x86_64'),
1958 ('x64', 'x86_64'),
1959 ('i86pc', 'x86_64'),
1960 ('earm', 'arm'),
1961 ('mips64el', 'mips'),
1962 ('mips64', 'mips'),
1963 ('mips', 'mips'),
1964 ('mipsel', 'mips'),
1965 ('aarch64', 'aarch64'),
1966 ('aarch64_be', 'aarch64'),
1967 ]
1968
1969 cc = ClangCCompiler([], [], 'fake', MachineChoice.HOST, get_fake_env())
1970
1971 with mock.patch('mesonbuild.envconfig.any_compiler_has_define', mock.Mock(return_value=False)):
1972 for test, expected in cases:
1973 with self.subTest(test, has_define=False), mock_trial(test):
1974 actual = mesonbuild.envconfig.detect_cpu({'c': cc})
1975 self.assertEqual(actual, expected)
1976
1977 with mock.patch('mesonbuild.envconfig.any_compiler_has_define', mock.Mock(return_value=True)):
1978 for test, expected in [('x86_64', 'i686'), ('aarch64', 'arm'), ('ppc', 'ppc64'), ('mips64', 'mips64')]:
1979 with self.subTest(test, has_define=True), mock_trial(test):
1980 actual = mesonbuild.envconfig.detect_cpu({'c': cc})
1981 self.assertEqual(actual, expected)
1982
1983 with mock.patch(
1984 'mesonbuild.envconfig.any_compiler_has_define',
1985 mock.Mock(side_effect=AssertionError('Should not be called')),
1986 ):
1987 for test, expected in [('mips64', 'mips64')]:
1988 with self.subTest(test, has_compiler=False), mock_trial(test):
1989 actual = mesonbuild.envconfig.detect_cpu({})
1990 self.assertEqual(actual, expected)
1991
1992 @mock.patch('mesonbuild.interpreter.Interpreter.load_root_meson_file', mock.Mock(return_value=None))
1993 @mock.patch('mesonbuild.interpreter.Interpreter.sanity_check_ast', mock.Mock(return_value=None))
1994 @mock.patch('mesonbuild.interpreter.Interpreter.parse_project', mock.Mock(return_value=None))
1995 def test_interpreter_unpicklable(self) -> None:
1996 build = mock.Mock()
1997 build.environment = mock.Mock()
1998 build.environment.get_source_dir = mock.Mock(return_value='')
1999 with mock.patch('mesonbuild.interpreter.Interpreter._redetect_machines', mock.Mock()), \
2000 self.assertRaises(mesonbuild.mesonlib.MesonBugException):
2001 i = mesonbuild.interpreter.Interpreter(build)
2002 pickle.dumps(i)
2003
2004 def test_major_versions_differ(self) -> None:
2005 # Return True when going to next major release, when going to dev cycle,
2006 # when going to rc cycle or when going out of rc cycle.
2007 self.assertTrue(coredata.major_versions_differ('0.59.0', '0.60.0'))
2008 self.assertTrue(coredata.major_versions_differ('0.59.0', '0.59.99'))
2009 self.assertTrue(coredata.major_versions_differ('0.59.0', '0.60.0.rc1'))
2010 self.assertTrue(coredata.major_versions_differ('0.59.99', '0.60.0.rc1'))
2011 self.assertTrue(coredata.major_versions_differ('0.60.0.rc1', '0.60.0'))
2012 # Return False when going to next point release or when staying in dev/rc cycle.
2013 self.assertFalse(coredata.major_versions_differ('0.60.0', '0.60.0'))
2014 self.assertFalse(coredata.major_versions_differ('0.60.0', '0.60.1'))
2015 self.assertFalse(coredata.major_versions_differ('0.59.99', '0.59.99'))
2016 self.assertFalse(coredata.major_versions_differ('0.60.0.rc1', '0.60.0.rc2'))
2017
2018 def test_option_key_from_string(self) -> None:
2019 cases = [
2020 ('c_args', OptionKey('c_args')),
2021 ('build.cpp_args', OptionKey('cpp_args', machine=MachineChoice.BUILD)),
2022 ('prefix', OptionKey('prefix')),
2023 ('made_up', OptionKey('made_up')),
2024
2025 # TODO: the from_String method should be splitting the prefix off of
2026 # these, as we have the type already, but it doesn't. For now have a
2027 # test so that we don't change the behavior un-intentionally
2028 ('b_lto', OptionKey('b_lto')),
2029 ('backend_startup_project', OptionKey('backend_startup_project')),
2030 ]
2031
2032 for raw, expected in cases:
2033 with self.subTest(raw):
2034 self.assertEqual(OptionKey.from_string(raw), expected)
2035
2036 def test_env2mfile_deb(self) -> None:
2037 MachineInfo = mesonbuild.scripts.env2mfile.MachineInfo
2038 to_machine_info = mesonbuild.scripts.env2mfile.dpkg_architecture_to_machine_info
2039
2040 # For testing purposes, behave as though all cross-programs
2041 # exist in /usr/bin
2042 def locate_path(program: str) -> T.List[str]:
2043 if os.path.isabs(program):
2044 return [program]
2045 return ['/usr/bin/' + program]
2046
2047 def expected_compilers(
2048 gnu_tuple: str,
2049 gcc_suffix: str = '',
2050 ) -> T.Dict[str, T.List[str]]:
2051 return {
2052 'c': [f'/usr/bin/{gnu_tuple}-gcc{gcc_suffix}'],
2053 'cpp': [f'/usr/bin/{gnu_tuple}-g++{gcc_suffix}'],
2054 'objc': [f'/usr/bin/{gnu_tuple}-gobjc{gcc_suffix}'],
2055 'objcpp': [f'/usr/bin/{gnu_tuple}-gobjc++{gcc_suffix}'],
2056 'vala': [f'/usr/bin/{gnu_tuple}-valac'],
2057 }
2058
2059 def expected_binaries(gnu_tuple: str) -> T.Dict[str, T.List[str]]:
2060 return {
2061 'ar': [f'/usr/bin/{gnu_tuple}-ar'],
2062 'strip': [f'/usr/bin/{gnu_tuple}-strip'],
2063 'objcopy': [f'/usr/bin/{gnu_tuple}-objcopy'],
2064 'ld': [f'/usr/bin/{gnu_tuple}-ld'],
2065 'cmake': ['/usr/bin/cmake'],
2066 'pkg-config': [f'/usr/bin/{gnu_tuple}-pkg-config'],
2067 'cups-config': ['/usr/bin/cups-config'],
2068 'exe_wrapper': [f'/usr/bin/{gnu_tuple}-cross-exe-wrapper'],
2069 'g-ir-annotation-tool': [f'/usr/bin/{gnu_tuple}-g-ir-annotation-tool'],
2070 'g-ir-compiler': [f'/usr/bin/{gnu_tuple}-g-ir-compiler'],
2071 'g-ir-doc-tool': [f'/usr/bin/{gnu_tuple}-g-ir-doc-tool'],
2072 'g-ir-generate': [f'/usr/bin/{gnu_tuple}-g-ir-generate'],
2073 'g-ir-inspect': [f'/usr/bin/{gnu_tuple}-g-ir-inspect'],
2074 'g-ir-scanner': [f'/usr/bin/{gnu_tuple}-g-ir-scanner'],
2075 'vapigen': [f'/usr/bin/{gnu_tuple}-vapigen'],
2076 }
2077
2078 for title, dpkg_arch, gccsuffix, env, expected in [
2079 (
2080 # s390x is an example of the common case where the
2081 # Meson CPU name, the GNU CPU name, the dpkg architecture
2082 # name and uname -m all agree.
2083 # (alpha, m68k, ppc64, riscv64, sh4, sparc64 are similar)
2084 's390x-linux-gnu',
2085 # Output of `dpkg-architecture -a...`, filtered to
2086 # only the DEB_HOST_ parts because that's all we use
2087 textwrap.dedent(
2088 '''
2089 DEB_HOST_ARCH=s390x
2090 DEB_HOST_ARCH_ABI=base
2091 DEB_HOST_ARCH_BITS=64
2092 DEB_HOST_ARCH_CPU=s390x
2093 DEB_HOST_ARCH_ENDIAN=big
2094 DEB_HOST_ARCH_LIBC=gnu
2095 DEB_HOST_ARCH_OS=linux
2096 DEB_HOST_GNU_CPU=s390x
2097 DEB_HOST_GNU_SYSTEM=linux-gnu
2098 DEB_HOST_GNU_TYPE=s390x-linux-gnu
2099 DEB_HOST_MULTIARCH=s390x-linux-gnu
2100 '''
2101 ),
2102 '',
2103 {'PATH': '/usr/bin'},
2104 MachineInfo(
2105 compilers=expected_compilers('s390x-linux-gnu'),
2106 binaries=expected_binaries('s390x-linux-gnu'),
2107 properties={},
2108 compile_args={},
2109 link_args={},
2110 cmake={
2111 'CMAKE_C_COMPILER': ['/usr/bin/s390x-linux-gnu-gcc'],
2112 'CMAKE_CXX_COMPILER': ['/usr/bin/s390x-linux-gnu-g++'],
2113 'CMAKE_SYSTEM_NAME': 'Linux',
2114 'CMAKE_SYSTEM_PROCESSOR': 's390x',
2115 },
2116 system='linux',
2117 subsystem='linux',
2118 kernel='linux',
2119 cpu='s390x',
2120 cpu_family='s390x',
2121 endian='big',
2122 ),
2123 ),
2124 # Debian amd64 vs. GNU, Meson, etc. x86_64.
2125 # arm64/aarch64, hppa/parisc, i386/i686/x86, loong64/loongarch64,
2126 # powerpc/ppc are similar.
2127 (
2128 'x86_64-linux-gnu',
2129 textwrap.dedent(
2130 '''
2131 DEB_HOST_ARCH=amd64
2132 DEB_HOST_ARCH_ABI=base
2133 DEB_HOST_ARCH_BITS=64
2134 DEB_HOST_ARCH_CPU=amd64
2135 DEB_HOST_ARCH_ENDIAN=little
2136 DEB_HOST_ARCH_LIBC=gnu
2137 DEB_HOST_ARCH_OS=linux
2138 DEB_HOST_GNU_CPU=x86_64
2139 DEB_HOST_GNU_SYSTEM=linux-gnu
2140 DEB_HOST_GNU_TYPE=x86_64-linux-gnu
2141 DEB_HOST_MULTIARCH=x86_64-linux-gnu
2142 '''
2143 ),
2144 '',
2145 {'PATH': '/usr/bin'},
2146 MachineInfo(
2147 compilers=expected_compilers('x86_64-linux-gnu'),
2148 binaries=expected_binaries('x86_64-linux-gnu'),
2149 properties={},
2150 compile_args={},
2151 link_args={},
2152 cmake={
2153 'CMAKE_C_COMPILER': ['/usr/bin/x86_64-linux-gnu-gcc'],
2154 'CMAKE_CXX_COMPILER': ['/usr/bin/x86_64-linux-gnu-g++'],
2155 'CMAKE_SYSTEM_NAME': 'Linux',
2156 'CMAKE_SYSTEM_PROCESSOR': 'x86_64',
2157 },
2158 system='linux',
2159 subsystem='linux',
2160 kernel='linux',
2161 cpu='x86_64',
2162 cpu_family='x86_64',
2163 endian='little',
2164 ),
2165 ),
2166 (
2167 'arm-linux-gnueabihf with non-default gcc and environment',
2168 textwrap.dedent(
2169 '''
2170 DEB_HOST_ARCH=armhf
2171 DEB_HOST_ARCH_ABI=eabihf
2172 DEB_HOST_ARCH_BITS=32
2173 DEB_HOST_ARCH_CPU=arm
2174 DEB_HOST_ARCH_ENDIAN=little
2175 DEB_HOST_ARCH_LIBC=gnu
2176 DEB_HOST_ARCH_OS=linux
2177 DEB_HOST_GNU_CPU=arm
2178 DEB_HOST_GNU_SYSTEM=linux-gnueabihf
2179 DEB_HOST_GNU_TYPE=arm-linux-gnueabihf
2180 DEB_HOST_MULTIARCH=arm-linux-gnueabihf
2181 '''
2182 ),
2183 '-12',
2184 {
2185 'PATH': '/usr/bin',
2186 'CPPFLAGS': '-DNDEBUG',
2187 'CFLAGS': '-std=c99',
2188 'CXXFLAGS': '-std=c++11',
2189 'OBJCFLAGS': '-fobjc-exceptions',
2190 'OBJCXXFLAGS': '-fobjc-nilcheck',
2191 'LDFLAGS': '-Wl,-O1',
2192 },
2193 MachineInfo(
2194 compilers=expected_compilers('arm-linux-gnueabihf', '-12'),
2195 binaries=expected_binaries('arm-linux-gnueabihf'),
2196 properties={},
2197 compile_args={
2198 'c': ['-DNDEBUG', '-std=c99'],
2199 'cpp': ['-DNDEBUG', '-std=c++11'],
2200 'objc': ['-DNDEBUG', '-fobjc-exceptions'],
2201 'objcpp': ['-DNDEBUG', '-fobjc-nilcheck'],
2202 },
2203 link_args={
2204 'c': ['-std=c99', '-Wl,-O1'],
2205 'cpp': ['-std=c++11', '-Wl,-O1'],
2206 'objc': ['-fobjc-exceptions', '-Wl,-O1'],
2207 'objcpp': ['-fobjc-nilcheck', '-Wl,-O1'],
2208 },
2209 cmake={
2210 'CMAKE_C_COMPILER': ['/usr/bin/arm-linux-gnueabihf-gcc-12'],
2211 'CMAKE_CXX_COMPILER': ['/usr/bin/arm-linux-gnueabihf-g++-12'],
2212 'CMAKE_SYSTEM_NAME': 'Linux',
2213 'CMAKE_SYSTEM_PROCESSOR': 'armv7l',
2214 },
2215 system='linux',
2216 subsystem='linux',
2217 kernel='linux',
2218 # In a native build this would often be armv8l
2219 # (the version of the running CPU) but the architecture
2220 # baseline in Debian is officially ARMv7
2221 cpu='arm7hlf',
2222 cpu_family='arm',
2223 endian='little',
2224 ),
2225 ),
2226 (
2227 'special cases for i386 (i686, x86) and Hurd',
2228 textwrap.dedent(
2229 '''
2230 DEB_HOST_ARCH=hurd-i386
2231 DEB_HOST_ARCH_ABI=base
2232 DEB_HOST_ARCH_BITS=32
2233 DEB_HOST_ARCH_CPU=i386
2234 DEB_HOST_ARCH_ENDIAN=little
2235 DEB_HOST_ARCH_LIBC=gnu
2236 DEB_HOST_ARCH_OS=hurd
2237 DEB_HOST_GNU_CPU=i686
2238 DEB_HOST_GNU_SYSTEM=gnu
2239 DEB_HOST_GNU_TYPE=i686-gnu
2240 DEB_HOST_MULTIARCH=i386-gnu
2241 '''
2242 ),
2243 '',
2244 {'PATH': '/usr/bin'},
2245 MachineInfo(
2246 compilers=expected_compilers('i686-gnu'),
2247 binaries=expected_binaries('i686-gnu'),
2248 properties={},
2249 compile_args={},
2250 link_args={},
2251 cmake={
2252 'CMAKE_C_COMPILER': ['/usr/bin/i686-gnu-gcc'],
2253 'CMAKE_CXX_COMPILER': ['/usr/bin/i686-gnu-g++'],
2254 'CMAKE_SYSTEM_NAME': 'GNU',
2255 'CMAKE_SYSTEM_PROCESSOR': 'i686',
2256 },
2257 system='gnu',
2258 subsystem='gnu',
2259 kernel='gnu',
2260 cpu='i686',
2261 cpu_family='x86',
2262 endian='little',
2263 ),
2264 ),
2265 (
2266 'special cases for amd64 (x86_64) and kFreeBSD',
2267 textwrap.dedent(
2268 '''
2269 DEB_HOST_ARCH=kfreebsd-amd64
2270 DEB_HOST_ARCH_ABI=base
2271 DEB_HOST_ARCH_BITS=64
2272 DEB_HOST_ARCH_CPU=x86_amd64
2273 DEB_HOST_ARCH_ENDIAN=little
2274 DEB_HOST_ARCH_LIBC=gnu
2275 DEB_HOST_ARCH_OS=kfreebsd
2276 DEB_HOST_GNU_CPU=x86_64
2277 DEB_HOST_GNU_SYSTEM=kfreebsd-gnu
2278 DEB_HOST_GNU_TYPE=x86_64-kfreebsd-gnu
2279 DEB_HOST_MULTIARCH=x86_64-kfreebsd-gnu
2280 '''
2281 ),
2282 '',
2283 {'PATH': '/usr/bin'},
2284 MachineInfo(
2285 compilers=expected_compilers('x86_64-kfreebsd-gnu'),
2286 binaries=expected_binaries('x86_64-kfreebsd-gnu'),
2287 properties={},
2288 compile_args={},
2289 link_args={},
2290 cmake={
2291 'CMAKE_C_COMPILER': ['/usr/bin/x86_64-kfreebsd-gnu-gcc'],
2292 'CMAKE_CXX_COMPILER': ['/usr/bin/x86_64-kfreebsd-gnu-g++'],
2293 'CMAKE_SYSTEM_NAME': 'kFreeBSD',
2294 'CMAKE_SYSTEM_PROCESSOR': 'x86_64',
2295 },
2296 system='kfreebsd',
2297 subsystem='kfreebsd',
2298 kernel='freebsd',
2299 cpu='x86_64',
2300 cpu_family='x86_64',
2301 endian='little',
2302 ),
2303 ),
2304 (
2305 'special case for mips64el',
2306 textwrap.dedent(
2307 '''
2308 DEB_HOST_ARCH=mips64el
2309 DEB_HOST_ARCH_ABI=abi64
2310 DEB_HOST_ARCH_BITS=64
2311 DEB_HOST_ARCH_CPU=mips64el
2312 DEB_HOST_ARCH_ENDIAN=little
2313 DEB_HOST_ARCH_LIBC=gnu
2314 DEB_HOST_ARCH_OS=linux
2315 DEB_HOST_GNU_CPU=mips64el
2316 DEB_HOST_GNU_SYSTEM=linux-gnuabi64
2317 DEB_HOST_GNU_TYPE=mips64el-linux-gnuabi64
2318 DEB_HOST_MULTIARCH=mips64el-linux-gnuabi64
2319 '''
2320 ),
2321 '',
2322 {'PATH': '/usr/bin'},
2323 MachineInfo(
2324 compilers=expected_compilers('mips64el-linux-gnuabi64'),
2325 binaries=expected_binaries('mips64el-linux-gnuabi64'),
2326 properties={},
2327 compile_args={},
2328 link_args={},
2329 cmake={
2330 'CMAKE_C_COMPILER': ['/usr/bin/mips64el-linux-gnuabi64-gcc'],
2331 'CMAKE_CXX_COMPILER': ['/usr/bin/mips64el-linux-gnuabi64-g++'],
2332 'CMAKE_SYSTEM_NAME': 'Linux',
2333 'CMAKE_SYSTEM_PROCESSOR': 'mips64',
2334 },
2335 system='linux',
2336 subsystem='linux',
2337 kernel='linux',
2338 cpu='mips64',
2339 cpu_family='mips64',
2340 endian='little',
2341 ),
2342 ),
2343 (
2344 'special case for ppc64el',
2345 textwrap.dedent(
2346 '''
2347 DEB_HOST_ARCH=ppc64el
2348 DEB_HOST_ARCH_ABI=base
2349 DEB_HOST_ARCH_BITS=64
2350 DEB_HOST_ARCH_CPU=ppc64el
2351 DEB_HOST_ARCH_ENDIAN=little
2352 DEB_HOST_ARCH_LIBC=gnu
2353 DEB_HOST_ARCH_OS=linux
2354 DEB_HOST_GNU_CPU=powerpc64le
2355 DEB_HOST_GNU_SYSTEM=linux-gnu
2356 DEB_HOST_GNU_TYPE=powerpc64le-linux-gnu
2357 DEB_HOST_MULTIARCH=powerpc64le-linux-gnu
2358 '''
2359 ),
2360 '',
2361 {'PATH': '/usr/bin'},
2362 MachineInfo(
2363 compilers=expected_compilers('powerpc64le-linux-gnu'),
2364 binaries=expected_binaries('powerpc64le-linux-gnu'),
2365 properties={},
2366 compile_args={},
2367 link_args={},
2368 cmake={
2369 'CMAKE_C_COMPILER': ['/usr/bin/powerpc64le-linux-gnu-gcc'],
2370 'CMAKE_CXX_COMPILER': ['/usr/bin/powerpc64le-linux-gnu-g++'],
2371 'CMAKE_SYSTEM_NAME': 'Linux',
2372 'CMAKE_SYSTEM_PROCESSOR': 'ppc64le',
2373 },
2374 system='linux',
2375 subsystem='linux',
2376 kernel='linux',
2377 # TODO: Currently ppc64, but native builds have ppc64le
2378 # https://github.com/mesonbuild/meson/issues/13741
2379 cpu='TODO',
2380 cpu_family='ppc64',
2381 endian='little',
2382 ),
2383 ),
2384 ]:
2385 with self.subTest(title), \
2386 unittest.mock.patch.dict('os.environ', env, clear=True), \
2387 unittest.mock.patch('mesonbuild.scripts.env2mfile.locate_path') as mock_locate_path:
2388 mock_locate_path.side_effect = locate_path
2389 options = argparse.Namespace()
2390 options.gccsuffix = gccsuffix
2391 actual = to_machine_info(dpkg_arch, options)
2392
2393 if expected.system == 'TODO':
2394 print(f'TODO: {title}: system() -> {actual.system}')
2395 else:
2396 self.assertEqual(actual.system, expected.system)
2397
2398 if expected.subsystem == 'TODO':
2399 print(f'TODO: {title}: subsystem() -> {actual.subsystem}')
2400 else:
2401 self.assertEqual(actual.subsystem, expected.subsystem)
2402
2403 if expected.kernel == 'TODO':
2404 print(f'TODO: {title}: kernel() -> {actual.kernel}')
2405 else:
2406 self.assertEqual(actual.kernel, expected.kernel)
2407
2408 if expected.cpu == 'TODO':
2409 print(f'TODO: {title}: cpu() -> {actual.cpu}')
2410 else:
2411 self.assertEqual(actual.cpu, expected.cpu)
2412
2413 self.assertEqual(actual.cpu_family, expected.cpu_family)
2414 self.assertEqual(actual.endian, expected.endian)
2415
2416 self.assertEqual(actual.compilers, expected.compilers)
2417 self.assertEqual(actual.binaries, expected.binaries)
2418 self.assertEqual(actual.properties, expected.properties)
2419 self.assertEqual(actual.compile_args, expected.compile_args)
2420 self.assertEqual(actual.link_args, expected.link_args)
2421 self.assertEqual(actual.cmake, expected.cmake)