Coverage for /usr/local/lib/python3.7/site-packages/_pytest/config/argparsing.py : 19%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1import argparse
2import sys
3import warnings
4from gettext import gettext
5from typing import Any
6from typing import Dict
7from typing import List
8from typing import Optional
9from typing import Tuple
11import py
13from _pytest.config.exceptions import UsageError
15FILE_OR_DIR = "file_or_dir"
18class Parser:
19 """ Parser for command line arguments and ini-file values.
21 :ivar extra_info: dict of generic param -> value to display in case
22 there's an error processing the command line arguments.
23 """
25 prog = None
27 def __init__(self, usage=None, processopt=None):
28 self._anonymous = OptionGroup("custom options", parser=self)
29 self._groups = [] # type: List[OptionGroup]
30 self._processopt = processopt
31 self._usage = usage
32 self._inidict = {} # type: Dict[str, Tuple[str, Optional[str], Any]]
33 self._ininames = [] # type: List[str]
34 self.extra_info = {} # type: Dict[str, Any]
36 def processoption(self, option):
37 if self._processopt:
38 if option.dest:
39 self._processopt(option)
41 def getgroup(self, name, description="", after=None):
42 """ get (or create) a named option Group.
44 :name: name of the option group.
45 :description: long description for --help output.
46 :after: name of other group, used for ordering --help output.
48 The returned group object has an ``addoption`` method with the same
49 signature as :py:func:`parser.addoption
50 <_pytest.config.argparsing.Parser.addoption>` but will be shown in the
51 respective group in the output of ``pytest. --help``.
52 """
53 for group in self._groups:
54 if group.name == name:
55 return group
56 group = OptionGroup(name, description, parser=self)
57 i = 0
58 for i, grp in enumerate(self._groups):
59 if grp.name == after:
60 break
61 self._groups.insert(i + 1, group)
62 return group
64 def addoption(self, *opts, **attrs):
65 """ register a command line option.
67 :opts: option names, can be short or long options.
68 :attrs: same attributes which the ``add_option()`` function of the
69 `argparse library
70 <http://docs.python.org/2/library/argparse.html>`_
71 accepts.
73 After command line parsing options are available on the pytest config
74 object via ``config.option.NAME`` where ``NAME`` is usually set
75 by passing a ``dest`` attribute, for example
76 ``addoption("--long", dest="NAME", ...)``.
77 """
78 self._anonymous.addoption(*opts, **attrs)
80 def parse(self, args, namespace=None):
81 from _pytest._argcomplete import try_argcomplete
83 self.optparser = self._getparser()
84 try_argcomplete(self.optparser)
85 args = [str(x) if isinstance(x, py.path.local) else x for x in args]
86 return self.optparser.parse_args(args, namespace=namespace)
88 def _getparser(self) -> "MyOptionParser":
89 from _pytest._argcomplete import filescompleter
91 optparser = MyOptionParser(self, self.extra_info, prog=self.prog)
92 groups = self._groups + [self._anonymous]
93 for group in groups:
94 if group.options:
95 desc = group.description or group.name
96 arggroup = optparser.add_argument_group(desc)
97 for option in group.options:
98 n = option.names()
99 a = option.attrs()
100 arggroup.add_argument(*n, **a)
101 # bash like autocompletion for dirs (appending '/')
102 # Type ignored because typeshed doesn't know about argcomplete.
103 optparser.add_argument( # type: ignore
104 FILE_OR_DIR, nargs="*"
105 ).completer = filescompleter
106 return optparser
108 def parse_setoption(self, args, option, namespace=None):
109 parsedoption = self.parse(args, namespace=namespace)
110 for name, value in parsedoption.__dict__.items():
111 setattr(option, name, value)
112 return getattr(parsedoption, FILE_OR_DIR)
114 def parse_known_args(self, args, namespace=None) -> argparse.Namespace:
115 """parses and returns a namespace object with known arguments at this
116 point.
117 """
118 return self.parse_known_and_unknown_args(args, namespace=namespace)[0]
120 def parse_known_and_unknown_args(
121 self, args, namespace=None
122 ) -> Tuple[argparse.Namespace, List[str]]:
123 """parses and returns a namespace object with known arguments, and
124 the remaining arguments unknown at this point.
125 """
126 optparser = self._getparser()
127 args = [str(x) if isinstance(x, py.path.local) else x for x in args]
128 return optparser.parse_known_args(args, namespace=namespace)
130 def addini(self, name, help, type=None, default=None):
131 """ register an ini-file option.
133 :name: name of the ini-variable
134 :type: type of the variable, can be ``pathlist``, ``args``, ``linelist``
135 or ``bool``.
136 :default: default value if no ini-file option exists but is queried.
138 The value of ini-variables can be retrieved via a call to
139 :py:func:`config.getini(name) <_pytest.config.Config.getini>`.
140 """
141 assert type in (None, "pathlist", "args", "linelist", "bool")
142 self._inidict[name] = (help, type, default)
143 self._ininames.append(name)
146class ArgumentError(Exception):
147 """
148 Raised if an Argument instance is created with invalid or
149 inconsistent arguments.
150 """
152 def __init__(self, msg, option):
153 self.msg = msg
154 self.option_id = str(option)
156 def __str__(self):
157 if self.option_id:
158 return "option {}: {}".format(self.option_id, self.msg)
159 else:
160 return self.msg
163class Argument:
164 """class that mimics the necessary behaviour of optparse.Option
166 it's currently a least effort implementation
167 and ignoring choices and integer prefixes
168 https://docs.python.org/3/library/optparse.html#optparse-standard-option-types
169 """
171 _typ_map = {"int": int, "string": str, "float": float, "complex": complex}
173 def __init__(self, *names, **attrs):
174 """store parms in private vars for use in add_argument"""
175 self._attrs = attrs
176 self._short_opts = [] # type: List[str]
177 self._long_opts = [] # type: List[str]
178 self.dest = attrs.get("dest")
179 if "%default" in (attrs.get("help") or ""):
180 warnings.warn(
181 'pytest now uses argparse. "%default" should be'
182 ' changed to "%(default)s" ',
183 DeprecationWarning,
184 stacklevel=3,
185 )
186 try:
187 typ = attrs["type"]
188 except KeyError:
189 pass
190 else:
191 # this might raise a keyerror as well, don't want to catch that
192 if isinstance(typ, str):
193 if typ == "choice":
194 warnings.warn(
195 "`type` argument to addoption() is the string %r."
196 " For choices this is optional and can be omitted, "
197 " but when supplied should be a type (for example `str` or `int`)."
198 " (options: %s)" % (typ, names),
199 DeprecationWarning,
200 stacklevel=4,
201 )
202 # argparse expects a type here take it from
203 # the type of the first element
204 attrs["type"] = type(attrs["choices"][0])
205 else:
206 warnings.warn(
207 "`type` argument to addoption() is the string %r, "
208 " but when supplied should be a type (for example `str` or `int`)."
209 " (options: %s)" % (typ, names),
210 DeprecationWarning,
211 stacklevel=4,
212 )
213 attrs["type"] = Argument._typ_map[typ]
214 # used in test_parseopt -> test_parse_defaultgetter
215 self.type = attrs["type"]
216 else:
217 self.type = typ
218 try:
219 # attribute existence is tested in Config._processopt
220 self.default = attrs["default"]
221 except KeyError:
222 pass
223 self._set_opt_strings(names)
224 if not self.dest:
225 if self._long_opts:
226 self.dest = self._long_opts[0][2:].replace("-", "_")
227 else:
228 try:
229 self.dest = self._short_opts[0][1:]
230 except IndexError:
231 raise ArgumentError("need a long or short option", self)
233 def names(self):
234 return self._short_opts + self._long_opts
236 def attrs(self):
237 # update any attributes set by processopt
238 attrs = "default dest help".split()
239 if self.dest:
240 attrs.append(self.dest)
241 for attr in attrs:
242 try:
243 self._attrs[attr] = getattr(self, attr)
244 except AttributeError:
245 pass
246 if self._attrs.get("help"):
247 a = self._attrs["help"]
248 a = a.replace("%default", "%(default)s")
249 # a = a.replace('%prog', '%(prog)s')
250 self._attrs["help"] = a
251 return self._attrs
253 def _set_opt_strings(self, opts):
254 """directly from optparse
256 might not be necessary as this is passed to argparse later on"""
257 for opt in opts:
258 if len(opt) < 2:
259 raise ArgumentError(
260 "invalid option string %r: "
261 "must be at least two characters long" % opt,
262 self,
263 )
264 elif len(opt) == 2:
265 if not (opt[0] == "-" and opt[1] != "-"):
266 raise ArgumentError(
267 "invalid short option string %r: "
268 "must be of the form -x, (x any non-dash char)" % opt,
269 self,
270 )
271 self._short_opts.append(opt)
272 else:
273 if not (opt[0:2] == "--" and opt[2] != "-"):
274 raise ArgumentError(
275 "invalid long option string %r: "
276 "must start with --, followed by non-dash" % opt,
277 self,
278 )
279 self._long_opts.append(opt)
281 def __repr__(self) -> str:
282 args = [] # type: List[str]
283 if self._short_opts:
284 args += ["_short_opts: " + repr(self._short_opts)]
285 if self._long_opts:
286 args += ["_long_opts: " + repr(self._long_opts)]
287 args += ["dest: " + repr(self.dest)]
288 if hasattr(self, "type"):
289 args += ["type: " + repr(self.type)]
290 if hasattr(self, "default"):
291 args += ["default: " + repr(self.default)]
292 return "Argument({})".format(", ".join(args))
295class OptionGroup:
296 def __init__(self, name, description="", parser=None):
297 self.name = name
298 self.description = description
299 self.options = [] # type: List[Argument]
300 self.parser = parser
302 def addoption(self, *optnames, **attrs):
303 """ add an option to this group.
305 if a shortened version of a long option is specified it will
306 be suppressed in the help. addoption('--twowords', '--two-words')
307 results in help showing '--two-words' only, but --twowords gets
308 accepted **and** the automatic destination is in args.twowords
309 """
310 conflict = set(optnames).intersection(
311 name for opt in self.options for name in opt.names()
312 )
313 if conflict:
314 raise ValueError("option names %s already added" % conflict)
315 option = Argument(*optnames, **attrs)
316 self._addoption_instance(option, shortupper=False)
318 def _addoption(self, *optnames, **attrs):
319 option = Argument(*optnames, **attrs)
320 self._addoption_instance(option, shortupper=True)
322 def _addoption_instance(self, option, shortupper=False):
323 if not shortupper:
324 for opt in option._short_opts:
325 if opt[0] == "-" and opt[1].islower():
326 raise ValueError("lowercase shortoptions reserved")
327 if self.parser:
328 self.parser.processoption(option)
329 self.options.append(option)
332class MyOptionParser(argparse.ArgumentParser):
333 def __init__(self, parser, extra_info=None, prog=None):
334 if not extra_info:
335 extra_info = {}
336 self._parser = parser
337 argparse.ArgumentParser.__init__(
338 self,
339 prog=prog,
340 usage=parser._usage,
341 add_help=False,
342 formatter_class=DropShorterLongHelpFormatter,
343 allow_abbrev=False,
344 )
345 # extra_info is a dict of (param -> value) to display if there's
346 # an usage error to provide more contextual information to the user
347 self.extra_info = extra_info
349 def error(self, message):
350 """Transform argparse error message into UsageError."""
351 msg = "{}: error: {}".format(self.prog, message)
353 if hasattr(self._parser, "_config_source_hint"):
354 msg = "{} ({})".format(msg, self._parser._config_source_hint)
356 raise UsageError(self.format_usage() + msg)
358 def parse_args(self, args=None, namespace=None):
359 """allow splitting of positional arguments"""
360 args, argv = self.parse_known_args(args, namespace)
361 if argv:
362 for arg in argv:
363 if arg and arg[0] == "-":
364 lines = ["unrecognized arguments: %s" % (" ".join(argv))]
365 for k, v in sorted(self.extra_info.items()):
366 lines.append(" {}: {}".format(k, v))
367 self.error("\n".join(lines))
368 getattr(args, FILE_OR_DIR).extend(argv)
369 return args
371 if sys.version_info[:2] < (3, 9): # pragma: no cover
372 # Backport of https://github.com/python/cpython/pull/14316 so we can
373 # disable long --argument abbreviations without breaking short flags.
374 def _parse_optional(self, arg_string):
375 if not arg_string:
376 return None
377 if not arg_string[0] in self.prefix_chars:
378 return None
379 if arg_string in self._option_string_actions:
380 action = self._option_string_actions[arg_string]
381 return action, arg_string, None
382 if len(arg_string) == 1:
383 return None
384 if "=" in arg_string:
385 option_string, explicit_arg = arg_string.split("=", 1)
386 if option_string in self._option_string_actions:
387 action = self._option_string_actions[option_string]
388 return action, option_string, explicit_arg
389 if self.allow_abbrev or not arg_string.startswith("--"):
390 option_tuples = self._get_option_tuples(arg_string)
391 if len(option_tuples) > 1:
392 msg = gettext(
393 "ambiguous option: %(option)s could match %(matches)s"
394 )
395 options = ", ".join(option for _, option, _ in option_tuples)
396 self.error(msg % {"option": arg_string, "matches": options})
397 elif len(option_tuples) == 1:
398 (option_tuple,) = option_tuples
399 return option_tuple
400 if self._negative_number_matcher.match(arg_string):
401 if not self._has_negative_number_optionals:
402 return None
403 if " " in arg_string:
404 return None
405 return None, arg_string, None
408class DropShorterLongHelpFormatter(argparse.HelpFormatter):
409 """shorten help for long options that differ only in extra hyphens
411 - collapse **long** options that are the same except for extra hyphens
412 - special action attribute map_long_option allows suppressing additional
413 long options
414 - shortcut if there are only two options and one of them is a short one
415 - cache result on action object as this is called at least 2 times
416 """
418 def __init__(self, *args, **kwargs):
419 """Use more accurate terminal width via pylib."""
420 if "width" not in kwargs:
421 kwargs["width"] = py.io.get_terminal_width()
422 super().__init__(*args, **kwargs)
424 def _format_action_invocation(self, action):
425 orgstr = argparse.HelpFormatter._format_action_invocation(self, action)
426 if orgstr and orgstr[0] != "-": # only optional arguments
427 return orgstr
428 res = getattr(action, "_formatted_action_invocation", None)
429 if res:
430 return res
431 options = orgstr.split(", ")
432 if len(options) == 2 and (len(options[0]) == 2 or len(options[1]) == 2):
433 # a shortcut for '-h, --help' or '--abc', '-a'
434 action._formatted_action_invocation = orgstr
435 return orgstr
436 return_list = []
437 option_map = getattr(action, "map_long_option", {})
438 if option_map is None:
439 option_map = {}
440 short_long = {} # type: Dict[str, str]
441 for option in options:
442 if len(option) == 2 or option[2] == " ":
443 continue
444 if not option.startswith("--"):
445 raise ArgumentError(
446 'long optional argument without "--": [%s]' % (option), self
447 )
448 xxoption = option[2:]
449 if xxoption.split()[0] not in option_map:
450 shortened = xxoption.replace("-", "")
451 if shortened not in short_long or len(short_long[shortened]) < len(
452 xxoption
453 ):
454 short_long[shortened] = xxoption
455 # now short_long has been filled out to the longest with dashes
456 # **and** we keep the right option ordering from add_argument
457 for option in options:
458 if len(option) == 2 or option[2] == " ":
459 return_list.append(option)
460 if option[2:] == short_long.get(option.replace("-", "")):
461 return_list.append(option.replace(" ", "=", 1))
462 action._formatted_action_invocation = ", ".join(return_list)
463 return action._formatted_action_invocation