Fix sorting of optional arguments

When there are no positional arguments only N-1 arguments
were sorted. The original unit test covered this case, but
had no luck to catch the issue.

Closes bug 1466061

Change-Id: I54ac8d5b6b20dd42b6c49873e5b0000fe7b92057
This commit is contained in:
Ilya Shakhat 2015-06-17 13:55:07 +03:00
parent 81864be008
commit 40676e2c74
2 changed files with 19 additions and 2 deletions
oslo_config

@ -1718,10 +1718,13 @@ class _CachedArgumentParser(argparse.ArgumentParser):
# option and then sort the values slice.
for container, values in six.iteritems(self._args_cache):
index = 0
has_positional = False
for index, argument in enumerate(values):
if not argument['args'][0].startswith('-'):
has_positional = True
break
values[:index] = sorted(values[:index], key=lambda x: x['args'])
size = index if has_positional else len(values)
values[:size] = sorted(values[:size], key=lambda x: x['args'])
for argument in values:
try:
container.add_argument(*argument['args'],

@ -146,8 +146,8 @@ class HelpTestCase(BaseTestCase):
def test_print_sorted_help(self):
f = moves.StringIO()
self.conf.register_cli_opt(cfg.StrOpt('zba'))
self.conf.register_cli_opt(cfg.StrOpt('abc'))
self.conf.register_cli_opt(cfg.StrOpt('zba'))
self.conf.register_cli_opt(cfg.StrOpt('ghi'))
self.conf.register_cli_opt(cfg.StrOpt('deb'))
self.conf([])
@ -159,6 +159,20 @@ class HelpTestCase(BaseTestCase):
list = [abc, deb, ghi, zba]
self.assertEqual(sorted(list), list)
def test_print_sorted_help_with_positionals(self):
f = moves.StringIO()
self.conf.register_cli_opt(cfg.StrOpt('pst', positional=True))
self.conf.register_cli_opt(cfg.StrOpt('abc'))
self.conf.register_cli_opt(cfg.StrOpt('zba'))
self.conf.register_cli_opt(cfg.StrOpt('ghi'))
self.conf([])
self.conf.print_help(file=f)
zba = f.getvalue().find('--zba')
abc = f.getvalue().find('--abc')
ghi = f.getvalue().find('--ghi')
list = [abc, ghi, zba]
self.assertEqual(sorted(list), list)
class FindConfigFilesTestCase(BaseTestCase):