Commit c0a76bc2 authored by YOU's avatar YOU Committed by Dylan Trotter

Add unittest for argparse (#200)

parent 7016d5b5
...@@ -83,7 +83,7 @@ __all__ = [ ...@@ -83,7 +83,7 @@ __all__ = [
import collections as _collections import collections as _collections
import copy as _copy # import copy as _copy
import os as _os import os as _os
import re as _re import re as _re
import sys as _sys import sys as _sys
...@@ -105,8 +105,11 @@ def dict_pop(d, k, default=None): ...@@ -105,8 +105,11 @@ def dict_pop(d, k, default=None):
if default: if default:
return default return default
def setattr(d, k, v): def list_remove(l, x):
d.__dict__[k] = v for i in range(len(l)):
if l[i] == x:
l.pop(i)
break
MAPPING_SUB = _re.compile(r'%\(([^)]+)\)s').sub MAPPING_SUB = _re.compile(r'%\(([^)]+)\)s').sub
...@@ -314,7 +317,8 @@ class HelpFormatter(object): ...@@ -314,7 +317,8 @@ class HelpFormatter(object):
# if usage is specified, use that # if usage is specified, use that
if usage is not None: if usage is not None:
usage = usage % dict(prog=self._prog) # usage = usage % dict(prog=self._prog)
usage = usage.replace('%(prog)s', str(self._prog))
# if no optionals or positionals are available, usage is just prog # if no optionals or positionals are available, usage is just prog
elif usage is None and not actions: elif usage is None and not actions:
...@@ -417,6 +421,7 @@ class HelpFormatter(object): ...@@ -417,6 +421,7 @@ class HelpFormatter(object):
if actions[i] == group._group_actions[0]: if actions[i] == group._group_actions[0]:
start = i start = i
break break
if start is None:
raise ValueError raise ValueError
except ValueError: except ValueError:
continue continue
...@@ -503,18 +508,21 @@ class HelpFormatter(object): ...@@ -503,18 +508,21 @@ class HelpFormatter(object):
open_bracket = r'[\[(]' open_bracket = r'[\[(]'
close = r'[\])]' close = r'[\])]'
# text = _re.sub(r'(%s) ' % open_bracket, r'\1', text) # text = _re.sub(r'(%s) ' % open_bracket, r'\1', text)
text = text.replace('[ ', '[').replace('( ', '(')
# text = _re.sub(r' (%s)' % close, r'\1', text) # text = _re.sub(r' (%s)' % close, r'\1', text)
text = text.replace(' ]', ']').replace(' )', ')')
text = _re.sub(r'%s *%s' % (open_bracket, close), r'', text) text = _re.sub(r'%s *%s' % (open_bracket, close), r'', text)
# text = _re.sub(r'\(([^|]*)\)', r'\1', text) # text = _re.sub(r'\(([^|]*)\)', r'\1', text)
text = _re.sub(r'\(([^|]*)\)', lambda x: x.group(1), text)
text = text.strip() text = text.strip()
# return the text # return the text
return text return text
def _format_text(self, text): def _format_text(self, text):
if '%(prog)' in text: if '%(prog)s' in text:
# text = text % dict(prog=self._prog) # text = text % dict(prog=self._prog)
text = self._prog.join(text.split('$(prog)')) text = text.replace('%(prog)s', self._prog)
text_width = max(self._width - self._current_indent, 11) text_width = max(self._width - self._current_indent, 11)
indent = ' ' * self._current_indent indent = ' ' * self._current_indent
return self._fill_text(text, text_width, indent) + '\n\n' return self._fill_text(text, text_width, indent) + '\n\n'
...@@ -529,20 +537,20 @@ class HelpFormatter(object): ...@@ -529,20 +537,20 @@ class HelpFormatter(object):
# ho nelp; start on same line and add a final newline # ho nelp; start on same line and add a final newline
if not action.help: if not action.help:
# tup = self._current_indent, '', action_header tup = self._current_indent, '', action_header
# action_header = '%*s%s\n' % tup # action_header = '%*s%s\n' % tup
action_header = ' ' * self._current_indent + action_header + '\n' action_header = ' ' * self._current_indent + action_header + '\n'
# short action name; start on the same line and pad two spaces # short action name; start on the same line and pad two spaces
elif len(action_header) <= action_width: elif len(action_header) <= action_width:
# tup = self._current_indent, '', action_width, action_header tup = self._current_indent, '', action_width, action_header
# action_header = '%*s%-*s ' % tup # action_header = '%*s%-*s ' % tup
action_header = ' ' * self._current_indent + (action_header + ' ' * action_width)[:10] + ' ' action_header = ' ' * self._current_indent + (action_header + ' ' * action_width)[:action_width] + ' '
indent_first = 0 indent_first = 0
# long action name; start on the next line # long action name; start on the next line
else: else:
# tup = self._current_indent, '', action_header tup = self._current_indent, '', action_header
# action_header = '%*s%s\n' % tup # action_header = '%*s%s\n' % tup
action_header = ' ' * self._current_indent + action_header + '\n' action_header = ' ' * self._current_indent + action_header + '\n'
indent_first = help_position indent_first = help_position
...@@ -600,7 +608,8 @@ class HelpFormatter(object): ...@@ -600,7 +608,8 @@ class HelpFormatter(object):
result = action.metavar result = action.metavar
elif action.choices is not None: elif action.choices is not None:
choice_strs = [str(choice) for choice in action.choices] choice_strs = [str(choice) for choice in action.choices]
result = '{%s}' % ','.join(choice_strs) # result = '{%s}' % ','.join(choice_strs)
result = '{%s}' % ','.join(sorted(choice_strs))
else: else:
result = default_metavar result = default_metavar
...@@ -643,9 +652,9 @@ class HelpFormatter(object): ...@@ -643,9 +652,9 @@ class HelpFormatter(object):
choices_str = ', '.join([str(c) for c in params['choices']]) choices_str = ', '.join([str(c) for c in params['choices']])
params['choices'] = choices_str params['choices'] = choices_str
# return self._get_help_string(action) % params # return self._get_help_string(action) % params
return MAPPING_SUB(lambda x: params.get( return MAPPING_SUB(lambda x: str(params.get(
x.group(1), x.group(0)), x.group(1), x.group(0))),
self._get_help_string(action)) self._get_help_string(action)).replace('%%', '%')
def _iter_indented_subactions(self, action): def _iter_indented_subactions(self, action):
try: try:
...@@ -745,7 +754,7 @@ class ArgumentError(Exception): ...@@ -745,7 +754,7 @@ class ArgumentError(Exception):
format = 'argument %(argument_name)s: %(message)s' format = 'argument %(argument_name)s: %(message)s'
# return format % dict(message=self.message, # return format % dict(message=self.message,
# argument_name=self.argument_name) # argument_name=self.argument_name)
return self.argument_name.join(self.message.join(format.split('%(message)s')).split('%(argument_name)s')) return format.replace('%(message)s', str(self.message)).replace('%(argument_name)s', str(self.argument_name))
class ArgumentTypeError(Exception): class ArgumentTypeError(Exception):
...@@ -972,7 +981,8 @@ class _AppendAction(Action): ...@@ -972,7 +981,8 @@ class _AppendAction(Action):
metavar=metavar) metavar=metavar)
def __call__(self, parser, namespace, values, option_string=None): def __call__(self, parser, namespace, values, option_string=None):
items = _copy.copy(_ensure_value(namespace, self.dest, [])) # items = _copy.copy(_ensure_value(namespace, self.dest, []))
items = (_ensure_value(namespace, self.dest, []))[:]
items.append(values) items.append(values)
setattr(namespace, self.dest, items) setattr(namespace, self.dest, items)
...@@ -998,7 +1008,8 @@ class _AppendConstAction(Action): ...@@ -998,7 +1008,8 @@ class _AppendConstAction(Action):
metavar=metavar) metavar=metavar)
def __call__(self, parser, namespace, values, option_string=None): def __call__(self, parser, namespace, values, option_string=None):
items = _copy.copy(_ensure_value(namespace, self.dest, [])) # items = _copy.copy(_ensure_value(namespace, self.dest, []))
items = (_ensure_value(namespace, self.dest, []))[:]
items.append(self.const) items.append(self.const)
setattr(namespace, self.dest, items) setattr(namespace, self.dest, items)
...@@ -1086,7 +1097,7 @@ class _SubParsersAction(Action): ...@@ -1086,7 +1097,7 @@ class _SubParsersAction(Action):
self._prog_prefix = prog self._prog_prefix = prog
self._parser_class = parser_class self._parser_class = parser_class
self._name_parser_map = {} #_collections.OrderedDict() self._name_parser_map = {} # _collections.OrderedDict()
self._choices_actions = [] self._choices_actions = []
super(_SubParsersAction, self).__init__( super(_SubParsersAction, self).__init__(
...@@ -1393,7 +1404,7 @@ class _ActionsContainer(object): ...@@ -1393,7 +1404,7 @@ class _ActionsContainer(object):
def _remove_action(self, action): def _remove_action(self, action):
# self._actions.remove(action) # self._actions.remove(action)
self._actions = [x for x in self._actions if x != action] list_remove(self._actions, action)
def _add_container_actions(self, container): def _add_container_actions(self, container):
# collect groups by titles # collect groups by titles
...@@ -1482,8 +1493,7 @@ class _ActionsContainer(object): ...@@ -1482,8 +1493,7 @@ class _ActionsContainer(object):
if not dest: if not dest:
msg = _('dest= is required for options like %r') msg = _('dest= is required for options like %r')
raise ValueError(msg % option_string) raise ValueError(msg % option_string)
# dest = dest.replace('-', '_') dest = dest.replace('-', '_')
dest = '_'.join(dest.split('-'))
# return the updated keyword arguments # return the updated keyword arguments
return dict(kwargs, dest=dest, option_strings=option_strings) return dict(kwargs, dest=dest, option_strings=option_strings)
...@@ -1530,7 +1540,7 @@ class _ActionsContainer(object): ...@@ -1530,7 +1540,7 @@ class _ActionsContainer(object):
# remove the conflicting option # remove the conflicting option
# action.option_strings.remove(option_string) # action.option_strings.remove(option_string)
action.options_strings = [x for x in action.option_strings if x != option_string] list_remove(action.option_strings, option_string)
# self._option_string_actions.pop(option_string, None) # self._option_string_actions.pop(option_string, None)
dict_pop(self._option_string_actions, option_string, None) dict_pop(self._option_string_actions, option_string, None)
...@@ -1631,13 +1641,13 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): ...@@ -1631,13 +1641,13 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
conflict_handler='error', conflict_handler='error',
add_help=True): add_help=True):
if version is not None: # if version is not None:
import warnings # import warnings
warnings.warn( # warnings.warn(
"""The "version" argument to ArgumentParser is deprecated. """ # """The "version" argument to ArgumentParser is deprecated. """
"""Please use """ # """Please use """
""""add_argument(..., action='version', version="N", ...)" """ # """"add_argument(..., action='version', version="N", ...)" """
"""instead""", DeprecationWarning) # """instead""", DeprecationWarning)
superinit = super(ArgumentParser, self).__init__ superinit = super(ArgumentParser, self).__init__
superinit(description=description, superinit(description=description,
...@@ -1801,7 +1811,8 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): ...@@ -1801,7 +1811,8 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR): if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
# args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) # args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
args += (getattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) args += (getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
delattr(namespace, _UNRECOGNIZED_ARGS_ATTR) # delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
del namespace.__dict__[_UNRECOGNIZED_ARGS_ATTR]
return namespace, args return namespace, args
except ArgumentError: except ArgumentError:
err = _sys.exc_info()[1] err = _sys.exc_info()[1]
...@@ -1819,10 +1830,10 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): ...@@ -1819,10 +1830,10 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
group_actions = mutex_group._group_actions group_actions = mutex_group._group_actions
for i, mutex_action in enumerate(mutex_group._group_actions): for i, mutex_action in enumerate(mutex_group._group_actions):
# conflicts = action_conflicts.setdefault(mutex_action, []) # conflicts = action_conflicts.setdefault(mutex_action, [])
conflicts = setdefault(action_conflicts, mutex_action, [])
# conflicts.extend(group_actions[:i]) # conflicts.extend(group_actions[:i])
conflicts += (group_actions[:i])
# conflicts.extend(group_actions[i + 1:]) # conflicts.extend(group_actions[i + 1:])
conflicts = setdefault(action_conflicts, mutex_action, [])
conflicts += (group_actions[:i])
conflicts += (group_actions[i + 1:]) conflicts += (group_actions[i + 1:])
# find all option indices, and determine the arg_string_pattern # find all option indices, and determine the arg_string_pattern
...@@ -2263,10 +2274,8 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): ...@@ -2263,10 +2274,8 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
# if this is an optional action, -- is not allowed # if this is an optional action, -- is not allowed
if action.option_strings: if action.option_strings:
# nargs_pattern = nargs_pattern.replace('-*', '') nargs_pattern = nargs_pattern.replace('-*', '')
nargs_pattern = ''.join(nargs_pattern.split('-*')) nargs_pattern = nargs_pattern.replace('-', '')
# nargs_pattern = nargs_pattern.replace('-', '')
nargs_pattern = ''.join(nargs_pattern.split('-'))
# return the pattern # return the pattern
return nargs_pattern return nargs_pattern
...@@ -2392,11 +2401,11 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): ...@@ -2392,11 +2401,11 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
return formatter.format_help() return formatter.format_help()
def format_version(self): def format_version(self):
import warnings # import warnings
warnings.warn( # warnings.warn(
'The format_version method is deprecated -- the "version" ' # 'The format_version method is deprecated -- the "version" '
'argument to ArgumentParser is no longer supported.', # 'argument to ArgumentParser is no longer supported.',
DeprecationWarning) # DeprecationWarning)
formatter = self._get_formatter() formatter = self._get_formatter()
formatter.add_text(self.version) formatter.add_text(self.version)
return formatter.format_help() return formatter.format_help()
...@@ -2418,11 +2427,11 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): ...@@ -2418,11 +2427,11 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
self._print_message(self.format_help(), file) self._print_message(self.format_help(), file)
def print_version(self, file=None): def print_version(self, file=None):
import warnings # import warnings
warnings.warn( # warnings.warn(
'The print_version method is deprecated -- the "version" ' # 'The print_version method is deprecated -- the "version" '
'argument to ArgumentParser is no longer supported.', # 'argument to ArgumentParser is no longer supported.',
DeprecationWarning) # DeprecationWarning)
self._print_message(self.format_version(), file) self._print_message(self.format_version(), file)
def _print_message(self, message, file=None): def _print_message(self, message, file=None):
......
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -9,13 +9,13 @@ import contextlib ...@@ -9,13 +9,13 @@ import contextlib
# import gc # import gc
# import socket # import socket
import sys import sys
# import os import os
# import platform # import platform
# import shutil # import shutil
import warnings import warnings
import unittest import unittest
# import importlib # import importlib
# import UserDict import UserDict
# import re # import re
# import time # import time
# import struct # import struct
...@@ -27,7 +27,8 @@ import unittest ...@@ -27,7 +27,8 @@ import unittest
__all__ = [ __all__ = [
"Error", "TestFailed", "have_unicode", "BasicTestRunner", "run_unittest", "Error", "TestFailed", "have_unicode", "BasicTestRunner", "run_unittest",
"check_warnings", "check_py3k_warnings" "check_warnings", "check_py3k_warnings", "CleanImport",
"EnvironmentVarGuard"
] ]
# __all__ = ["Error", "TestFailed", "ResourceDenied", "import_module", # __all__ = ["Error", "TestFailed", "ResourceDenied", "import_module",
...@@ -927,83 +928,83 @@ def check_py3k_warnings(*filters, **kwargs): ...@@ -927,83 +928,83 @@ def check_py3k_warnings(*filters, **kwargs):
return _filterwarnings(filters, kwargs.get('quiet')) return _filterwarnings(filters, kwargs.get('quiet'))
# class CleanImport(object): class CleanImport(object):
# """Context manager to force import to return a new module reference. """Context manager to force import to return a new module reference.
# This is useful for testing module-level behaviours, such as This is useful for testing module-level behaviours, such as
# the emission of a DeprecationWarning on import. the emission of a DeprecationWarning on import.
# Use like this: Use like this:
# with CleanImport("foo"): with CleanImport("foo"):
# importlib.import_module("foo") # new reference importlib.import_module("foo") # new reference
# """ """
# def __init__(self, *module_names): def __init__(self, *module_names):
# self.original_modules = sys.modules.copy() self.original_modules = sys.modules.copy()
# for module_name in module_names: for module_name in module_names:
# if module_name in sys.modules: if module_name in sys.modules:
# module = sys.modules[module_name] module = sys.modules[module_name]
# # It is possible that module_name is just an alias for # It is possible that module_name is just an alias for
# # another module (e.g. stub for modules renamed in 3.x). # another module (e.g. stub for modules renamed in 3.x).
# # In that case, we also need delete the real module to clear # In that case, we also need delete the real module to clear
# # the import cache. # the import cache.
# if module.__name__ != module_name: if module.__name__ != module_name:
# del sys.modules[module.__name__] del sys.modules[module.__name__]
# del sys.modules[module_name] del sys.modules[module_name]
# def __enter__(self): def __enter__(self):
# return self return self
# def __exit__(self, *ignore_exc): def __exit__(self, *ignore_exc):
# sys.modules.update(self.original_modules) sys.modules.update(self.original_modules)
# class EnvironmentVarGuard(UserDict.DictMixin): class EnvironmentVarGuard(UserDict.DictMixin):
# """Class to help protect the environment variable properly. Can be used as """Class to help protect the environment variable properly. Can be used as
# a context manager.""" a context manager."""
# def __init__(self): def __init__(self):
# self._environ = os.environ self._environ = os.environ
# self._changed = {} self._changed = {}
# def __getitem__(self, envvar): def __getitem__(self, envvar):
# return self._environ[envvar] return self._environ[envvar]
# def __setitem__(self, envvar, value): def __setitem__(self, envvar, value):
# # Remember the initial value on the first access # Remember the initial value on the first access
# if envvar not in self._changed: if envvar not in self._changed:
# self._changed[envvar] = self._environ.get(envvar) self._changed[envvar] = self._environ.get(envvar)
# self._environ[envvar] = value self._environ[envvar] = value
# def __delitem__(self, envvar): def __delitem__(self, envvar):
# # Remember the initial value on the first access # Remember the initial value on the first access
# if envvar not in self._changed: if envvar not in self._changed:
# self._changed[envvar] = self._environ.get(envvar) self._changed[envvar] = self._environ.get(envvar)
# if envvar in self._environ: if envvar in self._environ:
# del self._environ[envvar] del self._environ[envvar]
# def keys(self): def keys(self):
# return self._environ.keys() return self._environ.keys()
# def set(self, envvar, value): def set(self, envvar, value):
# self[envvar] = value self[envvar] = value
# def unset(self, envvar): def unset(self, envvar):
# del self[envvar] del self[envvar]
# def __enter__(self): def __enter__(self):
# return self return self
# def __exit__(self, *ignore_exc): def __exit__(self, *ignore_exc):
# for (k, v) in self._changed.items(): for (k, v) in self._changed.items():
# if v is None: if v is None:
# if k in self._environ: if k in self._environ:
# del self._environ[k] del self._environ[k]
# else: else:
# self._environ[k] = v self._environ[k] = v
# os.environ = self._environ os.environ = self._environ
# class DirsOnSysPath(object): # class DirsOnSysPath(object):
......
# TODO: support signal # TODO: support signal
# import signal # import signal
import weakref # import weakref
# from functools import wraps # from functools import wraps
import functools import functools
...@@ -43,7 +43,8 @@ class _InterruptHandler(object): ...@@ -43,7 +43,8 @@ class _InterruptHandler(object):
# for result in _results.keys(): # for result in _results.keys():
# result.stop() # result.stop()
_results = weakref.WeakKeyDictionary() # _results = weakref.WeakKeyDictionary()
_results = {}
def registerResult(result): def registerResult(result):
_results[result] = 1 _results[result] = 1
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment