pytest-dev/pytest · error · UsageError
{self.prog}: error: {message}
Error message
{self.prog}: error: {message} What it means
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.
Source
Thrown at src/_pytest/config/argparsing.py:523
add_help=False,
formatter_class=DropShorterLongHelpFormatter,
allow_abbrev=False,
fromfile_prefix_chars="@",
)
# extra_info is a dict of (param -> value) to display if there's
# an usage error to provide more contextual information to the user.
self.extra_info = extra_info
def error(self, message: str) -> NoReturn:
"""Transform argparse error message into UsageError."""
# TODO(py313): Replace with `exit_on_error=False`. Note that while it
# was added in Python 3.9, it was broken until 3.13 (cpython#121018).
msg = f"{self.prog}: error: {message}"
if self.extra_info:
msg += "\n" + "\n".join(
f" {k}: {v}" for k, v in sorted(self.extra_info.items())
)
raise UsageError(self.format_usage() + msg)
class DropShorterLongHelpFormatter(argparse.HelpFormatter):
"""Shorten help for long options that differ only in extra hyphens.
- Collapse **long** options that are the same except for extra hyphens.
- Shortcut if there are only two options and one of them is a short one.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
# Use more accurate terminal width.
if "width" not in kwargs:
kwargs["width"] = _pytest._io.get_terminal_width()
super().__init__(*args, **kwargs)
def _format_action_invocation(self, action: argparse.Action) -> str:
orgstr = super()._format_action_invocation(action)
if orgstr and orgstr[0] != "-": # only optional argumentsView on GitHub (pinned to 0d6fbdeffa)
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>).
Example fix
// before pytest --pdbset=foo:test_x.py // after pytest --pdbcls=foo:Pdb test_x.py
Defensive patterns
Strategy: try-catch
Validate before calling
null
Type guard
null
Try / catch
import pytest
try:
config = pytest.main(['--bad-flag'])
except pytest.UsageError as e:
print('usage error:', e)
# fall back to a known-good invocation
config = pytest.main([]) Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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.
Related errors
- {optname} must be a filename, given: {path}
- {optname} must be a directory, given: {path}
- {exc_message}: {e.text}: at column {e.offset}: {e.msg}
- unknown capturing method: {method!r}
- plugin {name} cannot be disabled
AI-assisted analysis of pytest-dev/pytest@0d6fbdeffa (2026-08-11).
Data as JSON: /api/errors/80fb2d8ba3fb6e89.
Report an issue: GitHub.