diff --git a/AUTHORS b/AUTHORS index 6fd2bec926e..1f30f713dfa 100644 --- a/AUTHORS +++ b/AUTHORS @@ -492,6 +492,7 @@ Tanvi Mehta Tanya Agarwal Tarcisio Fischer Tareq Alayan +Tate Suarez Tatiana Ovary Ted Xiao Terje Runde diff --git a/changelog/9452.feature.rst b/changelog/9452.feature.rst new file mode 100644 index 00000000000..b0c4ac9d7ba --- /dev/null +++ b/changelog/9452.feature.rst @@ -0,0 +1 @@ +Added the ``--help-group=`` command-line option, which shows ``--help`` output for only the given option group, such as one defined by a plugin or a project's ``conftest.py``. diff --git a/src/_pytest/config/__init__.py b/src/_pytest/config/__init__.py index f1593fb0336..12d0450a10e 100644 --- a/src/_pytest/config/__init__.py +++ b/src/_pytest/config/__init__.py @@ -1820,6 +1820,15 @@ def parse(self, args: list[str], addopts: bool = True) -> None: else: raise + if self.known_args_namespace.help_group is not False: + available_groups = [group.name for group in self._parser._groups] + if self.known_args_namespace.help_group not in available_groups: + raise UsageError( + f"unknown help group {self.known_args_namespace.help_group!r}; " + f"available groups: {', '.join(available_groups)}" + ) + self.option.help_group = self.known_args_namespace.help_group + try: self._parser.parse(args, namespace=self.option) except PrintHelp: diff --git a/src/_pytest/helpconfig.py b/src/_pytest/helpconfig.py index 8d9d44699c1..92c7f720c6c 100644 --- a/src/_pytest/helpconfig.py +++ b/src/_pytest/helpconfig.py @@ -22,7 +22,7 @@ class HelpAction(argparse.Action): """An argparse Action that will raise a PrintHelp exception in order to skip - the rest of the argument parsing when --help is passed. + the rest of the argument parsing when a help option is passed. This prevents argparse from raising UsageError when `--help` is used along with missing required arguments when any are defined, for example by @@ -34,12 +34,17 @@ class HelpAction(argparse.Action): """ def __init__( - self, option_strings: Sequence[str], dest: str, *, help: str | None = None + self, + option_strings: Sequence[str], + dest: str, + *, + help: str | None = None, + nargs: int | str | None = 0, ) -> None: super().__init__( option_strings=option_strings, dest=dest, - nargs=0, + nargs=nargs, const=True, default=False, help=help, @@ -52,7 +57,11 @@ def __call__( values: str | Sequence[Any] | None, option_string: str | None = None, ) -> None: - setattr(namespace, self.dest, self.const) + if self.nargs == 0: + setattr(namespace, self.dest, self.const) + else: + setattr(namespace, self.dest, values) + setattr(namespace, "help", True) if getattr(namespace, "_raise_print_help", False): raise PrintHelp @@ -76,6 +85,13 @@ def pytest_addoption(parser: Parser) -> None: dest="help", help="Show help message and configuration info", ) + group.addoption( + "--help-group", + action=HelpAction, + nargs=None, + dest="help_group", + help="Show help for a specific option group.", + ) group._addoption( # private to use reserved lower-case short option "-p", action="append", @@ -179,12 +195,33 @@ def pytest_cmdline_main(config: Config) -> int | ExitCode | None: return None +def _format_group_help(config: Config, name: str) -> str: + """Format the --help section for the option group called ``name``. + + The name has already been validated in ``Config._preparse``. + """ + group = next(g for g in config._parser._groups if g.name == name) + arggroup = group._arggroup + formatter = config._parser.optparser._get_formatter() + formatter.start_section(arggroup.title) + formatter.add_text(arggroup.description) + formatter.add_arguments(arggroup._group_actions) + formatter.end_section() + return formatter.format_help() + + def showhelp(config: Config) -> None: reporter: TerminalReporter | None = config.pluginmanager.get_plugin( "terminalreporter" ) assert reporter is not None tw = reporter._tw + + help_group = getattr(config.option, "help_group", False) + if help_group is not False: + tw.write(_format_group_help(config, help_group)) + return + tw.write(config._parser.optparser.format_help()) tw.line() tw.line( diff --git a/testing/test_help_group.py b/testing/test_help_group.py new file mode 100644 index 00000000000..6d7222afd35 --- /dev/null +++ b/testing/test_help_group.py @@ -0,0 +1,185 @@ +# mypy: allow-untyped-defs +"""Unit and regression tests for ``--help-group`` (#9452). + +``pytest --help-group=`` shows the help for a single option group, so +projects can see their own options without scrolling through all of +``pytest --help``. +""" + +from __future__ import annotations + +import argparse + +from _pytest.config import ExitCode +from _pytest.helpconfig import HelpAction +from _pytest.pytester import Pytester +import pytest + + +CUSTOM_CONFTEST = """ +def pytest_addoption(parser): + group = parser.getgroup("custom", "custom options") + group.addoption("--foo", help="foo option help") + group.addoption("--bar-thing", action="store_true", help="bar option help") +""" + + +@pytest.fixture +def custom_group(pytester: Pytester) -> None: + pytester.makeconftest(CUSTOM_CONFTEST) + + +# --- HelpAction --------------------------------------------------------------- + + +def test_help_action_without_value_sets_flag() -> None: + """``--help`` takes no value and just turns help on.""" + parser = argparse.ArgumentParser() + parser.add_argument("--help-x", action=HelpAction, dest="help") + namespace = parser.parse_args(["--help-x"]) + assert namespace.help is True + + +def test_help_action_with_value_stores_group_and_turns_on_help() -> None: + """``--help-group`` stores the group name and also turns help on.""" + parser = argparse.ArgumentParser() + parser.add_argument( + "--help-group", action=HelpAction, nargs=None, dest="help_group" + ) + namespace = parser.parse_args(["--help-group", "custom"]) + assert namespace.help_group == "custom" + assert namespace.help is True + + +def test_help_action_defaults_to_false() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--help-group", action=HelpAction, nargs=None, dest="help_group" + ) + assert parser.parse_args([]).help_group is False + + +# --- Normal filtering --------------------------------------------------------- + + +@pytest.mark.parametrize( + "args", [["--help-group=custom"], ["--help", "--help-group=custom"]] +) +def test_help_group_shows_only_that_group( + pytester: Pytester, custom_group: None, args: list[str] +) -> None: + result = pytester.runpytest(*args) + assert result.ret == ExitCode.OK + result.stdout.fnmatch_lines( + [ + "*custom options*", + "*--foo=FOO*foo option help*", + "*--bar-thing*bar option help*", + ] + ) + # Options from other groups are hidden. + result.stdout.no_fnmatch_line("*-k EXPRESSION*") + result.stdout.no_fnmatch_line("*--durations=N*") + result.stdout.no_fnmatch_line("*--version*") + + +def test_help_group_works_for_builtin_group(pytester: Pytester) -> None: + result = pytester.runpytest("--help-group=debugconfig") + assert result.ret == ExitCode.OK + result.stdout.fnmatch_lines(["*-V, --version*"]) + result.stdout.no_fnmatch_line("*-k EXPRESSION*") + + +def test_help_group_does_not_run_tests(pytester: Pytester, custom_group: None) -> None: + pytester.makepyfile("def test_fails(): assert False") + result = pytester.runpytest("--help-group=custom") + assert result.ret == ExitCode.OK + result.stdout.no_fnmatch_line("*1 failed*") + result.stdout.no_fnmatch_line("*test_fails*") + + +def test_help_group_ignores_missing_required_options(pytester: Pytester) -> None: + """Like ``--help``, it works even if a required option wasn't passed.""" + pytester.makeconftest( + """ + def pytest_addoption(parser): + group = parser.getgroup("custom", "custom options") + group.addoption("--needed", required=True, help="needed option help") + """ + ) + result = pytester.runpytest("--help-group=custom") + assert result.ret == ExitCode.OK + result.stdout.fnmatch_lines(["*--needed*needed option help*"]) + + +# --- Invalid commands --------------------------------------------------------- + + +def test_help_group_unknown_name(pytester: Pytester, custom_group: None) -> None: + result = pytester.runpytest("--help-group=nope") + assert result.ret == ExitCode.USAGE_ERROR + result.stderr.fnmatch_lines( + ["*unknown help group 'nope'; available groups:*general*custom*"] + ) + + +def test_help_group_empty_name(pytester: Pytester) -> None: + result = pytester.runpytest("--help-group=") + assert result.ret == ExitCode.USAGE_ERROR + result.stderr.fnmatch_lines(["*unknown help group ''*"]) + + +def test_help_group_missing_value(pytester: Pytester) -> None: + result = pytester.runpytest("--help-group") + assert result.ret == ExitCode.USAGE_ERROR + result.stderr.fnmatch_lines(["*--help-group: expected one argument*"]) + + +def test_help_group_unknown_name_does_not_run_tests(pytester: Pytester) -> None: + pytester.makepyfile("def test_fails(): assert False") + result = pytester.runpytest("--help-group=nope") + assert result.ret == ExitCode.USAGE_ERROR + result.stdout.no_fnmatch_line("*1 failed*") + + +# --- Regression: everything else works like before ------------------------------ + + +@pytest.mark.parametrize("flag", ["--help", "-h"]) +def test_full_help_still_shows_every_section(pytester: Pytester, flag: str) -> None: + result = pytester.runpytest(flag) + assert result.ret == ExitCode.OK + result.stdout.fnmatch_lines( + [ + "*-k EXPRESSION*", + "*--durations=N*", + "*-V, --version*", + "*--help-group=HELP_GROUP*", + "*configuration options*", + "Environment variables:", + "*to see*markers*pytest --markers*", + ] + ) + + +def test_full_help_still_shows_custom_options( + pytester: Pytester, custom_group: None +) -> None: + result = pytester.runpytest("--help") + assert result.ret == ExitCode.OK + result.stdout.fnmatch_lines( + ["*-k EXPRESSION*", "*custom options*", "*--foo=FOO*foo option help*"] + ) + + +def test_normal_run_has_help_options_off(pytester: Pytester) -> None: + pytester.makepyfile( + """ + def test_options(request): + assert request.config.option.help is False + assert request.config.option.help_group is False + """ + ) + result = pytester.runpytest() + assert result.ret == ExitCode.OK + result.assert_outcomes(passed=1)