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