Skip to content
This repository was archived by the owner on Mar 23, 2023. It is now read-only.

Commit c0a76bc

Browse files
S-YOUtrotterdylan
authored andcommitted
Add unittest for argparse (#200)
1 parent 7016d5b commit c0a76bc

4 files changed

Lines changed: 4980 additions & 111 deletions

File tree

third_party/stdlib/argparse.py

Lines changed: 56 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@
8383

8484

8585
import collections as _collections
86-
import copy as _copy
86+
# import copy as _copy
8787
import os as _os
8888
import re as _re
8989
import sys as _sys
@@ -105,8 +105,11 @@ def dict_pop(d, k, default=None):
105105
if default:
106106
return default
107107

108-
def setattr(d, k, v):
109-
d.__dict__[k] = v
108+
def list_remove(l, x):
109+
for i in range(len(l)):
110+
if l[i] == x:
111+
l.pop(i)
112+
break
110113

111114
MAPPING_SUB = _re.compile(r'%\(([^)]+)\)s').sub
112115

@@ -314,7 +317,8 @@ def _format_usage(self, usage, actions, groups, prefix):
314317

315318
# if usage is specified, use that
316319
if usage is not None:
317-
usage = usage % dict(prog=self._prog)
320+
# usage = usage % dict(prog=self._prog)
321+
usage = usage.replace('%(prog)s', str(self._prog))
318322

319323
# if no optionals or positionals are available, usage is just prog
320324
elif usage is None and not actions:
@@ -417,7 +421,8 @@ def _format_actions_usage(self, actions, groups):
417421
if actions[i] == group._group_actions[0]:
418422
start = i
419423
break
420-
raise ValueError
424+
if start is None:
425+
raise ValueError
421426
except ValueError:
422427
continue
423428
else:
@@ -503,18 +508,21 @@ def _format_actions_usage(self, actions, groups):
503508
open_bracket = r'[\[(]'
504509
close = r'[\])]'
505510
# text = _re.sub(r'(%s) ' % open_bracket, r'\1', text)
511+
text = text.replace('[ ', '[').replace('( ', '(')
506512
# text = _re.sub(r' (%s)' % close, r'\1', text)
513+
text = text.replace(' ]', ']').replace(' )', ')')
507514
text = _re.sub(r'%s *%s' % (open_bracket, close), r'', text)
508515
# text = _re.sub(r'\(([^|]*)\)', r'\1', text)
516+
text = _re.sub(r'\(([^|]*)\)', lambda x: x.group(1), text)
509517
text = text.strip()
510518

511519
# return the text
512520
return text
513521

514522
def _format_text(self, text):
515-
if '%(prog)' in text:
523+
if '%(prog)s' in text:
516524
# text = text % dict(prog=self._prog)
517-
text = self._prog.join(text.split('$(prog)'))
525+
text = text.replace('%(prog)s', self._prog)
518526
text_width = max(self._width - self._current_indent, 11)
519527
indent = ' ' * self._current_indent
520528
return self._fill_text(text, text_width, indent) + '\n\n'
@@ -529,20 +537,20 @@ def _format_action(self, action):
529537

530538
# ho nelp; start on same line and add a final newline
531539
if not action.help:
532-
# tup = self._current_indent, '', action_header
540+
tup = self._current_indent, '', action_header
533541
# action_header = '%*s%s\n' % tup
534542
action_header = ' ' * self._current_indent + action_header + '\n'
535543

536544
# short action name; start on the same line and pad two spaces
537545
elif len(action_header) <= action_width:
538-
# tup = self._current_indent, '', action_width, action_header
546+
tup = self._current_indent, '', action_width, action_header
539547
# action_header = '%*s%-*s ' % tup
540-
action_header = ' ' * self._current_indent + (action_header + ' ' * action_width)[:10] + ' '
548+
action_header = ' ' * self._current_indent + (action_header + ' ' * action_width)[:action_width] + ' '
541549
indent_first = 0
542550

543551
# long action name; start on the next line
544552
else:
545-
# tup = self._current_indent, '', action_header
553+
tup = self._current_indent, '', action_header
546554
# action_header = '%*s%s\n' % tup
547555
action_header = ' ' * self._current_indent + action_header + '\n'
548556
indent_first = help_position
@@ -600,7 +608,8 @@ def _metavar_formatter(self, action, default_metavar):
600608
result = action.metavar
601609
elif action.choices is not None:
602610
choice_strs = [str(choice) for choice in action.choices]
603-
result = '{%s}' % ','.join(choice_strs)
611+
# result = '{%s}' % ','.join(choice_strs)
612+
result = '{%s}' % ','.join(sorted(choice_strs))
604613
else:
605614
result = default_metavar
606615

@@ -643,9 +652,9 @@ def _expand_help(self, action):
643652
choices_str = ', '.join([str(c) for c in params['choices']])
644653
params['choices'] = choices_str
645654
# return self._get_help_string(action) % params
646-
return MAPPING_SUB(lambda x: params.get(
647-
x.group(1), x.group(0)),
648-
self._get_help_string(action))
655+
return MAPPING_SUB(lambda x: str(params.get(
656+
x.group(1), x.group(0))),
657+
self._get_help_string(action)).replace('%%', '%')
649658

650659
def _iter_indented_subactions(self, action):
651660
try:
@@ -745,7 +754,7 @@ def __str__(self):
745754
format = 'argument %(argument_name)s: %(message)s'
746755
# return format % dict(message=self.message,
747756
# argument_name=self.argument_name)
748-
return self.argument_name.join(self.message.join(format.split('%(message)s')).split('%(argument_name)s'))
757+
return format.replace('%(message)s', str(self.message)).replace('%(argument_name)s', str(self.argument_name))
749758

750759

751760
class ArgumentTypeError(Exception):
@@ -972,7 +981,8 @@ def __init__(self,
972981
metavar=metavar)
973982

974983
def __call__(self, parser, namespace, values, option_string=None):
975-
items = _copy.copy(_ensure_value(namespace, self.dest, []))
984+
# items = _copy.copy(_ensure_value(namespace, self.dest, []))
985+
items = (_ensure_value(namespace, self.dest, []))[:]
976986
items.append(values)
977987
setattr(namespace, self.dest, items)
978988

@@ -998,7 +1008,8 @@ def __init__(self,
9981008
metavar=metavar)
9991009

10001010
def __call__(self, parser, namespace, values, option_string=None):
1001-
items = _copy.copy(_ensure_value(namespace, self.dest, []))
1011+
# items = _copy.copy(_ensure_value(namespace, self.dest, []))
1012+
items = (_ensure_value(namespace, self.dest, []))[:]
10021013
items.append(self.const)
10031014
setattr(namespace, self.dest, items)
10041015

@@ -1086,7 +1097,7 @@ def __init__(self,
10861097

10871098
self._prog_prefix = prog
10881099
self._parser_class = parser_class
1089-
self._name_parser_map = {} #_collections.OrderedDict()
1100+
self._name_parser_map = {} # _collections.OrderedDict()
10901101
self._choices_actions = []
10911102

10921103
super(_SubParsersAction, self).__init__(
@@ -1393,7 +1404,7 @@ def _add_action(self, action):
13931404

13941405
def _remove_action(self, action):
13951406
# self._actions.remove(action)
1396-
self._actions = [x for x in self._actions if x != action]
1407+
list_remove(self._actions, action)
13971408

13981409
def _add_container_actions(self, container):
13991410
# collect groups by titles
@@ -1482,8 +1493,7 @@ def _get_optional_kwargs(self, *args, **kwargs):
14821493
if not dest:
14831494
msg = _('dest= is required for options like %r')
14841495
raise ValueError(msg % option_string)
1485-
# dest = dest.replace('-', '_')
1486-
dest = '_'.join(dest.split('-'))
1496+
dest = dest.replace('-', '_')
14871497

14881498
# return the updated keyword arguments
14891499
return dict(kwargs, dest=dest, option_strings=option_strings)
@@ -1530,7 +1540,7 @@ def _handle_conflict_resolve(self, action, conflicting_actions):
15301540

15311541
# remove the conflicting option
15321542
# action.option_strings.remove(option_string)
1533-
action.options_strings = [x for x in action.option_strings if x != option_string]
1543+
list_remove(action.option_strings, option_string)
15341544
# self._option_string_actions.pop(option_string, None)
15351545
dict_pop(self._option_string_actions, option_string, None)
15361546

@@ -1631,13 +1641,13 @@ def __init__(self,
16311641
conflict_handler='error',
16321642
add_help=True):
16331643

1634-
if version is not None:
1635-
import warnings
1636-
warnings.warn(
1637-
"""The "version" argument to ArgumentParser is deprecated. """
1638-
"""Please use """
1639-
""""add_argument(..., action='version', version="N", ...)" """
1640-
"""instead""", DeprecationWarning)
1644+
# if version is not None:
1645+
# import warnings
1646+
# warnings.warn(
1647+
# """The "version" argument to ArgumentParser is deprecated. """
1648+
# """Please use """
1649+
# """"add_argument(..., action='version', version="N", ...)" """
1650+
# """instead""", DeprecationWarning)
16411651

16421652
superinit = super(ArgumentParser, self).__init__
16431653
superinit(description=description,
@@ -1801,7 +1811,8 @@ def parse_known_args(self, args=None, namespace=None):
18011811
if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
18021812
# args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
18031813
args += (getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
1804-
delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
1814+
# delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
1815+
del namespace.__dict__[_UNRECOGNIZED_ARGS_ATTR]
18051816
return namespace, args
18061817
except ArgumentError:
18071818
err = _sys.exc_info()[1]
@@ -1819,10 +1830,10 @@ def _parse_known_args(self, arg_strings, namespace):
18191830
group_actions = mutex_group._group_actions
18201831
for i, mutex_action in enumerate(mutex_group._group_actions):
18211832
# conflicts = action_conflicts.setdefault(mutex_action, [])
1822-
conflicts = setdefault(action_conflicts, mutex_action, [])
18231833
# conflicts.extend(group_actions[:i])
1824-
conflicts += (group_actions[:i])
18251834
# conflicts.extend(group_actions[i + 1:])
1835+
conflicts = setdefault(action_conflicts, mutex_action, [])
1836+
conflicts += (group_actions[:i])
18261837
conflicts += (group_actions[i + 1:])
18271838

18281839
# find all option indices, and determine the arg_string_pattern
@@ -2263,10 +2274,8 @@ def _get_nargs_pattern(self, action):
22632274

22642275
# if this is an optional action, -- is not allowed
22652276
if action.option_strings:
2266-
# nargs_pattern = nargs_pattern.replace('-*', '')
2267-
nargs_pattern = ''.join(nargs_pattern.split('-*'))
2268-
# nargs_pattern = nargs_pattern.replace('-', '')
2269-
nargs_pattern = ''.join(nargs_pattern.split('-'))
2277+
nargs_pattern = nargs_pattern.replace('-*', '')
2278+
nargs_pattern = nargs_pattern.replace('-', '')
22702279

22712280
# return the pattern
22722281
return nargs_pattern
@@ -2392,11 +2401,11 @@ def format_help(self):
23922401
return formatter.format_help()
23932402

23942403
def format_version(self):
2395-
import warnings
2396-
warnings.warn(
2397-
'The format_version method is deprecated -- the "version" '
2398-
'argument to ArgumentParser is no longer supported.',
2399-
DeprecationWarning)
2404+
# import warnings
2405+
# warnings.warn(
2406+
# 'The format_version method is deprecated -- the "version" '
2407+
# 'argument to ArgumentParser is no longer supported.',
2408+
# DeprecationWarning)
24002409
formatter = self._get_formatter()
24012410
formatter.add_text(self.version)
24022411
return formatter.format_help()
@@ -2418,11 +2427,11 @@ def print_help(self, file=None):
24182427
self._print_message(self.format_help(), file)
24192428

24202429
def print_version(self, file=None):
2421-
import warnings
2422-
warnings.warn(
2423-
'The print_version method is deprecated -- the "version" '
2424-
'argument to ArgumentParser is no longer supported.',
2425-
DeprecationWarning)
2430+
# import warnings
2431+
# warnings.warn(
2432+
# 'The print_version method is deprecated -- the "version" '
2433+
# 'argument to ArgumentParser is no longer supported.',
2434+
# DeprecationWarning)
24262435
self._print_message(self.format_version(), file)
24272436

24282437
def _print_message(self, message, file=None):

0 commit comments

Comments
 (0)