Debian Codegraph @

ml_collections/config_flags/tests/config_overriding_test.py

raw symbols SCIP
1 # Copyright 2024 The ML Collections Authors.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 """Tests for ml_collection.config_flags."""
16
17 import copy
18 import shlex
19 import sys
20 import tempfile
21
22 from absl import flags
23 from absl.testing import absltest
24 from absl.testing import flagsaver
25 from absl.testing import parameterized
26 from ml_collections import config_dict
27 from ml_collections.config_flags import config_flags
28 from ml_collections.config_flags.tests import mock_config
29 from ml_collections.config_flags.tests import spork
30
31 import pytest
32
33
34 _CHECK_TYPES = (int, str, float, bool)
35
36 _TEST_DIRECTORY = 'ml_collections/config_flags/tests'
37 _TEST_CONFIG_FILE = '{}/mock_config.py'.format(_TEST_DIRECTORY)
38 # Parameters to test that config loading and overriding works with both
39 # one and two dashes.
40 _DASH_PARAMETERS = (
41 ('WithTwoDashesAndEqual', '--test_config={}'.format(_TEST_CONFIG_FILE)),
42 ('WithTwoDashes', '--test_config {}'.format(_TEST_CONFIG_FILE)),
43 ('WithOneDashAndEqual', '-test_config={}'.format(_TEST_CONFIG_FILE)),
44 ('WithOneDash', '-test_config {}'.format(_TEST_CONFIG_FILE)))
45
46 _CONFIGDICT_CONFIG_FILE = '{}/configdict_config.py'.format(_TEST_DIRECTORY)
47 _IOERROR_CONFIG_FILE = '{}/ioerror_config.py'.format(_TEST_DIRECTORY)
48 _VALUEERROR_CONFIG_FILE = '{}/valueerror_config.py'.format(_TEST_DIRECTORY)
49 _TYPEERROR_CONFIG_FILE = '{}/typeerror_config.py'.format(_TEST_DIRECTORY)
50 _FIELDREFERENCE_CONFIG_FILE = '{}/fieldreference_config.py'.format(
51 _TEST_DIRECTORY)
52 _PARAMETERISED_CONFIG_FILE = '{}/parameterised_config.py'.format(
53 _TEST_DIRECTORY)
54 _LITERAL_CONFIG_FILE = '{}/literal_config.py'.format(_TEST_DIRECTORY)
55
56
57 def _parse_flags(
58 command,
59 default=None,
60 config=None,
61 lock_config=True,
62 required=False,
63 accept_new_attributes=False,
64 use_sys_argv_override=False,
65 ):
66 """Parses arguments simulating sys.argv or via sys_argv argument."""
67
68 if config is not None and default is not None:
69 raise ValueError('If config is supplied a default should not be.')
70
71 # The module shlex is useful here because it splits the input similar to
72 # sys.argv. For instance, string arguments are not split by space.
73 argv = shlex.split(command)
74
75 # Storing copy of the old sys.argv.
76 old_argv = list(sys.argv)
77 # Overwriting sys.argv, as sys has a global state it gets propagated.
78 if not use_sys_argv_override:
79 sys.argv = argv
80
81 # Actual parsing.
82 values = flags.FlagValues()
83 if config is None:
84 config_flags.DEFINE_config_file(
85 'test_config',
86 default=default,
87 flag_values=values,
88 lock_config=lock_config,
89 accept_new_attributes=accept_new_attributes,
90 sys_argv=(argv if use_sys_argv_override else None),
91 )
92 else:
93 config_flags.DEFINE_config_dict(
94 'test_config',
95 config=config,
96 flag_values=values,
97 lock_config=lock_config,
98 sys_argv=(argv if use_sys_argv_override else None))
99
100 if required:
101 flags.mark_flag_as_required('test_config', flag_values=values)
102 values(argv)
103
104 # Going back to original values.
105 if not use_sys_argv_override:
106 sys.argv = old_argv
107
108 return values
109
110
111 def _get_override_flags(overrides, override_format):
112 return ' '.join([override_format.format(path, value)
113 for path, value in overrides.items()])
114
115
116 class _ConfigFlagTestCase(object):
117 """Base class for tests with additional asserts for comparing configs."""
118
119 def assert_subset_configs(self, config1, config2):
120 """Checks if all attributes/values in config1 are present in config2."""
121
122 if config1 is None:
123 return
124
125 if hasattr(config1, '__dict__'):
126 keys = [key for key in config1.__dict__ if not key.startswith('_')]
127 get_val = getattr
128 elif hasattr(config1, 'keys') and callable(config1.keys):
129 keys = [key for key in config1.keys() if not key.startswith('_')]
130 get_val = lambda haystack, needle: haystack[needle]
131 else:
132 # This should not fail as it simply means we cannot iterate deeper.
133 return
134
135 for attribute in keys:
136 if isinstance(get_val(config1, attribute), _CHECK_TYPES):
137 self.assertEqual(get_val(config1, attribute),
138 get_val(config2, attribute))
139 else:
140 # Try to go deeper with comparison
141 self.assert_subset_configs(get_val(config1, attribute),
142 get_val(config2, attribute))
143
144 def assert_equal_configs(self, config1, config2):
145 """Checks if two configs are identical."""
146 self.assert_subset_configs(config1, config2)
147 self.assert_subset_configs(config2, config1) # pylint: disable=arguments-out-of-order
148
149
150 class ConfigFileFlagTest(_ConfigFlagTestCase, parameterized.TestCase):
151 """Tests config flags library."""
152
153 @parameterized.named_parameters(*_DASH_PARAMETERS)
154 def testLoading(self, config_flag):
155 """Tests loading config from file."""
156
157 values = _parse_flags('./program {}'.format(config_flag),
158 default='nonexisting.py')
159
160 self.assertIn('test_config', values)
161
162 self.assert_equal_configs(values.test_config,
163 mock_config.get_config())
164 self.assertEqual(
165 values['test_config'].serialize(),
166 '--test_config=ml_collections/config_flags/tests/mock_config.py',
167 )
168
169 @parameterized.named_parameters(*_DASH_PARAMETERS)
170 def testRequired(self, config_flag):
171 """Tests making a config_file flag required."""
172 with self.assertRaises(flags.IllegalFlagValueError):
173 _parse_flags('./program ', required=True)
174
175 values = _parse_flags('./program {}'.format(config_flag),
176 required=True)
177 self.assertIn('test_config', values)
178
179 def testDefaultLoading(self):
180 """Tests loading config from file using default path."""
181
182 for required in [True, False]:
183 values = _parse_flags(
184 './program', default=_TEST_CONFIG_FILE, required=required)
185
186 self.assertIn('test_config', values)
187
188 self.assert_equal_configs(values.test_config,
189 mock_config.get_config())
190 self.assertEqual(
191 values['test_config'].serialize(),
192 f'--test_config={_TEST_CONFIG_FILE}',
193 )
194
195 def testLoadingNonExistingConfigLoading(self):
196 """Tests whether loading non existing file raises an error."""
197
198 nonexisting_file = 'nonexisting.py'
199
200 # Test whether loading non existing files raises an Error with both
201 # file loading formats i.e. with '--' and '-'.
202 # The Error is not expected to be raised until the config dict actually
203 # has one of its attributes accessed.
204 values = _parse_flags(
205 './program --test_config={}'.format(nonexisting_file),
206 default=_TEST_CONFIG_FILE)
207 with self.assertRaisesRegex(IOError, '.*{}.*'.format(nonexisting_file)):
208 _ = values.test_config.a
209
210 values = _parse_flags(
211 './program -test_config {}'.format(nonexisting_file),
212 default=_TEST_CONFIG_FILE)
213 with self.assertRaisesRegex(IOError, '.*{}.*'.format(nonexisting_file)):
214 _ = values.test_config.a
215
216 values = _parse_flags(
217 './program -test_config ""', default=_TEST_CONFIG_FILE)
218 with self.assertRaisesRegex(IOError, 'empty string'):
219 _ = values.test_config.a
220
221 def testIOError(self):
222 """Tests that IOErrors raised inside config files are reported correctly."""
223 values = _parse_flags('./program --test_config={}'
224 .format(_IOERROR_CONFIG_FILE))
225 with self.assertRaisesRegex(IOError, 'This is an IOError'):
226 _ = values.test_config.a
227
228 def testValueError(self):
229 """Tests that ValueErrors raised when parsing config files are passed up."""
230 allchars_regexp = r'[\s\S]*'
231 error_regexp = allchars_regexp.join(['Error whilst parsing config file',
232 'in get_config',
233 'in value_error_function',
234 'This is a ValueError'])
235 with self.assertRaisesRegex(flags.IllegalFlagValueError, error_regexp):
236 _ = _parse_flags('./program --test_config={}'
237 .format(_VALUEERROR_CONFIG_FILE))
238
239 def testTypeError(self):
240 """Tests that TypeErrors raised when parsing config files are passed up."""
241 allchars_regexp = r'[\s\S]*'
242 error_regexp = allchars_regexp.join(['Error whilst parsing config file',
243 'in get_config',
244 'in type_error_function',
245 'This is a TypeError'])
246 with self.assertRaisesRegex(flags.IllegalFlagValueError, error_regexp):
247 _ = _parse_flags('./program --test_config={}'
248 .format(_TYPEERROR_CONFIG_FILE))
249
250 # Note: While testing the overriding of parameters, we explicitly set
251 # '!r' in the format string for the value. This ensures the 'repr()' is
252 # called on the argument which basically means that for string arguments,
253 # the quotes (' ') are left intact when we format the string.
254 @parameterized.named_parameters(
255 ('TwoDashConfigAndOverride',
256 '--test_config={}'.format(_TEST_CONFIG_FILE), '--test_config.{}={!r}',
257 False),
258 ('TwoDashSpaceConfigAndOverride',
259 '--test_config {}'.format(_TEST_CONFIG_FILE), '--test_config.{} {!r}',
260 False),
261 ('OneDashConfigAndOverride',
262 '-test_config {}'.format(_TEST_CONFIG_FILE), '-test_config.{} {!r}',
263 False),
264 ('OneDashEqualConfigAndOverride',
265 '-test_config={}'.format(_TEST_CONFIG_FILE), '-test_config.{}={!r}',
266 False),
267 ('OneDashConfigAndTwoDashOverride',
268 '-test_config {}'.format(_TEST_CONFIG_FILE), '--test_config.{}={!r}',
269 False),
270 ('TwoDashConfigAndOneDashOverride',
271 '--test_config={}'.format(_TEST_CONFIG_FILE), '-test_config.{} {!r}',
272 False),
273 ('TwoDashConfigAndOverrideAndSysArgvOverride',
274 '--test_config={}'.format(_TEST_CONFIG_FILE), '--test_config.{}={!r}',
275 True),
276 ('TwoDashSpaceConfigAndOverrideAndSysArgvOverride',
277 '--test_config {}'.format(_TEST_CONFIG_FILE), '--test_config.{} {!r}',
278 True),
279 )
280 def testOverride(self, config_flag, override_format, use_sys_argv_override):
281 """Tests overriding config values from command line."""
282 overrides = {
283 'integer': 1,
284 'float': -3,
285 'dict.float': 3,
286 'object.integer': 12,
287 'object.float': 123,
288 'object.string': 'tom',
289 'object.dict.integer': -2,
290 'object.dict.float': 3.15,
291 'object.dict.list[0]': 101,
292 'object.dict.list[2][0]': 103,
293 'object.list[0]': 101,
294 'object.list[2][0]': 103,
295 'object.tuple': '(1,2,(1,2))',
296 'object.tuple_with_spaces': '(1, 2, (1, 2))',
297 'object_reference.dict.string': 'marry',
298 'object.dict.dict.float': 123,
299 'object_copy.float': 111.111
300 }
301
302 override_flags = _get_override_flags(overrides, override_format)
303 values = _parse_flags(
304 './program {} {}'.format(config_flag, override_flags),
305 use_sys_argv_override=use_sys_argv_override)
306
307 test_config = mock_config.get_config()
308 test_config.integer = overrides['integer']
309 test_config.float = overrides['float']
310 test_config.dict['float'] = overrides['dict.float']
311 test_config.object.integer = overrides['object.integer']
312 test_config.object.float = overrides['object.float']
313 test_config.object.string = overrides['object.string']
314 test_config.object.dict['integer'] = overrides['object.dict.integer']
315 test_config.object.dict['float'] = overrides['object.dict.float']
316 test_config.object.dict['list'][0] = overrides['object.dict.list[0]']
317 test_config.object.dict['list'][2][0] = overrides['object.dict.list[2][0]']
318 test_config.object.dict['list'][0] = overrides['object.list[0]']
319 test_config.object.dict['list'][2][0] = overrides['object.list[2][0]']
320 test_config.object.tuple = (1, 2, (1, 2))
321 test_config.object.tuple_with_spaces = (1, 2, (1, 2))
322 test_config.object_reference.dict['string'] = overrides[
323 'object_reference.dict.string']
324 test_config.object.dict['dict']['float'] = overrides[
325 'object.dict.dict.float']
326 test_config.object_copy.float = overrides['object_copy.float']
327
328 self.assert_equal_configs(values.test_config, test_config)
329
330 @parameterized.named_parameters(
331 ('GlobalSysArgvParsing', False),
332 ('SysArgvOverride', True))
333 def testOverrideBoolean(self, use_sys_argv_override):
334 """Tests overriding boolean config values from command line."""
335 prefix = './program --test_config={}'.format(_TEST_CONFIG_FILE)
336
337 # The default for dict.bool is False.
338 values = _parse_flags(
339 '{} --test_config.dict.bool'.format(prefix),
340 use_sys_argv_override=use_sys_argv_override)
341 self.assertTrue(values.test_config.dict['bool'])
342
343 values = _parse_flags(
344 '{} --test_config.dict.bool=true'.format(prefix),
345 use_sys_argv_override=use_sys_argv_override)
346 self.assertTrue(values.test_config.dict['bool'])
347
348 # The default for object.bool is True.
349 values = _parse_flags(
350 '{} --test_config.object.bool=false'.format(prefix),
351 use_sys_argv_override=use_sys_argv_override)
352 self.assertFalse(values.test_config.object.bool)
353
354 values = _parse_flags(
355 '{} --notest_config.object.bool'.format(prefix),
356 use_sys_argv_override=use_sys_argv_override)
357 self.assertFalse(values.test_config.object.bool)
358
359 def testOverrideEnum(self):
360 """Tests overriding enumn config values from command line."""
361 prefix = './program --test_config={}'.format(_TEST_CONFIG_FILE)
362
363 # The default for dict.enum is SPOON.
364 values = _parse_flags('{} --test_config.enum=FORK'.format(prefix))
365 self.assertEqual(values.test_config.enum, spork.SporkType.FORK)
366 # Flag is case-insensetive.
367 values = _parse_flags('{} --test_config.enum=spork'.format(prefix))
368 self.assertEqual(values.test_config.enum, spork.SporkType.SPORK)
369
370 def testFieldReferenceOverride(self):
371 """Tests whether types of FieldReference fields are valid."""
372 overrides = {'ref_nodefault': 1, 'ref': 2}
373 override_flags = _get_override_flags(overrides, '--test_config.{}={!r}')
374 config_flag = '--test_config={}'.format(_FIELDREFERENCE_CONFIG_FILE)
375 values = _parse_flags('./program {} {}'.format(config_flag, override_flags))
376 cfg = values.test_config
377
378 self.assertEqual(cfg.ref_nodefault, overrides['ref_nodefault'])
379 self.assertEqual(cfg.ref, overrides['ref'])
380
381 @parameterized.named_parameters(*_DASH_PARAMETERS)
382 def testSetNotExistingKey(self, config_flag):
383 """Tests setting value of not existing key."""
384
385 with self.assertRaises(KeyError):
386 _parse_flags('./program {} '
387 '--test_config.not_existing_key=1 '.format(config_flag))
388
389 @parameterized.named_parameters(*_DASH_PARAMETERS)
390 def testSetReadOnlyField(self, config_flag):
391 """Tests setting value of key which is read only."""
392
393 with self.assertRaises(AttributeError):
394 _parse_flags('./program {} '
395 '--test_config.readonly_field=1 '.format(config_flag))
396
397 @parameterized.named_parameters(*_DASH_PARAMETERS)
398 def testNotSupportedOperation(self, config_flag):
399 """Tests setting value to not supported type."""
400
401 with self.assertRaises(config_flags.UnsupportedOperationError):
402 _parse_flags('./program {} '
403 '--test_config.list=[1]'.format(config_flag))
404
405 def testParserWrapping(self):
406 """Tests callback based Parser wrapping."""
407
408 parser = flags.IntegerParser()
409
410 test_config = mock_config.get_config()
411 overrides = {}
412
413 config_field_flag = config_flags._ConfigFieldFlag(
414 path='integer',
415 config=test_config,
416 override_values=overrides,
417 parser=parser,
418 serializer=flags.ArgumentSerializer(),
419 name='integer',
420 default=test_config.integer,
421 help_string='')
422
423 config_field_flag.parse('12321')
424 self.assertEqual(test_config.integer, 12321)
425 self.assertEqual(overrides, {'integer': 12321})
426
427 def testTypes(self):
428 """Tests whether various types of objects are valid."""
429
430 parser = config_flags.ConfigFileFlagParser('test_config')
431 self.assertEqual(parser.flag_type(), 'config object')
432
433 @parameterized.named_parameters(
434 ('WithTwoDashesAndEqual', '--test_config=config.py'),
435 ('WithTwoDashes', '--test_config'),
436 ('WithOneDashAndEqual', '-test_config=config.py'),
437 ('WithOneDash', '-test_config'))
438 def testConfigSpecified(self, config_argument):
439 """Tests whether config is specified on the command line."""
440
441 config_flag = config_flags._ConfigFlag(
442 parser=flags.ArgumentParser(),
443 serializer=None,
444 name='test_config',
445 default='defaultconfig.py',
446 help_string=''
447 )
448 self.assertTrue(config_flag._IsConfigSpecified([config_argument]))
449 self.assertFalse(config_flag._IsConfigSpecified(['']))
450
451 def testFindConfigSpecified(self):
452 """Tests whether config is specified on the command line."""
453
454 config_flag = config_flags._ConfigFlag(
455 parser=flags.ArgumentParser(),
456 serializer=None,
457 name='test_config',
458 default='defaultconfig.py',
459 help_string=''
460 )
461 self.assertEqual(config_flag._FindConfigSpecified(['']), -1)
462
463 argv_length = 20
464 for i in range(argv_length):
465 # Generate list of '--test_config.i=0' args.
466 argv = ['--test_config.{}=0'.format(arg) for arg in range(argv_length)]
467 self.assertEqual(config_flag._FindConfigSpecified(argv), -1)
468
469 # Override i-th arg with something specifying the value of 'test_config'.
470 # After doing this, _FindConfigSpecified should return the value of i.
471 argv[i] = '--test_config'
472 self.assertEqual(config_flag._FindConfigSpecified(argv), i)
473 argv[i] = '--test_config=config.py'
474 self.assertEqual(config_flag._FindConfigSpecified(argv), i)
475 argv[i] = '-test_config'
476 self.assertEqual(config_flag._FindConfigSpecified(argv), i)
477 argv[i] = '-test_config=config.py'
478 self.assertEqual(config_flag._FindConfigSpecified(argv), i)
479
480 def testLoadingLockedConfigDict(self):
481 """Tests loading ConfigDict instance and that it is locked."""
482
483 config_flag = '--test_config={}'.format(_CONFIGDICT_CONFIG_FILE)
484 values = _parse_flags('./program {}'.format(config_flag),
485 lock_config=True)
486
487 self.assertTrue(values.test_config.is_locked)
488 self.assertTrue(values.test_config.nested_configdict.is_locked)
489
490 values = _parse_flags('./program {}'.format(config_flag),
491 lock_config=False)
492
493 self.assertFalse(values.test_config.is_locked)
494 self.assertFalse(values.test_config.nested_configdict.is_locked)
495
496 def testOverridingNestedConfigDict(self):
497 """Tests overriding of ConfigDict fields."""
498
499 config_flag = f'--test_config={_CONFIGDICT_CONFIG_FILE}'
500 values = _parse_flags(
501 f'./program {config_flag}'
502 ' --test_config.nested_configdict="{\\"a\\": True, \\"b\\": 123}"'
503 )
504 self.assertEqual(values.test_config.nested_configdict.a, True)
505 self.assertEqual(values.test_config.nested_configdict.b, 123)
506 self.assertEqual(
507 dict(values.test_config.nested_configdict.items()),
508 {'a': True, 'b': 123},
509 )
510
511 @parameterized.named_parameters(
512 ('WithTwoDashesAndEqual', '--test_config={}'.format(_TEST_DIRECTORY)),
513 ('WithTwoDashes', '--test_config {}'.format(_TEST_DIRECTORY)),
514 ('WithOneDashAndEqual', '-test_config={}'.format(_TEST_DIRECTORY)),
515 ('WithOneDash', '-test_config {}'.format(_TEST_DIRECTORY)))
516 def testPriorityOfFieldLookup(self, config_flag):
517 """Tests whether attributes have higher priority than key-based lookup."""
518
519 values = _parse_flags('./program {}/mini_config.py'.format(config_flag),
520 lock_config=False)
521 self.assertTrue(values.test_config.entry_with_collision)
522
523 @parameterized.named_parameters(
524 ('TypeAEnabled', ':type_a', {'thing_a': 23, 'thing_b': 42}, ['thing_c']),
525 ('TypeASpecify', ':type_a --test_config.thing_a=24', {'thing_a': 24}, []),
526 ('TypeBEnabled', ':type_b', {'thing_a': 19, 'thing_c': 65}, ['thing_b']))
527 def testExtraConfigString(self, flag_override, should_exist, should_error):
528 """Tests with the config_string argument is used properly."""
529 values = _parse_flags(
530 './program --test_config={}/parameterised_config.py{}'.format(
531 _TEST_DIRECTORY, flag_override))
532 # Ensure that the values exist in the ConfigDict, with desired values.
533 for subfield_name, expected_value in should_exist.items():
534 self.assertEqual(values.test_config[subfield_name], expected_value)
535
536 # Ensure the values which should not be part of the ConfigDict are really
537 # not there.
538 for should_error_name in should_error:
539 with self.assertRaisesRegex(KeyError, 'Did you mean'):
540 _ = values.test_config[should_error_name]
541
542 def testExtraConfigInvalidFlag(self):
543 with self.assertRaisesRegex(AttributeError, 'not_valid_item'):
544 _parse_flags(
545 ('./program --test_config={}/parameterised_config.py:type_a '
546 '--test_config.not_valid_item=42').format(_TEST_DIRECTORY))
547
548 def testOverridingConfigDict(self):
549 """Tests overriding of ConfigDict fields."""
550
551 config_flag = '--test_config={}'.format(_CONFIGDICT_CONFIG_FILE)
552 overrides = {
553 'integer': 2,
554 'reference': 2,
555 'list[0]': 5,
556 'nested_list[0][0]': 5,
557 'nested_configdict.integer': 5,
558 'unusable_config.valid_attribute': 5
559 }
560 override_flags = _get_override_flags(overrides, '--test_config.{}={}')
561 values = _parse_flags('./program {} {}'.format(config_flag, override_flags))
562 self.assertEqual(values.test_config.integer, overrides['integer'])
563 self.assertEqual(values.test_config.reference, overrides['reference'])
564 self.assertEqual(values.test_config.list[0], overrides['list[0]'])
565 self.assertEqual(values.test_config.nested_list[0][0],
566 overrides['nested_list[0][0]'])
567 self.assertEqual(values.test_config.nested_configdict.integer,
568 overrides['nested_configdict.integer'])
569 self.assertEqual(values.test_config.unusable_config.valid_attribute,
570 overrides['unusable_config.valid_attribute'])
571 # Attribute error.
572 overrides = {'nonexistent': 'value'}
573 with self.assertRaises(AttributeError):
574 override_flags = _get_override_flags(overrides, '--test_config.{}={}')
575 _parse_flags('./program {} {}'.format(config_flag, override_flags))
576
577 # "Did you mean" messages.
578 overrides = {'integre': 2}
579 with self.assertRaisesRegex(AttributeError, 'Did you.*integer.*'):
580 override_flags = _get_override_flags(overrides, '--test_config.{}={}')
581 _parse_flags('./program {} {}'.format(config_flag, override_flags))
582
583 overrides = {'referecne': 2}
584 with self.assertRaisesRegex(AttributeError, 'Did you.*reference.*'):
585 override_flags = _get_override_flags(overrides, '--test_config.{}={}')
586 _parse_flags('./program {} {}'.format(config_flag, override_flags))
587
588 @parameterized.parameters(
589 {'overrides': ('2,',), 'expected_tuple': (2,)},
590 {'overrides': ('2,3',), 'expected_tuple': (2, 3)},
591 {'overrides': ('(2,3)',), 'expected_tuple': (2, 3)},
592 {'overrides': ('2',), 'expected_tuple': (2,)},
593 {'overrides': ('2', '3',), 'expected_tuple': (2, 3)},
594 {'overrides': ('a',), 'expected_tuple': ('a',)},
595 {'overrides': ('"a"',), 'expected_tuple': ('a',)},
596 {'overrides': ('"a",',), 'expected_tuple': ('a',)},
597 {'overrides': ('("a",)',), 'expected_tuple': ('a',)},
598 {'overrides': ('a', 'b',), 'expected_tuple': ('a', 'b')},
599 {'overrides': ('("a","b")',), 'expected_tuple': ('a', 'b')},
600 )
601 def testOverridingMultiConfigDict(self, overrides, expected_tuple):
602 config_flag = '--test_config={}'.format(_TEST_CONFIG_FILE)
603 override_flags = ' '.join(
604 [f'--test_config.tuple={shlex.quote(value)}' for value in overrides])
605 values = _parse_flags('./program {} {}'.format(config_flag, override_flags))
606 self.assertEqual(values.test_config.tuple, expected_tuple)
607
608 # This test adds new flags, so use FlagSaver to make it hermetic.
609 @flagsaver.flagsaver
610 def testIsConfigFile(self):
611 config_flags.DEFINE_config_file('is_a_config_flag')
612 flags.DEFINE_integer('not_a_config_flag', -1, '')
613
614 self.assertTrue(
615 config_flags.is_config_flag(flags.FLAGS['is_a_config_flag']))
616 self.assertFalse(
617 config_flags.is_config_flag(flags.FLAGS['not_a_config_flag']))
618
619 # This test adds new flags, so use FlagSaver to make it hermetic.
620 @flagsaver.flagsaver
621 @pytest.mark.skip
622 def testModuleName(self):
623 config_flags.DEFINE_config_file('flag')
624 argv_0 = './program'
625 _parse_flags(argv_0)
626 self.assertIn(flags.FLAGS['flag'],
627 flags.FLAGS.flags_by_module_dict()[argv_0])
628
629 def testFlagOrder(self):
630 with self.assertRaisesWithLiteralMatch(
631 config_flags.FlagOrderError,
632 ('Found --test_config.int=1 in argv before a value for --test_config '
633 'was specified')):
634 _parse_flags('./program --test_config.int=1 '
635 '--test_config={}'.format(_TEST_CONFIG_FILE))
636
637 @flagsaver.flagsaver
638 def testOverrideValues(self):
639 config_flags.DEFINE_config_file('config')
640 with self.assertRaisesWithLiteralMatch(config_flags.UnparsedFlagError,
641 'The flag has not been parsed yet'):
642 flags.FLAGS['config'].override_values # pylint: disable=pointless-statement
643
644 original_float = -1.0
645 original_dictfloat = -2.0
646 config = config_dict.ConfigDict({
647 'integer': -1,
648 'float': original_float,
649 'dict': {
650 'float': original_dictfloat
651 }
652 })
653 integer_override = 0
654 dictfloat_override = 1.1
655 values = _parse_flags('./program --test_config={} --test_config.integer={} '
656 '--test_config.dict.float={}'.format(
657 _TEST_CONFIG_FILE, integer_override,
658 dictfloat_override))
659
660 config.update_from_flattened_dict(
661 config_flags.get_override_values(values['test_config']))
662 self.assertEqual(config['integer'], integer_override)
663 self.assertEqual(config['float'], original_float)
664 self.assertEqual(config['dict']['float'], dictfloat_override)
665
666 @parameterized.named_parameters(
667 ('ConfigFile1', _TEST_CONFIG_FILE),
668 ('ConfigFile2', _CONFIGDICT_CONFIG_FILE),
669 ('ParameterisedConfigFile', _PARAMETERISED_CONFIG_FILE + ':type_a'),
670 )
671 def testConfigPath(self, config_file):
672 """Test access to saved config file path."""
673 values = _parse_flags('./program --test_config={}'.format(config_file))
674 self.assertEqual(config_flags.get_config_filename(values['test_config']),
675 config_file)
676
677 def testLiteral(self):
678 """Test access to saved config file path."""
679 values = _parse_flags(
680 './program'
681 f' --test_config={_LITERAL_CONFIG_FILE}'
682 ' --test_config.integer=123'
683 ' --test_config.string="abc def"'
684 ' --test_config.nested="{\'a\': [1, 2, 3]}"'
685 ' --test_config.other_with_default_overitten=True'
686 )
687 cfg = values.test_config
688 self.assertEqual(cfg.integer, 123)
689 self.assertEqual(cfg.string, 'abc def')
690 self.assertEqual(cfg.nested, {'a': [1, 2, 3]})
691 self.assertEqual(cfg.other_with_default, 123)
692 self.assertEqual(cfg.other_with_default_overitten, True)
693
694 def testLiteralBool(self):
695 """Test access to saved config file path."""
696 values = _parse_flags(
697 './program'
698 f' --test_config={_LITERAL_CONFIG_FILE}'
699 ' --test_config.integer'
700 ' --test_config.nested=1'
701 ' --notest_config.string'
702 ' --test_config.other_with_default_overitten'
703 )
704 cfg = values.test_config
705 self.assertEqual(cfg.integer, True)
706 self.assertEqual(cfg.string, False)
707 self.assertEqual(cfg.nested, 1)
708 self.assertEqual(cfg.other_with_default_overitten, True)
709
710 def testNewAttributes(self):
711 values = _parse_flags(
712 './program'
713 f' --test_config={_LITERAL_CONFIG_FILE}'
714 ' --test_config.integer=123'
715 ' --test_config.other_new_value="abc def"'
716 ' --test_config.new_value="{\'a\': [1, 2, 3]}"',
717 accept_new_attributes=True,
718 lock_config=False,
719 )
720 cfg = values.test_config
721 self.assertEqual(cfg.integer, 123)
722 self.assertIsNone(cfg.string)
723 self.assertEqual(cfg.other_new_value, 'abc def')
724 self.assertEqual(cfg.new_value, config_dict.ConfigDict({'a': [1, 2, 3]}))
725
726
727 def _simple_config():
728 config = config_dict.ConfigDict()
729 config.foo = 3
730 return config
731
732
733 class ConfigDictFlagTest(_ConfigFlagTestCase, parameterized.TestCase):
734 """Tests DEFINE_config_dict.
735
736 DEFINE_config_dict reuses a lot of code in DEFINE_config_file so the tests
737 here are mostly sanity checks.
738 """
739
740 def testBasicUsage(self):
741 values = _parse_flags('./program', config=_simple_config())
742 self.assertIn('test_config', values)
743 self.assert_equal_configs(_simple_config(), values.test_config)
744
745 def testChangingLockedConfigRaisesAnError(self):
746 values = _parse_flags(
747 './program', config=_simple_config(), lock_config=True)
748 with self.assertRaisesRegex(AttributeError, 'config is locked'):
749 values.test_config.new_foo = 20
750
751 def testChangingUnlockedConfig(self):
752 values = _parse_flags(
753 './program', config=_simple_config(), lock_config=False)
754 values.test_config.new_foo = 20
755
756 def testNonConfigDictAsConfig(self):
757 non_config_dict = dict(a=1, b=2)
758 with self.assertRaisesRegex(TypeError, 'should be a ConfigDict'):
759 _parse_flags('./program', config=non_config_dict)
760
761 @parameterized.named_parameters(
762 ('GlobalSysArgvParsing', False),
763 ('SysArgvOverride', True))
764 def testOverridingAttribute(self, use_sys_argv_override):
765 new_foo = 10
766 values = _parse_flags(
767 './program --test_config.foo={}'.format(new_foo),
768 config=_simple_config(),
769 use_sys_argv_override=use_sys_argv_override)
770 self.assertNotEqual(new_foo, _simple_config().foo)
771 self.assertEqual(new_foo, values.test_config.foo)
772
773 def testOverridingMainConfigFlagRaisesAnError(self):
774 with self.assertRaisesRegex(flags.IllegalFlagValueError,
775 'Overriding test_config is not allowed'):
776 _parse_flags('./program --test_config=bad_input', config=_simple_config())
777
778 def testOverridesSerialize(self):
779 all_types_config = config_dict.ConfigDict()
780 all_types_config.type_bool = False
781 all_types_config.type_bytes = b'bytes'
782 all_types_config.type_float = 1.0
783 all_types_config.type_int = 1
784 all_types_config.type_str = 'str'
785 all_types_config.type_ustr = u'ustr'
786 all_types_config.type_tuple = (False, b'bbytes', 1.0, 1, 'str', u'ustr',)
787 # Change values via the command line:
788 command_line = (
789 './program'
790 ' --test_config.type_bool=True'
791 ' --test_config.type_float=10'
792 ' --test_config.type_int=10'
793 ' --test_config.type_str=str_commandline'
794 ' --test_config.type_tuple="(\'tuple_str\', 10)"'
795 )
796 command_line += ' --test_config.type_ustr=ustr_commandline'
797 values = _parse_flags(command_line, config=copy.copy(all_types_config))
798
799 # Check we get the expected values (ie the ones defined above not the ones
800 # defined in the config itself)
801 get_parser = lambda name: values._flags()[name].parser.parse
802 get_serializer = lambda name: values._flags()[name].serializer.serialize
803 serialize_parse = (
804 lambda name, value: get_parser(name)(get_serializer(name)(value)))
805
806 with self.subTest('bool'):
807 self.assertNotEqual(values.test_config.type_bool,
808 all_types_config['type_bool'])
809 self.assertEqual(values.test_config.type_bool, True)
810 self.assertEqual(values.test_config.type_bool,
811 serialize_parse('test_config.type_bool',
812 values.test_config.type_bool))
813 with self.subTest('float'):
814 self.assertNotEqual(values.test_config.type_float,
815 all_types_config['type_float'])
816 self.assertEqual(values.test_config.type_float, 10.)
817 self.assertEqual(values.test_config.type_float,
818 serialize_parse('test_config.type_float',
819 values.test_config.type_float))
820 with self.subTest('int'):
821 self.assertNotEqual(values.test_config.type_int,
822 all_types_config['type_int'])
823 self.assertEqual(values.test_config.type_int, 10)
824 self.assertEqual(values.test_config.type_int,
825 serialize_parse('test_config.type_int',
826 values.test_config.type_int))
827 with self.subTest('str'):
828 self.assertNotEqual(values.test_config.type_str,
829 all_types_config['type_str'])
830 self.assertEqual(values.test_config.type_str, 'str_commandline')
831 self.assertEqual(values.test_config.type_str,
832 serialize_parse('test_config.type_str',
833 values.test_config.type_str))
834
835 with self.subTest('ustr'):
836 self.assertNotEqual(values.test_config.type_ustr,
837 all_types_config['type_ustr'])
838 self.assertEqual(values.test_config.type_ustr, u'ustr_commandline')
839 self.assertEqual(
840 values.test_config.type_ustr,
841 serialize_parse('test_config.type_ustr',
842 values.test_config.type_ustr))
843 with self.subTest('tuple'):
844 self.assertNotEqual(values.test_config.type_tuple,
845 all_types_config['type_tuple'])
846 self.assertEqual(values.test_config.type_tuple, ('tuple_str', 10))
847 self.assertEqual(values.test_config.type_tuple,
848 serialize_parse('test_config.type_tuple',
849 values.test_config.type_tuple))
850
851 def testFlagfile(self):
852 config = config_dict.ConfigDict()
853 config.foo = 3
854 config.bar = 4
855
856 with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
857 f.write('--test_config.foo=7\n')
858 f.flush()
859 f.close()
860 values = _parse_flags(f'./program --flagfile={f.name}', config=config)
861 self.assertEqual(values.test_config.foo, 7)
862 self.assertEqual(values.test_config.bar, 4)
863
864
865 def main():
866 absltest.main()
867
868
869 if __name__ == '__main__':
870 main()