diff --git a/oslo_config/cfg.py b/oslo_config/cfg.py index 8f97af20..1c003ea5 100644 --- a/oslo_config/cfg.py +++ b/oslo_config/cfg.py @@ -1261,6 +1261,27 @@ class StrOpt(Opt): max_length=max_length), **kwargs) + def _get_choice_text(self, choice): + if choice is None: + return '' + elif choice == '': + return "''" + return six.text_type(choice) + + def _get_argparse_kwargs(self, group, **kwargs): + """Extends the base argparse keyword dict for the config dir option.""" + kwargs = super(StrOpt, self)._get_argparse_kwargs(group) + + if getattr(self.type, 'choices', None): + choices_text = ', '.join([self._get_choice_text(choice) + for choice in self.type.choices]) + if kwargs['help'] is not None: + kwargs['help'] += (' Allowed values: %s\n' % choices_text) + else: + kwargs['help'] = (' Allowed values: %s\n' % choices_text) + + return kwargs + class BoolOpt(Opt): diff --git a/oslo_config/tests/test_cfg.py b/oslo_config/tests/test_cfg.py index 4e236d04..a23e6b3e 100644 --- a/oslo_config/tests/test_cfg.py +++ b/oslo_config/tests/test_cfg.py @@ -167,6 +167,32 @@ class HelpTestCase(BaseTestCase): self.assertIn('optional', f.getvalue()) self.assertIn('-h, --help', f.getvalue()) + def test_print_strOpt_with_choices_help(self): + f = moves.StringIO() + cli_opts = [ + cfg.StrOpt('aa', short='a', default='xx', + choices=['xx', 'yy', 'zz'], + help='StrOpt with choices.'), + cfg.StrOpt('bb', short='b', default='yy', + choices=[None, 'yy', 'zz'], + help='StrOpt with choices.'), + cfg.StrOpt('cc', short='c', default='zz', + choices=['', 'yy', 'zz'], + help='StrOpt with choices.'), + ] + self.conf.register_cli_opts(cli_opts) + self.conf([]) + self.conf.print_help(file=f) + self.assertIn('usage: test FOO BAR', f.getvalue()) + self.assertIn('optional', f.getvalue()) + self.assertIn('-h, --help', f.getvalue()) + self.assertIn('StrOpt with choices. Allowed values: xx, yy, zz', + f.getvalue()) + self.assertIn('StrOpt with choices. Allowed values: , yy, zz', + f.getvalue()) + self.assertIn("StrOpt with choices. Allowed values: '', yy, zz", + f.getvalue()) + def test_print_sorted_help(self): f = moves.StringIO() self.conf.register_cli_opt(cfg.StrOpt('abc'))