Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -492,6 +492,7 @@ Tanvi Mehta
Tanya Agarwal
Tarcisio Fischer
Tareq Alayan
Tate Suarez
Tatiana Ovary
Ted Xiao
Terje Runde
Expand Down
1 change: 1 addition & 0 deletions changelog/9452.feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added the ``--help-group=<name>`` 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``.
9 changes: 9 additions & 0 deletions src/_pytest/config/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
45 changes: 41 additions & 4 deletions src/_pytest/helpconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand All @@ -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
Expand All @@ -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",
Expand Down Expand Up @@ -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(
Expand Down
185 changes: 185 additions & 0 deletions testing/test_help_group.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
# mypy: allow-untyped-defs
"""Unit and regression tests for ``--help-group`` (#9452).

``pytest --help-group=<name>`` 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)
Loading