From 2a6a1ca07dac49cc7ceb64543ea16ad457f1a1dd Mon Sep 17 00:00:00 2001 From: Daniel Hahler Date: Fri, 5 Apr 2019 15:16:35 +0200 Subject: [PATCH] Inject width via pylib to argparse formatter `argparse.HelpFormatter` looks at `$COLUMNS` only, falling back to a default of 80. `py.io.get_terminal_width()` is smarter there, and could even work better with https://github.com/pytest-dev/py/pull/219. This ensures to use a consistent value for formatting the ini values etc. --- changelog/5056.trivial.rst | 1 + src/_pytest/config/argparsing.py | 6 ++++++ testing/test_config.py | 15 +++++++++++++++ 3 files changed, 22 insertions(+) create mode 100644 changelog/5056.trivial.rst diff --git a/changelog/5056.trivial.rst b/changelog/5056.trivial.rst new file mode 100644 index 000000000..75e01a88b --- /dev/null +++ b/changelog/5056.trivial.rst @@ -0,0 +1 @@ +The HelpFormatter uses ``py.io.get_terminal_width`` for better width detection. diff --git a/src/_pytest/config/argparsing.py b/src/_pytest/config/argparsing.py index 8994ff7d9..de3c7d90b 100644 --- a/src/_pytest/config/argparsing.py +++ b/src/_pytest/config/argparsing.py @@ -405,6 +405,12 @@ class DropShorterLongHelpFormatter(argparse.HelpFormatter): - cache result on action object as this is called at least 2 times """ + def __init__(self, *args, **kwargs): + """Use more accurate terminal width via pylib.""" + if "width" not in kwargs: + kwargs["width"] = py.io.get_terminal_width() + super().__init__(*args, **kwargs) + def _format_action_invocation(self, action): orgstr = argparse.HelpFormatter._format_action_invocation(self, action) if orgstr and orgstr[0] != "-": # only optional arguments diff --git a/testing/test_config.py b/testing/test_config.py index fc3659d2a..71dae5c4c 100644 --- a/testing/test_config.py +++ b/testing/test_config.py @@ -1194,6 +1194,21 @@ def test_help_and_version_after_argument_error(testdir): assert result.ret == ExitCode.USAGE_ERROR +def test_help_formatter_uses_py_get_terminal_width(testdir, monkeypatch): + from _pytest.config.argparsing import DropShorterLongHelpFormatter + + monkeypatch.setenv("COLUMNS", "90") + formatter = DropShorterLongHelpFormatter("prog") + assert formatter._width == 90 + + monkeypatch.setattr("py.io.get_terminal_width", lambda: 160) + formatter = DropShorterLongHelpFormatter("prog") + assert formatter._width == 160 + + formatter = DropShorterLongHelpFormatter("prog", width=42) + assert formatter._width == 42 + + def test_config_does_not_load_blocked_plugin_from_args(testdir): """This tests that pytest's config setup handles "-p no:X".""" p = testdir.makepyfile("def test(capfd): pass")