{"record":{"id":"80fb2d8ba3fb6e89","repo":"pytest-dev/pytest","slug":"self-prog-error-message","errorCode":null,"errorMessage":"{self.prog}: error: {message}","messagePattern":"(.+?): error: (.+?)","errorType":"exception","errorClass":"UsageError","httpStatus":null,"severity":"error","filePath":"src/_pytest/config/argparsing.py","lineNumber":523,"sourceCode":"            add_help=False,\n            formatter_class=DropShorterLongHelpFormatter,\n            allow_abbrev=False,\n            fromfile_prefix_chars=\"@\",\n        )\n        # extra_info is a dict of (param -> value) to display if there's\n        # an usage error to provide more contextual information to the user.\n        self.extra_info = extra_info\n\n    def error(self, message: str) -> NoReturn:\n        \"\"\"Transform argparse error message into UsageError.\"\"\"\n        # TODO(py313): Replace with `exit_on_error=False`. Note that while it\n        # was added in Python 3.9, it was broken until 3.13 (cpython#121018).\n        msg = f\"{self.prog}: error: {message}\"\n        if self.extra_info:\n            msg += \"\\n\" + \"\\n\".join(\n                f\"  {k}: {v}\" for k, v in sorted(self.extra_info.items())\n            )\n        raise UsageError(self.format_usage() + msg)\n\n\nclass DropShorterLongHelpFormatter(argparse.HelpFormatter):\n    \"\"\"Shorten help for long options that differ only in extra hyphens.\n\n    - Collapse **long** options that are the same except for extra hyphens.\n    - Shortcut if there are only two options and one of them is a short one.\n    \"\"\"\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        # Use more accurate terminal width.\n        if \"width\" not in kwargs:\n            kwargs[\"width\"] = _pytest._io.get_terminal_width()\n        super().__init__(*args, **kwargs)\n\n    def _format_action_invocation(self, action: argparse.Action) -> str:\n        orgstr = super()._format_action_invocation(action)\n        if orgstr and orgstr[0] != \"-\":  # only optional arguments","sourceCodeStart":505,"sourceCodeEnd":541,"githubUrl":"https://github.com/pytest-dev/pytest/blob/0d6fbdeffa57c796123f62f81f7dd370d9b7ecdc/src/_pytest/config/argparsing.py#L505-L541","documentation":"PytestArgumentParser.error() wraps any argparse usage error (unknown flag, missing required arg, bad value) into a pytest UsageError. The message combines the program name, the argparse error, and any extra_info (e.g. plugin context). It replaces argparse's default sys.exit so pytest can surface the failure as a catchable exception.","triggerScenarios":"Passing an unrecognized command-line flag; supplying a value to a flag that expects a count; missing a required argument to a pytest plugin option; malformed -k expression where argparse itself rejects it.","commonSituations":"Typo in a CLI flag (--pdbset vs --pdbcls); upgrading pytest and an old flag was removed; a plugin not installed but its flag referenced; shell quoting issues passing params.","solutions":["Re-read the error: the {message} portion usually names the offending flag; fix or remove it from your pytest invocation.","Run 'pytest --help' to confirm the exact spelling and whether the option still exists.","If a plugin option is reported, ensure the plugin is installed and importable (pip show <plugin>)."],"exampleFix":"// before\npytest --pdbset=foo:test_x.py\n// after\npytest --pdbcls=foo:Pdb test_x.py","handlingStrategy":"try-catch","validationCode":"null","typeGuard":"null","tryCatchPattern":"import pytest\n\ntry:\n    config = pytest.main(['--bad-flag'])\nexcept pytest.UsageError as e:\n    print('usage error:', e)\n    # fall back to a known-good invocation\n    config = pytest.main([])","preventionTips":["Validate CLI flags against 'pytest --help' before scripting pytest invocations.","In CI, run 'pytest --collect-only' first to fail fast on bad flags.","Pin pytest and plugin versions to avoid silent flag removal."],"tags":["cli","argparse","usage-error"],"backgroundTag":null,"analyzedSha":"0d6fbdeffa57c796123f62f81f7dd370d9b7ecdc","analyzedAt":"2026-08-11T20:52:36.969Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}