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.
This commit is contained in:
Daniel Hahler 2019-04-05 15:16:35 +02:00
parent 0f11a7a73d
commit 2a6a1ca07d
3 changed files with 22 additions and 0 deletions

View File

@ -0,0 +1 @@
The HelpFormatter uses ``py.io.get_terminal_width`` for better width detection.

View File

@ -405,6 +405,12 @@ class DropShorterLongHelpFormatter(argparse.HelpFormatter):
- cache result on action object as this is called at least 2 times - 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): def _format_action_invocation(self, action):
orgstr = argparse.HelpFormatter._format_action_invocation(self, action) orgstr = argparse.HelpFormatter._format_action_invocation(self, action)
if orgstr and orgstr[0] != "-": # only optional arguments if orgstr and orgstr[0] != "-": # only optional arguments

View File

@ -1194,6 +1194,21 @@ def test_help_and_version_after_argument_error(testdir):
assert result.ret == ExitCode.USAGE_ERROR 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): def test_config_does_not_load_blocked_plugin_from_args(testdir):
"""This tests that pytest's config setup handles "-p no:X".""" """This tests that pytest's config setup handles "-p no:X"."""
p = testdir.makepyfile("def test(capfd): pass") p = testdir.makepyfile("def test(capfd): pass")