Skip to content

Commit 46e751b

Browse files
committed
Improve error reporting for custom CLI args with missing path; add test
1 parent d2d57e3 commit 46e751b

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

src/_pytest/config/argparsing.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -443,6 +443,13 @@ def __init__(
443443
def error(self, message: str) -> NoReturn:
444444
"""Transform argparse error message into UsageError."""
445445
msg = f"{self.prog}: error: {message}"
446+
if "unrecognized arguments:" in message:
447+
file_or_dir_args = getattr(self._parser, 'extra_info', {}).get('file_or_dir', [])
448+
if file_or_dir_args:
449+
from pathlib import Path
450+
missing_paths = [str(p) for p in file_or_dir_args if not Path(str(p)).exists()]
451+
if missing_paths:
452+
msg += ("\nNote: The specified path(s) do not exist, so custom CLI options from conftest.py may not be available.")
446453

447454
if hasattr(self._parser, "_config_source_hint"):
448455
msg = f"{msg} ({self._parser._config_source_hint})"

testing/test_main.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,18 @@ def test_absolute_paths_are_resolved_correctly(self, invocation_path: Path) -> N
271271
module_name=None,
272272
)
273273

274+
def test_custom_cli_arg_with_missing_path(pytester: Pytester):
275+
"""Test that a helpful error message is shown when a custom CLI argument is used with a non-existent path."""
276+
pytester.makeconftest(
277+
"""
278+
def pytest_addoption(parser):
279+
parser.addoption("--potato", default="")
280+
"""
281+
)
282+
result = pytester.runpytest("file_does_not_exist.py", "--potato=yum")
283+
assert result.ret != 0
284+
assert "unrecognized arguments: --potato=yum" in result.stderr.str()
285+
assert "Note: The specified path(s) do not exist" in result.stderr.str()
274286

275287
def test_module_full_path_without_drive(pytester: Pytester) -> None:
276288
"""Collect and run test using full path except for the drive letter (#7628).

0 commit comments

Comments
 (0)