Debian Codegraph @

unittests/platformagnostictests.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2021 The Meson development team
3 # Copyright © 2024-2025 Intel Corporation
4
5 from __future__ import annotations
6 import json
7 import os
8 import pickle
9 import subprocess
10 import tempfile
11 import subprocess
12 import textwrap
13 import shutil
14 from unittest import skipIf, SkipTest
15 from pathlib import Path
16
17 from .baseplatformtests import BasePlatformTests
18 from .helpers import *
19 from mesonbuild.mesonlib import EnvironmentVariables, ExecutableSerialisation, MesonException, is_linux, python_command, windows_proof_rmtree
20 from mesonbuild.mformat import Formatter, match_path
21 from mesonbuild.optinterpreter import OptionInterpreter, OptionException
22 from mesonbuild.options import OptionStore
23 from run_tests import Backend
24
25 @skipIf(IS_CI and not is_linux(), "Run only on fast platforms")
26 class PlatformAgnosticTests(BasePlatformTests):
27 '''
28 Tests that does not need to run on all platforms during CI
29 '''
30
31 def test_relative_find_program(self):
32 '''
33 Tests that find_program() with a relative path does not find the program
34 in current workdir.
35 '''
36 testdir = os.path.join(self.unit_test_dir, '100 relative find program')
37 self.init(testdir, workdir=testdir)
38
39 def test_invalid_option_names(self):
40 store = OptionStore(False)
41 interp = OptionInterpreter(store, '')
42
43 def write_file(code: str):
44 with tempfile.NamedTemporaryFile('w', dir=self.builddir, encoding='utf-8', delete=False) as f:
45 f.write(code)
46 return f.name
47
48 fname = write_file("option('default_library', type: 'string')")
49 self.assertRaisesRegex(OptionException, 'Option name default_library is reserved.',
50 interp.process, fname)
51
52 fname = write_file("option('c_anything', type: 'string')")
53 self.assertRaisesRegex(OptionException, 'Option name c_anything is reserved.',
54 interp.process, fname)
55
56 fname = write_file("option('b_anything', type: 'string')")
57 self.assertRaisesRegex(OptionException, 'Option name b_anything is reserved.',
58 interp.process, fname)
59
60 fname = write_file("option('backend_anything', type: 'string')")
61 self.assertRaisesRegex(OptionException, 'Option name backend_anything is reserved.',
62 interp.process, fname)
63
64 fname = write_file("option('foo.bar', type: 'string')")
65 self.assertRaisesRegex(OptionException, 'Option names can only contain letters, numbers or dashes.',
66 interp.process, fname)
67
68 # platlib is allowed, only python.platlib is reserved.
69 fname = write_file("option('platlib', type: 'string')")
70 interp.process(fname)
71
72 def test_option_validation(self):
73 """Test cases that are not catch by the optinterpreter itself."""
74 store = OptionStore(False)
75 interp = OptionInterpreter(store, '')
76
77 def write_file(code: str):
78 with tempfile.NamedTemporaryFile('w', dir=self.builddir, encoding='utf-8', delete=False) as f:
79 f.write(code)
80 return f.name
81
82 fname = write_file("option('intminmax', type: 'integer', value: 10, min: 0, max: 5)")
83 self.assertRaisesRegex(MesonException, 'Value 10 for option "intminmax" is more than maximum value 5.',
84 interp.process, fname)
85
86 fname = write_file("option('array', type: 'array', choices : ['one', 'two', 'three'], value : ['one', 'four'])")
87 self.assertRaisesRegex(MesonException, 'Value "four" for option "array" is not in allowed choices: "one, two, three"',
88 interp.process, fname)
89
90 fname = write_file("option('array', type: 'array', choices : ['one', 'two', 'three'], value : ['four', 'five', 'six'])")
91 self.assertRaisesRegex(MesonException, 'Values "four, five, six" for option "array" are not in allowed choices: "one, two, three"',
92 interp.process, fname)
93
94 def test_python_dependency_without_pkgconfig(self):
95 testdir = os.path.join(self.unit_test_dir, '102 python without pkgconfig')
96 self.init(testdir, override_envvars={'PKG_CONFIG': 'notfound'})
97
98 def test_vala_target_with_internal_glib(self):
99 testdir = os.path.join(self.unit_test_dir, '131 vala internal glib')
100 for run in [{ 'version': '2.84.4', 'expected': '2.84'}, { 'version': '2.85.2', 'expected': '2.84' }]:
101 self.new_builddir()
102 self.init(testdir, extra_args=[f'-Dglib-version={run["version"]}'])
103 try:
104 with open(os.path.join(self.builddir, 'meson-info', 'intro-targets.json'), 'r', encoding='utf-8') as tgt_intro:
105 intro = json.load(tgt_intro)
106 target = list(filter(lambda tgt: tgt['name'] == 'vala-tgt', intro))
107 self.assertLength(target, 1)
108 sources = target[0]['target_sources']
109 vala_sources = filter(lambda src: src.get('language') == 'vala', sources)
110 for src in vala_sources:
111 self.assertIn(('--target-glib', run['expected']), zip(src['parameters'], src['parameters'][1:]))
112 except FileNotFoundError:
113 self.skipTest('Current backend does not produce introspection data')
114
115 def test_debug_function_outputs_to_meson_log(self):
116 testdir = os.path.join(self.unit_test_dir, '104 debug function')
117 log_msg = 'This is an example debug output, should only end up in debug log'
118 output = self.init(testdir)
119
120 # Check if message is not printed to stdout while configuring
121 self.assertNotIn(log_msg, output)
122
123 # Check if message is written to the meson log
124 mesonlog = self.get_meson_log_raw()
125 self.assertIn(log_msg, mesonlog)
126
127 def test_new_subproject_reconfigure(self):
128 testdir = os.path.join(self.unit_test_dir, '108 new subproject on reconfigure')
129 self.init(testdir)
130 self.build()
131
132 # Enable the subproject "foo" and reconfigure, this is used to fail
133 # because per-subproject builtin options were not initialized:
134 # https://github.com/mesonbuild/meson/issues/10225.
135 self.setconf('-Dfoo=enabled')
136 self.build('reconfigure')
137
138 def check_connectivity(self):
139 import urllib
140 try:
141 with urllib.request.urlopen('https://wrapdb.mesonbuild.com') as p:
142 pass
143 except urllib.error.URLError as e:
144 self.skipTest('No internet connectivity: ' + str(e))
145
146 def test_update_wrapdb(self):
147 self.check_connectivity()
148 # Write the project into a temporary directory because it will add files
149 # into subprojects/ and we don't want to pollute meson source tree.
150 with tempfile.TemporaryDirectory() as testdir:
151 with Path(testdir, 'meson.build').open('w', encoding='utf-8') as f:
152 f.write(textwrap.dedent(
153 '''
154 project('wrap update-db',
155 default_options: ['wrap_mode=forcefallback'])
156
157 zlib_dep = dependency('zlib')
158 assert(zlib_dep.type_name() == 'internal')
159 '''))
160 subprocess.check_call(self.wrap_command + ['update-db'], cwd=testdir)
161 self.init(testdir, workdir=testdir)
162
163 def test_none_backend(self):
164 testdir = os.path.join(self.python_test_dir, '7 install path')
165
166 self.init(testdir, extra_args=['--backend=none'], override_envvars={'NINJA': 'absolutely false command'})
167 self.assertPathDoesNotExist(os.path.join(self.builddir, 'build.ninja'))
168
169 self.run_tests(inprocess=True, override_envvars={})
170
171 out = self._run(self.meson_command + ['install', f'--destdir={self.installdir}'], workdir=self.builddir)
172 self.assertNotIn('Only ninja backend is supported to rebuild the project before installation.', out)
173
174 with open(os.path.join(testdir, 'test.json'), 'rb') as f:
175 dat = json.load(f)
176 for i in dat['installed']:
177 self.assertPathExists(os.path.join(self.installdir, i['file']))
178
179 def test_change_backend(self):
180 if self.backend != Backend.ninja:
181 raise SkipTest('Only useful to test if backend is ninja.')
182
183 testdir = os.path.join(self.python_test_dir, '7 install path')
184 self.init(testdir)
185
186 # no-op change works
187 with self.subTest('set the option to the same value'):
188 self.setconf('--backend=ninja')
189 self.init(testdir, extra_args=['--reconfigure', '--backend=ninja'])
190
191 # Change backend option is not allowed
192 with self.subTest('Changing the backend'):
193 with self.assertRaises(subprocess.CalledProcessError) as cm:
194 self.setconf('-Dbackend=none')
195 self.assertIn('ERROR: Tried to modify read only option "backend"', cm.exception.stdout)
196
197 # Check that the new value was not written in the store.
198 with self.subTest('option is stored correctly'):
199 self.assertEqual(self.getconf('backend'), 'ninja')
200
201 # Wipe with a different backend is allowed
202 with self.subTest('Changing the backend with wipe'):
203 self.init(testdir, extra_args=['--wipe', '--backend=none'])
204
205 self.assertEqual(self.getconf('backend'), 'none')
206
207 def test_validate_dirs(self):
208 testdir = os.path.join(self.common_test_dir, '1 trivial')
209
210 # Using parent as source directory should fail
211 self.builddir = os.path.dirname(os.getcwd())
212 with self.assertRaises(subprocess.CalledProcessError) as cm:
213 self.init(testdir)
214 self.assertIn('cannot be a parent of source directory', cm.exception.stdout)
215
216 # Reconfigure of empty builddir should work
217 self.new_builddir()
218 self.init(testdir, extra_args=['--reconfigure'])
219
220 # Reconfigure of not empty builddir should work
221 self.new_builddir()
222 Path(self.builddir, 'dummy').touch()
223 self.init(testdir, extra_args=['--reconfigure', '--buildtype=custom'])
224
225 # Setup a valid builddir should update options but not reconfigure
226 self.assertEqual(self.getconf('buildtype'), 'custom')
227 o = self.init(testdir, extra_args=['-Dbuildtype=release'])
228 self.assertIn('Directory already configured', o)
229 self.assertNotIn('The Meson build system', o)
230 self.assertEqual(self.getconf('buildtype'), 'release')
231
232 # Wipe of empty builddir should work
233 self.new_builddir()
234 self.init(testdir, extra_args=['--wipe'])
235
236 # Wipe of partial builddir should work
237 self.new_builddir()
238 Path(self.builddir, 'meson-private').mkdir()
239 Path(self.builddir, 'dummy').touch()
240 self.init(testdir, extra_args=['--wipe'])
241
242 # Wipe of not empty builddir should fail
243 self.new_builddir()
244 Path(self.builddir, 'dummy').touch()
245 with self.assertRaises(subprocess.CalledProcessError) as cm:
246 self.init(testdir, extra_args=['--wipe'])
247 self.assertIn('Directory is not empty', cm.exception.stdout)
248
249 def test_scripts_loaded_modules(self):
250 '''
251 Simulate a wrapped command, as done for custom_target() that capture
252 output. The script will print all python modules loaded and we verify
253 that it contains only an acceptable subset. Loading too many modules
254 slows down the build when many custom targets get wrapped.
255
256 This list must not be edited without a clear rationale for why it is
257 acceptable to do so!
258 '''
259 es = ExecutableSerialisation(python_command + ['-c', 'exit(0)'], env=EnvironmentVariables())
260 p = Path(self.builddir, 'exe.dat')
261 with p.open('wb') as f:
262 pickle.dump(es, f)
263 cmd = self.meson_command + ['--internal', 'test_loaded_modules', '--unpickle', str(p)]
264 p = subprocess.run(cmd, stdout=subprocess.PIPE)
265 all_modules = json.loads(p.stdout.splitlines()[0])
266 meson_modules = [m for m in all_modules if m.startswith('mesonbuild')]
267 expected_meson_modules = [
268 'mesonbuild',
269 'mesonbuild._pathlib',
270 'mesonbuild.utils',
271 'mesonbuild.utils.core',
272 'mesonbuild.mesonmain',
273 'mesonbuild.mlog',
274 'mesonbuild.scripts',
275 'mesonbuild.scripts.meson_exe',
276 'mesonbuild.scripts.test_loaded_modules'
277 ]
278 self.assertEqual(sorted(expected_meson_modules), sorted(meson_modules))
279
280 def test_setup_loaded_modules(self):
281 '''
282 Execute a very basic meson.build and capture a list of all python
283 modules loaded. We verify that it contains only an acceptable subset.
284 Loading too many modules slows down `meson setup` startup time and
285 gives a perception that meson is slow.
286
287 Adding more modules to the default startup flow is not an unreasonable
288 thing to do as new features are added, but keeping track of them is
289 good.
290 '''
291 testdir = os.path.join(self.unit_test_dir, '116 empty project')
292
293 self.init(testdir)
294 self._run(self.meson_command + ['--internal', 'regenerate', '--profile-self', testdir, self.builddir])
295 with open(os.path.join(self.builddir, 'meson-logs', 'profile-startup-modules.json'), encoding='utf-8') as f:
296 data = json.load(f)['meson']
297
298 with open(os.path.join(testdir, 'expected_mods.json'), encoding='utf-8') as f:
299 expected = json.load(f)['meson']
300
301 self.assertEqual(data['modules'], expected['modules'])
302 self.assertEqual(data['count'], expected['count'])
303
304 def test_meson_package_cache_dir(self):
305 # Copy testdir into temporary directory to not pollute meson source tree.
306 testdir = os.path.join(self.unit_test_dir, '118 meson package cache dir')
307 srcdir = os.path.join(self.builddir, 'srctree')
308 shutil.copytree(testdir, srcdir)
309 builddir = os.path.join(srcdir, '_build')
310 self.change_builddir(builddir)
311 self.init(srcdir, override_envvars={'MESON_PACKAGE_CACHE_DIR': os.path.join(srcdir, 'cache_dir')})
312
313 def test_cmake_openssl_not_found_bug(self):
314 """Issue #12098"""
315 testdir = os.path.join(self.unit_test_dir, '119 openssl cmake bug')
316 self.meson_native_files.append(os.path.join(testdir, 'nativefile.ini'))
317 out = self.init(testdir, allow_fail=True)
318 self.assertNotIn('Unhandled python exception', out)
319
320 def test_editorconfig_match_path(self):
321 '''match_path function used to parse editorconfig in meson format'''
322 cases = [
323 ('a.txt', '*.txt', True),
324 ('a.txt', '?.txt', True),
325 ('a.txt', 'a.t?t', True),
326 ('a.txt', '*.build', False),
327
328 ('/a.txt', '*.txt', True),
329 ('/a.txt', '/*.txt', True),
330 ('a.txt', '/*.txt', False),
331
332 ('a/b/c.txt', 'a/b/*.txt', True),
333 ('a/b/c.txt', 'a/*/*.txt', True),
334 ('a/b/c.txt', '*/*.txt', True),
335 ('a/b/c.txt', 'b/*.txt', True),
336 ('a/b/c.txt', 'a/*.txt', False),
337
338 ('a/b/c/d.txt', 'a/**/*.txt', True),
339 ('a/b/c/d.txt', 'a/*', False),
340 ('a/b/c/d.txt', 'a/**', True),
341
342 ('a.txt', '[abc].txt', True),
343 ('a.txt', '[!xyz].txt', True),
344 ('a.txt', '[xyz].txt', False),
345 ('a.txt', '[!abc].txt', False),
346
347 ('a.txt', '{a,b,c}.txt', True),
348 ('a.txt', '*.{txt,tex,cpp}', True),
349 ('a.hpp', '*.{txt,tex,cpp}', False),
350
351 ('a1.txt', 'a{0..9}.txt', True),
352 ('a001.txt', 'a{0..9}.txt', True),
353 ('a-1.txt', 'a{-10..10}.txt', True),
354 ('a99.txt', 'a{0..9}.txt', False),
355 ('a099.txt', 'a{0..9}.txt', False),
356 ('a-1.txt', 'a{0..10}.txt', False),
357 ]
358
359 for filename, pattern, expected in cases:
360 self.assertTrue(match_path(filename, pattern) is expected, f'{filename} -> {pattern}')
361
362 def test_format_invalid_config_key(self) -> None:
363 fd, fname = tempfile.mkstemp(suffix='.ini', text=True)
364 self.addCleanup(os.unlink, fname)
365
366 with os.fdopen(fd, 'w', encoding='utf-8') as handle:
367 handle.write('not_an_option = 42\n')
368
369 with self.assertRaises(MesonException):
370 Formatter(Path(fname), use_editor_config=False, fetch_subdirs=False)
371
372 def test_format_invalid_config_value(self) -> None:
373 fd, fname = tempfile.mkstemp(suffix='.ini', text=True)
374 self.addCleanup(os.unlink, fname)
375
376 with os.fdopen(fd, 'w', encoding='utf-8') as handle:
377 handle.write('max_line_length = string\n')
378
379 with self.assertRaises(MesonException):
380 Formatter(Path(fname), use_editor_config=False, fetch_subdirs=False)
381
382 def test_format_invalid_editorconfig_value(self) -> None:
383 dirpath = tempfile.mkdtemp()
384 self.addCleanup(windows_proof_rmtree, dirpath)
385
386 editorconfig = Path(dirpath, '.editorconfig')
387 with open(editorconfig, 'w', encoding='utf-8') as handle:
388 handle.write('[*]\n')
389 handle.write('indent_size = string\n')
390
391 formatter = Formatter(None, use_editor_config=True, fetch_subdirs=False)
392 with self.assertRaises(MesonException):
393 formatter.load_editor_config(editorconfig)
394
395 def test_format_empty_file(self) -> None:
396 formatter = Formatter(None, use_editor_config=False, fetch_subdirs=False)
397 for code in ('', '\n'):
398 formatted = formatter.format(code, Path())
399 self.assertEqual('\n', formatted)
400
401 def test_format_indent_comment_in_brackets(self) -> None:
402 """Ensure comments in arrays and dicts are correctly indented"""
403 formatter = Formatter(None, use_editor_config=False, fetch_subdirs=False)
404 code = 'a = [\n # comment\n]\n'
405 formatted = formatter.format(code, Path())
406 self.assertEqual(code, formatted)
407
408 code = 'a = [\n # comment\n 1,\n]\n'
409 formatted = formatter.format(code, Path())
410 self.assertEqual(code, formatted)
411
412 code = 'a = {\n # comment\n}\n'
413 formatted = formatter.format(code, Path())
414 self.assertEqual(code, formatted)
415
416 def test_error_configuring_subdir(self):
417 testdir = os.path.join(self.common_test_dir, '152 index customtarget')
418 out = self.init(os.path.join(testdir, 'subdir'), allow_fail=True)
419
420 self.assertIn('first statement must be a call to project()', out)
421 # provide guidance diagnostics by finding a file whose first AST statement is project()
422 self.assertIn(f'Did you mean to run meson from the directory: "{testdir}"?', out)
423
424 def test_reconfigure_base_options(self):
425 testdir = os.path.join(self.unit_test_dir, '123 reconfigure base options')
426 out = self.init(testdir, extra_args=['-Db_ndebug=true'])
427 self.assertIn('\nMessage: b_ndebug: true\n', out)
428 self.assertIn('\nMessage: c_std: c89\n', out)
429
430 out = self.init(testdir, extra_args=['--reconfigure', '-Db_ndebug=if-release', '-Dsub:b_ndebug=false', '-Dc_std=c99', '-Dsub:c_std=c11'])
431 self.assertIn('\n b_ndebug : if-release\n', out)
432 self.assertIn('\n c_std : c99\n', out)
433 self.assertIn('\n sub:b_ndebug: false\n', out)
434 self.assertIn('\n sub:c_std : c11\n', out)
435
436 def test_setup_with_unknown_option(self):
437 testdir = os.path.join(self.common_test_dir, '1 trivial')
438
439 with self.subTest('unknown user option'):
440 out = self.init(testdir, extra_args=['-Dnot_an_option=1'], allow_fail=True)
441 self.assertIn('ERROR: Unknown option: "not_an_option"', out)
442
443 with self.subTest('unknown builtin option'):
444 self.new_builddir()
445 out = self.init(testdir, extra_args=['-Db_not_an_option=1'], allow_fail=True)
446 self.assertIn('ERROR: Unknown option: "b_not_an_option"', out)
447
448
449 def test_configure_new_option(self) -> None:
450 """Adding a new option without reconfiguring should work."""
451 testdir = self.copy_srcdir(os.path.join(self.common_test_dir, '40 options'))
452 self.init(testdir)
453 with open(os.path.join(testdir, 'meson_options.txt'), 'a', encoding='utf-8') as f:
454 f.write("option('new_option', type : 'boolean', value : false)")
455 self.setconf('-Dnew_option=true')
456 self.assertEqual(self.getconf('new_option'), True)
457
458 def test_configure_removed_option(self) -> None:
459 """Removing an options without reconfiguring should still give an error."""
460 testdir = self.copy_srcdir(os.path.join(self.common_test_dir, '40 options'))
461 self.init(testdir)
462 with open(os.path.join(testdir, 'meson_options.txt'), 'r', encoding='utf-8') as f:
463 opts = f.readlines()
464 with open(os.path.join(testdir, 'meson_options.txt'), 'w', encoding='utf-8') as f:
465 for line in opts:
466 if line.startswith("option('neg'"):
467 continue
468 f.write(line)
469 with self.assertRaises(subprocess.CalledProcessError) as e:
470 self.setconf('-Dneg_int_opt=0')
471 self.assertIn('Unknown option: "neg_int_opt"', e.exception.stdout)
472
473 def test_reconfigure_option(self) -> None:
474 testdir = self.copy_srcdir(os.path.join(self.common_test_dir, '40 options'))
475 self.init(testdir)
476 self.assertEqual(self.getconf('neg_int_opt'), -3)
477 with self.assertRaises(subprocess.CalledProcessError) as e:
478 self.init(testdir, extra_args=['--reconfigure', '-Dneg_int_opt=0'])
479 self.assertEqual(self.getconf('neg_int_opt'), -3)
480 self.init(testdir, extra_args=['--reconfigure', '-Dneg_int_opt=-2'])
481 self.assertEqual(self.getconf('neg_int_opt'), -2)
482
483 def test_configure_option_changed_constraints(self) -> None:
484 """Changing the constraints of an option without reconfiguring should work."""
485 testdir = self.copy_srcdir(os.path.join(self.common_test_dir, '40 options'))
486 self.init(testdir)
487 with open(os.path.join(testdir, 'meson_options.txt'), 'r', encoding='utf-8') as f:
488 opts = f.readlines()
489 with open(os.path.join(testdir, 'meson_options.txt'), 'w', encoding='utf-8') as f:
490 for line in opts:
491 if line.startswith("option('neg'"):
492 f.write("option('neg_int_opt', type : 'integer', min : -10, max : 10, value : -3)\n")
493 else:
494 f.write(line)
495 self.setconf('-Dneg_int_opt=-10')
496 self.assertEqual(self.getconf('neg_int_opt'), -10)
497
498 def test_configure_meson_options_txt_to_meson_options(self) -> None:
499 """Changing from a meson_options.txt to meson.options should still be detected."""
500 testdir = self.copy_srcdir(os.path.join(self.common_test_dir, '40 options'))
501 self.init(testdir)
502 with open(os.path.join(testdir, 'meson_options.txt'), 'r', encoding='utf-8') as f:
503 opts = f.readlines()
504 with open(os.path.join(testdir, 'meson_options.txt'), 'w', encoding='utf-8') as f:
505 for line in opts:
506 if line.startswith("option('neg'"):
507 f.write("option('neg_int_opt', type : 'integer', min : -10, max : 10, value : -3)\n")
508 else:
509 f.write(line)
510 shutil.move(os.path.join(testdir, 'meson_options.txt'), os.path.join(testdir, 'meson.options'))
511 self.setconf('-Dneg_int_opt=-10')
512 self.assertEqual(self.getconf('neg_int_opt'), -10)
513
514 def test_configure_options_file_deleted(self) -> None:
515 """Deleting all option files should make seting a project option an error."""
516 testdir = self.copy_srcdir(os.path.join(self.common_test_dir, '40 options'))
517 self.init(testdir)
518 os.unlink(os.path.join(testdir, 'meson_options.txt'))
519 with self.assertRaises(subprocess.CalledProcessError) as e:
520 self.setconf('-Dneg_int_opt=0')
521 self.assertIn('Unknown option: "neg_int_opt"', e.exception.stdout)
522
523 def test_configure_options_file_added(self) -> None:
524 """A new project option file should be detected."""
525 testdir = self.copy_srcdir(os.path.join(self.common_test_dir, '1 trivial'))
526 self.init(testdir)
527 with open(os.path.join(testdir, 'meson.options'), 'w', encoding='utf-8') as f:
528 f.write("option('new_option', type : 'string', value : 'foo')")
529 self.setconf('-Dnew_option=bar')
530 self.assertEqual(self.getconf('new_option'), 'bar')
531
532 def test_configure_options_file_added_old(self) -> None:
533 """A new project option file should be detected."""
534 testdir = self.copy_srcdir(os.path.join(self.common_test_dir, '1 trivial'))
535 self.init(testdir)
536 with open(os.path.join(testdir, 'meson_options.txt'), 'w', encoding='utf-8') as f:
537 f.write("option('new_option', type : 'string', value : 'foo')")
538 self.setconf('-Dnew_option=bar')
539 self.assertEqual(self.getconf('new_option'), 'bar')
540
541 def test_configure_new_option_subproject(self) -> None:
542 """Adding a new option to a subproject without reconfiguring should work."""
543 testdir = self.copy_srcdir(os.path.join(self.common_test_dir, '43 subproject options'))
544 self.init(testdir)
545 with open(os.path.join(testdir, 'subprojects/subproject/meson_options.txt'), 'a', encoding='utf-8') as f:
546 f.write("option('new_option', type : 'boolean', value : false)")
547 self.setconf('-Dsubproject:new_option=true')
548 self.assertEqual(self.getconf('subproject:new_option'), True)
549
550 def test_mtest_rebuild_deps(self):
551 testdir = os.path.join(self.unit_test_dir, '106 underspecified mtest')
552 self.init(testdir)
553
554 with self.assertRaises(subprocess.CalledProcessError):
555 self._run(self.mtest_command)
556 self.clean()
557
558 with self.assertRaises(subprocess.CalledProcessError):
559 self._run(self.mtest_command + ['runner-without-dep'])
560 self.clean()
561
562 self._run(self.mtest_command + ['runner-with-exedep'])
563
564 def test_buildtype_debug_optimization_override(self) -> None:
565 """Explicitly setting debug or optimization should override buildtype."""
566 testdir = os.path.join(self.common_test_dir, '1 trivial')
567
568 for extra_args in [['--debug', '--buildtype=release'],
569 ['-Ddebug=true', '--buildtype=release'],
570 ['-Ddebug=true', '-Dbuildtype=release'],
571 ['--debug', '-Dbuildtype=release']]:
572 with self.subTest(extra_args=extra_args):
573 self.new_builddir()
574 self.init(testdir, extra_args=extra_args)
575 opts = self.introspect('--buildoptions')
576 self.assertEqual(self.getconf('buildtype', opts), 'release')
577 self.assertEqual(self.getconf('debug', opts), True)
578 self.assertEqual(self.getconf('optimization', opts), '3')
579
580 for extra_args in [['--optimization=3', '--buildtype=debug'],
581 ['-Doptimization=3', '--buildtype=debug'],
582 ['-Doptimization=3', '-Dbuildtype=debug'],
583 ['--optimization=3', '-Dbuildtype=debug']]:
584 with self.subTest(extra_args=extra_args):
585 self.new_builddir()
586 self.init(testdir, extra_args=extra_args)
587 opts = self.introspect('--buildoptions')
588 self.assertEqual(self.getconf('buildtype', opts), 'debug')
589 self.assertEqual(self.getconf('debug', opts), True)
590 self.assertEqual(self.getconf('optimization', opts), '3')
591
592 def test_setup_mixed_long_short_options(self) -> None:
593 """Mixing unity and unity_size as long and short options should work."""
594 testdir = self.copy_srcdir(os.path.join(self.common_test_dir, '1 trivial'))
595 self.init(testdir, extra_args=['-Dunity=on', '--unity-size=123'])
596
597 def test_minit_executable_with_matching_source(self) -> None:
598 """meson init --executable bar with bar.c present must not create a spurious project-name.c"""
599 with tempfile.TemporaryDirectory() as d:
600 Path(d, 'bar.c').write_text('int main() {}', encoding='utf-8')
601 self._run(self.meson_command + ['init', '--name', 'foo', '--executable', 'bar', '--language', 'c'], workdir=d)
602 files = {p.name for p in Path(d).iterdir()}
603 self.assertIn('meson.build', files)
604 self.assertNotIn('foo.c', files, 'spurious foo.c was created')
605 meson_build = Path(d, 'meson.build').read_text(encoding='utf-8')
606 self.assertNotIn("'foo.c'", meson_build, 'spurious foo.c listed in meson.build')
607 self.assertIn("'bar.c'", meson_build, 'existing bar.c not listed in meson.build')
608
609 def test_minit_multi_file_keeps_existing_sources(self) -> None:
610 """meson init without --executable must create a new source file alongside existing ones"""
611 with tempfile.TemporaryDirectory() as d:
612 Path(d, 'bar.c').write_text('int bar() {}', encoding='utf-8')
613 Path(d, 'foo.c').write_text('int main() {}', encoding='utf-8')
614 self._run(self.meson_command + ['init', '--name', 'foo', '--language', 'c'], workdir=d)
615 files = {p.name for p in Path(d).iterdir()}
616 self.assertIn('meson.build', files)
617 meson_build = Path(d, 'meson.build').read_text(encoding='utf-8')
618 self.assertIn("'foo.c'", meson_build, 'existing foo.c not listed in meson.build')
619 self.assertIn("'bar.c'", meson_build, 'existing bar.c not listed in meson.build')
620
621 def test_minit_wrong_name_creates_sample(self) -> None:
622 """meson init in an empty directory must create a sample source file"""
623 with tempfile.TemporaryDirectory() as d:
624 Path(d, 'bar.c').write_text('int main() {}', encoding='utf-8')
625 self._run(self.meson_command + ['init', '--name', 'foo', '--language', 'c'], workdir=d)
626 files = {p.name for p in Path(d).iterdir()}
627 self.assertIn('meson.build', files)
628 self.assertIn('foo.c', files)
629 meson_build = Path(d, 'meson.build').read_text(encoding='utf-8')
630 self.assertIn("'foo.c'", meson_build, 'created foo.c not listed in meson.build')
631 self.assertNotIn("'bar.c'", meson_build, 'existing bar.c listed in meson.build')
632
633 def test_minit_empty_dir_creates_sample(self) -> None:
634 """meson init in an empty directory must create a sample source file"""
635 with tempfile.TemporaryDirectory() as d:
636 self._run(self.meson_command + ['init', '--name', 'foo', '--language', 'c'], workdir=d)
637 files = {p.name for p in Path(d).iterdir()}
638 self.assertIn('meson.build', files)
639 self.assertIn('foo.c', files)
640 meson_build = Path(d, 'meson.build').read_text(encoding='utf-8')
641 self.assertIn("'foo.c'", meson_build, 'created foo.c not listed in meson.build')
642
643 def test_readonly_sourcedir(self) -> None:
644 """Test building with read-only source directory."""
645 testdir = self.copy_srcdir(os.path.join(self.common_test_dir, '233 wrap case'))
646
647 # Make the source directory and all its contents read-only recursively
648 # Keep execute permission on directories
649 for dir, _, files in os.walk(testdir):
650 os.chmod(dir, 0o555)
651 for file in files:
652 filepath = os.path.join(dir, file)
653 os.chmod(filepath, 0o444)
654
655 self.init(testdir)
656 self.build()
657
658 @skip_if_not_language('java')
659 def test_java_build_subdir_correct_deps(self):
660 """Test that jar() with build_subdir sources does not rebuild unnecessarily."""
661 testdir = os.path.join(self.src_root, 'test cases', 'java', '11 build subdir')
662 self.init(testdir)
663 self.build()
664 self.assertBuildIsNoop()