Ejemplo n.º 1
0
class AppConstantsTest(parameterized.TestCase, absltest.TestCase):
    def test_get_default_constants(self):
        constants = app_constants.get_default_constants()
        self.assertLen(constants, 7)

    @flagsaver.flagsaver(app_constants_test_flag='valid')
    def test_get_constants_from_flags(self):
        constants = app_constants.get_constants_from_flags(module=__name__)
        self.assertLen(constants, 1)
        self.assertEqual('valid', constants['app_constants_test_flag'].value)

    def test_get_constants_from_flags__not_parsed(self):
        FLAGS.__dict__['__flags_parsed'] = False
        constants = app_constants.get_constants_from_flags(module=__name__)
        FLAGS.__dict__['__flags_parsed'] = True
        self.assertLen(constants, 1)
        self.assertEqual('', constants['app_constants_test_flag'].value)

    @parameterized.parameters(
        ('DEFAULT', None, 'new', 'new'),
        ('', utils.StringParser(True), '', ''),
        ('yes', utils.YesNoParser(), 'no', False),
        ('', utils.ListParser(True), 'this,one', ['this', 'one']),
        ('', utils.StringParser(False), 'asdf', 'asdf'),
        ('1', flags.IntegerParser(), '10', 10),
        ('*****@*****.**', utils.EmailParser(), '*****@*****.**', '*****@*****.**'),
    )
    def test_constant_constructor(self, default, parser, new_value, expected):
        test_constant = app_constants.Constant('name', 'message', default,
                                               parser)
        self.assertEqual('name: {}'.format(default), str(test_constant))
        self.assertEqual(
            "<Constant('name', 'message', {!r}, {!r})>".format(
                default, parser), repr(test_constant))
        self.assertEqual(
            app_constants.Constant('name', 'message', default, parser),
            test_constant)
        self.assertNotEqual(
            app_constants.Constant('other', 'message', default, parser),
            test_constant)
        test_constant.value = new_value
        self.assertTrue(test_constant.valid)
        self.assertEqual(test_constant.value, expected)

    def test_constant_prompt(self):
        test_constant = app_constants.Constant('name', 'messsage', '',
                                               utils.StringParser(False))
        self.assertFalse(test_constant.valid)
        with mock.patch.object(utils, 'prompt', return_value='VALID!'):
            test_constant.prompt()
            self.assertTrue(test_constant.valid)
Ejemplo n.º 2
0
def prompt_int(message, minimum=None, maximum=None, **kwargs):
  """Prompts the user for an integer.

  Args:
    message: str, the info message to display before prompting for user input.
    minimum: int, the minimum accepted value.
    maximum: int, the maximum accepted value.
    **kwargs: keyword arguments to be passed to prompt.

  Returns:
    A user provided int.
  """
  parser = flags.IntegerParser(lower_bound=minimum, upper_bound=maximum)
  return prompt(message, parser=parser, **kwargs)
    def testParserWrapping(self):
        """Tests callback based Parser wrapping."""

        parser = flags.IntegerParser()

        test_config = mock_config.get_config()
        overrides = {}

        wrapped_parser = config_flags._ConfigFieldParser(
            parser, 'integer', test_config, overrides)

        wrapped_parser.parse('12321')
        self.assertEqual(test_config.integer, 12321)
        self.assertEqual(overrides, {'integer': 12321})

        self.assertEqual(wrapped_parser.flag_type(), parser.flag_type())
        self.assertEqual(wrapped_parser.syntactic_help, parser.syntactic_help)

        self.assertEqual(wrapped_parser.convert('3'), parser.convert('3'))
Ejemplo n.º 4
0
#     types.StringType: flags.ArgumentParser(),
#     types.TupleType: tuple_parser.TupleParser(),  # OK For Python 3
# }
# The possible breaking changes are:
# - A Python 3 int could be a Python 2 long, which was not previously supported.
#   We then add support for long.
# - Only Python 2 str were supported (not unicode). Python 3 will behave the
#   same with the str semantic change.
_FIELD_TYPE_TO_PARSER = {
    float: flags.FloatParser(),
    bool: flags.BooleanParser(),
    # Implementing a custom parser to override `Tuple` arguments.
    tuple: tuple_parser.TupleParser(),
}
for t in six.integer_types:
    _FIELD_TYPE_TO_PARSER[t] = flags.IntegerParser()
for t in six.string_types:
    _FIELD_TYPE_TO_PARSER[t] = flags.ArgumentParser()
_FIELD_TYPE_TO_PARSER[str] = flags.ArgumentParser()
_FIELD_TYPE_TO_SERIALIZER = {
    t: flags.ArgumentSerializer()
    for t in _FIELD_TYPE_TO_PARSER
}


class UnsupportedOperationError(flags.Error):
    pass


class FlagOrderError(flags.Error):
    pass
 def __init__(self, *args, **kwargs):
     super(_VerbosityFlag, self).__init__(flags.IntegerParser(),
                                          flags.ArgumentSerializer(), *args,
                                          **kwargs)
Ejemplo n.º 6
0
 def __init__(self, default, help_string):
     super().__init__(default, help_string, flags.IntegerParser())
Ejemplo n.º 7
0
FLAGS = flags.FLAGS

# Forward for backwards compatability.
GetValue = config_path.get_value
GetType = config_path.get_type
SetValue = config_path.set_value

# Prevent this module being considered for `FLAGS.find_module_defining_flag`.
flags._helpers.disclaim_module_ids.add(id(sys.modules[__name__]))  # pylint: disable=protected-access

_FIELD_TYPE_TO_PARSER = {
    float: flags.FloatParser(),
    bool: flags.BooleanParser(),
    tuple: tuple_parser.TupleParser(),
    int: flags.IntegerParser(),
    str: flags.ArgumentParser()
}

_FIELD_TYPE_TO_SERIALIZER = {
    t: flags.ArgumentSerializer()
    for t in _FIELD_TYPE_TO_PARSER
}


class UnsupportedOperationError(flags.Error):
  pass


class FlagOrderError(flags.Error):
  pass
Ejemplo n.º 8
0
 def __init__(
     self,
     default: Optional[int],
     help_string: Optional[str] = None,
 ):
     super().__init__(default, help_string, flags.IntegerParser())