You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

523 lines
20KB

  1. import argparse
  2. import sys
  3. import warnings
  4. from gettext import gettext
  5. from typing import Any
  6. from typing import Callable
  7. from typing import cast
  8. from typing import Dict
  9. from typing import List
  10. from typing import Mapping
  11. from typing import Optional
  12. from typing import Sequence
  13. from typing import Tuple
  14. from typing import TYPE_CHECKING
  15. from typing import Union
  16. import py
  17. import _pytest._io
  18. from _pytest.compat import final
  19. from _pytest.config.exceptions import UsageError
  20. if TYPE_CHECKING:
  21. from typing import NoReturn
  22. from typing_extensions import Literal
  23. FILE_OR_DIR = "file_or_dir"
  24. @final
  25. class Parser:
  26. """Parser for command line arguments and ini-file values.
  27. :ivar extra_info: Dict of generic param -> value to display in case
  28. there's an error processing the command line arguments.
  29. """
  30. prog: Optional[str] = None
  31. def __init__(
  32. self,
  33. usage: Optional[str] = None,
  34. processopt: Optional[Callable[["Argument"], None]] = None,
  35. ) -> None:
  36. self._anonymous = OptionGroup("custom options", parser=self)
  37. self._groups: List[OptionGroup] = []
  38. self._processopt = processopt
  39. self._usage = usage
  40. self._inidict: Dict[str, Tuple[str, Optional[str], Any]] = {}
  41. self._ininames: List[str] = []
  42. self.extra_info: Dict[str, Any] = {}
  43. def processoption(self, option: "Argument") -> None:
  44. if self._processopt:
  45. if option.dest:
  46. self._processopt(option)
  47. def getgroup(
  48. self, name: str, description: str = "", after: Optional[str] = None
  49. ) -> "OptionGroup":
  50. """Get (or create) a named option Group.
  51. :name: Name of the option group.
  52. :description: Long description for --help output.
  53. :after: Name of another group, used for ordering --help output.
  54. The returned group object has an ``addoption`` method with the same
  55. signature as :py:func:`parser.addoption
  56. <_pytest.config.argparsing.Parser.addoption>` but will be shown in the
  57. respective group in the output of ``pytest. --help``.
  58. """
  59. for group in self._groups:
  60. if group.name == name:
  61. return group
  62. group = OptionGroup(name, description, parser=self)
  63. i = 0
  64. for i, grp in enumerate(self._groups):
  65. if grp.name == after:
  66. break
  67. self._groups.insert(i + 1, group)
  68. return group
  69. def addoption(self, *opts: str, **attrs: Any) -> None:
  70. """Register a command line option.
  71. :opts: Option names, can be short or long options.
  72. :attrs: Same attributes which the ``add_argument()`` function of the
  73. `argparse library <https://docs.python.org/library/argparse.html>`_
  74. accepts.
  75. After command line parsing, options are available on the pytest config
  76. object via ``config.option.NAME`` where ``NAME`` is usually set
  77. by passing a ``dest`` attribute, for example
  78. ``addoption("--long", dest="NAME", ...)``.
  79. """
  80. self._anonymous.addoption(*opts, **attrs)
  81. def parse(
  82. self,
  83. args: Sequence[Union[str, py.path.local]],
  84. namespace: Optional[argparse.Namespace] = None,
  85. ) -> argparse.Namespace:
  86. from _pytest._argcomplete import try_argcomplete
  87. self.optparser = self._getparser()
  88. try_argcomplete(self.optparser)
  89. strargs = [str(x) if isinstance(x, py.path.local) else x for x in args]
  90. return self.optparser.parse_args(strargs, namespace=namespace)
  91. def _getparser(self) -> "MyOptionParser":
  92. from _pytest._argcomplete import filescompleter
  93. optparser = MyOptionParser(self, self.extra_info, prog=self.prog)
  94. groups = self._groups + [self._anonymous]
  95. for group in groups:
  96. if group.options:
  97. desc = group.description or group.name
  98. arggroup = optparser.add_argument_group(desc)
  99. for option in group.options:
  100. n = option.names()
  101. a = option.attrs()
  102. arggroup.add_argument(*n, **a)
  103. file_or_dir_arg = optparser.add_argument(FILE_OR_DIR, nargs="*")
  104. # bash like autocompletion for dirs (appending '/')
  105. # Type ignored because typeshed doesn't know about argcomplete.
  106. file_or_dir_arg.completer = filescompleter # type: ignore
  107. return optparser
  108. def parse_setoption(
  109. self,
  110. args: Sequence[Union[str, py.path.local]],
  111. option: argparse.Namespace,
  112. namespace: Optional[argparse.Namespace] = None,
  113. ) -> List[str]:
  114. parsedoption = self.parse(args, namespace=namespace)
  115. for name, value in parsedoption.__dict__.items():
  116. setattr(option, name, value)
  117. return cast(List[str], getattr(parsedoption, FILE_OR_DIR))
  118. def parse_known_args(
  119. self,
  120. args: Sequence[Union[str, py.path.local]],
  121. namespace: Optional[argparse.Namespace] = None,
  122. ) -> argparse.Namespace:
  123. """Parse and return a namespace object with known arguments at this point."""
  124. return self.parse_known_and_unknown_args(args, namespace=namespace)[0]
  125. def parse_known_and_unknown_args(
  126. self,
  127. args: Sequence[Union[str, py.path.local]],
  128. namespace: Optional[argparse.Namespace] = None,
  129. ) -> Tuple[argparse.Namespace, List[str]]:
  130. """Parse and return a namespace object with known arguments, and
  131. the remaining arguments unknown at this point."""
  132. optparser = self._getparser()
  133. strargs = [str(x) if isinstance(x, py.path.local) else x for x in args]
  134. return optparser.parse_known_args(strargs, namespace=namespace)
  135. def addini(
  136. self,
  137. name: str,
  138. help: str,
  139. type: Optional[
  140. "Literal['string', 'pathlist', 'args', 'linelist', 'bool']"
  141. ] = None,
  142. default=None,
  143. ) -> None:
  144. """Register an ini-file option.
  145. :name: Name of the ini-variable.
  146. :type: Type of the variable, can be ``string``, ``pathlist``, ``args``,
  147. ``linelist`` or ``bool``. Defaults to ``string`` if ``None`` or
  148. not passed.
  149. :default: Default value if no ini-file option exists but is queried.
  150. The value of ini-variables can be retrieved via a call to
  151. :py:func:`config.getini(name) <_pytest.config.Config.getini>`.
  152. """
  153. assert type in (None, "string", "pathlist", "args", "linelist", "bool")
  154. self._inidict[name] = (help, type, default)
  155. self._ininames.append(name)
  156. class ArgumentError(Exception):
  157. """Raised if an Argument instance is created with invalid or
  158. inconsistent arguments."""
  159. def __init__(self, msg: str, option: Union["Argument", str]) -> None:
  160. self.msg = msg
  161. self.option_id = str(option)
  162. def __str__(self) -> str:
  163. if self.option_id:
  164. return f"option {self.option_id}: {self.msg}"
  165. else:
  166. return self.msg
  167. class Argument:
  168. """Class that mimics the necessary behaviour of optparse.Option.
  169. It's currently a least effort implementation and ignoring choices
  170. and integer prefixes.
  171. https://docs.python.org/3/library/optparse.html#optparse-standard-option-types
  172. """
  173. _typ_map = {"int": int, "string": str, "float": float, "complex": complex}
  174. def __init__(self, *names: str, **attrs: Any) -> None:
  175. """Store parms in private vars for use in add_argument."""
  176. self._attrs = attrs
  177. self._short_opts: List[str] = []
  178. self._long_opts: List[str] = []
  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. dest: Optional[str] = attrs.get("dest")
  225. if dest:
  226. self.dest = dest
  227. elif self._long_opts:
  228. self.dest = self._long_opts[0][2:].replace("-", "_")
  229. else:
  230. try:
  231. self.dest = self._short_opts[0][1:]
  232. except IndexError as e:
  233. self.dest = "???" # Needed for the error repr.
  234. raise ArgumentError("need a long or short option", self) from e
  235. def names(self) -> List[str]:
  236. return self._short_opts + self._long_opts
  237. def attrs(self) -> Mapping[str, Any]:
  238. # Update any attributes set by processopt.
  239. attrs = "default dest help".split()
  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
  252. def _set_opt_strings(self, opts: Sequence[str]) -> None:
  253. """Directly from optparse.
  254. Might not be necessary as this is passed to argparse later on.
  255. """
  256. for opt in opts:
  257. if len(opt) < 2:
  258. raise ArgumentError(
  259. "invalid option string %r: "
  260. "must be at least two characters long" % opt,
  261. self,
  262. )
  263. elif len(opt) == 2:
  264. if not (opt[0] == "-" and opt[1] != "-"):
  265. raise ArgumentError(
  266. "invalid short option string %r: "
  267. "must be of the form -x, (x any non-dash char)" % opt,
  268. self,
  269. )
  270. self._short_opts.append(opt)
  271. else:
  272. if not (opt[0:2] == "--" and opt[2] != "-"):
  273. raise ArgumentError(
  274. "invalid long option string %r: "
  275. "must start with --, followed by non-dash" % opt,
  276. self,
  277. )
  278. self._long_opts.append(opt)
  279. def __repr__(self) -> str:
  280. args: List[str] = []
  281. if self._short_opts:
  282. args += ["_short_opts: " + repr(self._short_opts)]
  283. if self._long_opts:
  284. args += ["_long_opts: " + repr(self._long_opts)]
  285. args += ["dest: " + repr(self.dest)]
  286. if hasattr(self, "type"):
  287. args += ["type: " + repr(self.type)]
  288. if hasattr(self, "default"):
  289. args += ["default: " + repr(self.default)]
  290. return "Argument({})".format(", ".join(args))
  291. class OptionGroup:
  292. def __init__(
  293. self, name: str, description: str = "", parser: Optional[Parser] = None
  294. ) -> None:
  295. self.name = name
  296. self.description = description
  297. self.options: List[Argument] = []
  298. self.parser = parser
  299. def addoption(self, *optnames: str, **attrs: Any) -> None:
  300. """Add an option to this group.
  301. If a shortened version of a long option is specified, it will
  302. be suppressed in the help. addoption('--twowords', '--two-words')
  303. results in help showing '--two-words' only, but --twowords gets
  304. accepted **and** the automatic destination is in args.twowords.
  305. """
  306. conflict = set(optnames).intersection(
  307. name for opt in self.options for name in opt.names()
  308. )
  309. if conflict:
  310. raise ValueError("option names %s already added" % conflict)
  311. option = Argument(*optnames, **attrs)
  312. self._addoption_instance(option, shortupper=False)
  313. def _addoption(self, *optnames: str, **attrs: Any) -> None:
  314. option = Argument(*optnames, **attrs)
  315. self._addoption_instance(option, shortupper=True)
  316. def _addoption_instance(self, option: "Argument", shortupper: bool = False) -> None:
  317. if not shortupper:
  318. for opt in option._short_opts:
  319. if opt[0] == "-" and opt[1].islower():
  320. raise ValueError("lowercase shortoptions reserved")
  321. if self.parser:
  322. self.parser.processoption(option)
  323. self.options.append(option)
  324. class MyOptionParser(argparse.ArgumentParser):
  325. def __init__(
  326. self,
  327. parser: Parser,
  328. extra_info: Optional[Dict[str, Any]] = None,
  329. prog: Optional[str] = None,
  330. ) -> None:
  331. self._parser = parser
  332. argparse.ArgumentParser.__init__(
  333. self,
  334. prog=prog,
  335. usage=parser._usage,
  336. add_help=False,
  337. formatter_class=DropShorterLongHelpFormatter,
  338. allow_abbrev=False,
  339. )
  340. # extra_info is a dict of (param -> value) to display if there's
  341. # an usage error to provide more contextual information to the user.
  342. self.extra_info = extra_info if extra_info else {}
  343. def error(self, message: str) -> "NoReturn":
  344. """Transform argparse error message into UsageError."""
  345. msg = f"{self.prog}: error: {message}"
  346. if hasattr(self._parser, "_config_source_hint"):
  347. # Type ignored because the attribute is set dynamically.
  348. msg = f"{msg} ({self._parser._config_source_hint})" # type: ignore
  349. raise UsageError(self.format_usage() + msg)
  350. # Type ignored because typeshed has a very complex type in the superclass.
  351. def parse_args( # type: ignore
  352. self,
  353. args: Optional[Sequence[str]] = None,
  354. namespace: Optional[argparse.Namespace] = None,
  355. ) -> argparse.Namespace:
  356. """Allow splitting of positional arguments."""
  357. parsed, unrecognized = self.parse_known_args(args, namespace)
  358. if unrecognized:
  359. for arg in unrecognized:
  360. if arg and arg[0] == "-":
  361. lines = ["unrecognized arguments: %s" % (" ".join(unrecognized))]
  362. for k, v in sorted(self.extra_info.items()):
  363. lines.append(f" {k}: {v}")
  364. self.error("\n".join(lines))
  365. getattr(parsed, FILE_OR_DIR).extend(unrecognized)
  366. return parsed
  367. if sys.version_info[:2] < (3, 9): # pragma: no cover
  368. # Backport of https://github.com/python/cpython/pull/14316 so we can
  369. # disable long --argument abbreviations without breaking short flags.
  370. def _parse_optional(
  371. self, arg_string: str
  372. ) -> Optional[Tuple[Optional[argparse.Action], str, Optional[str]]]:
  373. if not arg_string:
  374. return None
  375. if not arg_string[0] in self.prefix_chars:
  376. return None
  377. if arg_string in self._option_string_actions:
  378. action = self._option_string_actions[arg_string]
  379. return action, arg_string, None
  380. if len(arg_string) == 1:
  381. return None
  382. if "=" in arg_string:
  383. option_string, explicit_arg = arg_string.split("=", 1)
  384. if option_string in self._option_string_actions:
  385. action = self._option_string_actions[option_string]
  386. return action, option_string, explicit_arg
  387. if self.allow_abbrev or not arg_string.startswith("--"):
  388. option_tuples = self._get_option_tuples(arg_string)
  389. if len(option_tuples) > 1:
  390. msg = gettext(
  391. "ambiguous option: %(option)s could match %(matches)s"
  392. )
  393. options = ", ".join(option for _, option, _ in option_tuples)
  394. self.error(msg % {"option": arg_string, "matches": options})
  395. elif len(option_tuples) == 1:
  396. (option_tuple,) = option_tuples
  397. return option_tuple
  398. if self._negative_number_matcher.match(arg_string):
  399. if not self._has_negative_number_optionals:
  400. return None
  401. if " " in arg_string:
  402. return None
  403. return None, arg_string, None
  404. class DropShorterLongHelpFormatter(argparse.HelpFormatter):
  405. """Shorten help for long options that differ only in extra hyphens.
  406. - Collapse **long** options that are the same except for extra hyphens.
  407. - Shortcut if there are only two options and one of them is a short one.
  408. - Cache result on the action object as this is called at least 2 times.
  409. """
  410. def __init__(self, *args: Any, **kwargs: Any) -> None:
  411. # Use more accurate terminal width.
  412. if "width" not in kwargs:
  413. kwargs["width"] = _pytest._io.get_terminal_width()
  414. super().__init__(*args, **kwargs)
  415. def _format_action_invocation(self, action: argparse.Action) -> str:
  416. orgstr = argparse.HelpFormatter._format_action_invocation(self, action)
  417. if orgstr and orgstr[0] != "-": # only optional arguments
  418. return orgstr
  419. res: Optional[str] = getattr(action, "_formatted_action_invocation", None)
  420. if res:
  421. return res
  422. options = orgstr.split(", ")
  423. if len(options) == 2 and (len(options[0]) == 2 or len(options[1]) == 2):
  424. # a shortcut for '-h, --help' or '--abc', '-a'
  425. action._formatted_action_invocation = orgstr # type: ignore
  426. return orgstr
  427. return_list = []
  428. short_long: Dict[str, str] = {}
  429. for option in options:
  430. if len(option) == 2 or option[2] == " ":
  431. continue
  432. if not option.startswith("--"):
  433. raise ArgumentError(
  434. 'long optional argument without "--": [%s]' % (option), option
  435. )
  436. xxoption = option[2:]
  437. shortened = xxoption.replace("-", "")
  438. if shortened not in short_long or len(short_long[shortened]) < len(
  439. xxoption
  440. ):
  441. short_long[shortened] = xxoption
  442. # now short_long has been filled out to the longest with dashes
  443. # **and** we keep the right option ordering from add_argument
  444. for option in options:
  445. if len(option) == 2 or option[2] == " ":
  446. return_list.append(option)
  447. if option[2:] == short_long.get(option.replace("-", "")):
  448. return_list.append(option.replace(" ", "=", 1))
  449. formatted_action_invocation = ", ".join(return_list)
  450. action._formatted_action_invocation = formatted_action_invocation # type: ignore
  451. return formatted_action_invocation
  452. def _split_lines(self, text, width):
  453. """Wrap lines after splitting on original newlines.
  454. This allows to have explicit line breaks in the help text.
  455. """
  456. import textwrap
  457. lines = []
  458. for line in text.splitlines():
  459. lines.extend(textwrap.wrap(line.strip(), width))
  460. return lines