Skip to content

Commit f05ca74

Browse files
authored
Merge pull request #5056 from blueyed/argparsing-width
Inject width via pylib to argparse formatter
2 parents 0f11a7a + 2a6a1ca commit f05ca74

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

changelog/5056.trivial.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
The HelpFormatter uses ``py.io.get_terminal_width`` for better width detection.

src/_pytest/config/argparsing.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -405,6 +405,12 @@ class DropShorterLongHelpFormatter(argparse.HelpFormatter):
405405
- cache result on action object as this is called at least 2 times
406406
"""
407407

408+
def __init__(self, *args, **kwargs):
409+
"""Use more accurate terminal width via pylib."""
410+
if "width" not in kwargs:
411+
kwargs["width"] = py.io.get_terminal_width()
412+
super().__init__(*args, **kwargs)
413+
408414
def _format_action_invocation(self, action):
409415
orgstr = argparse.HelpFormatter._format_action_invocation(self, action)
410416
if orgstr and orgstr[0] != "-": # only optional arguments

testing/test_config.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1194,6 +1194,21 @@ def pytest_addoption(parser):
11941194
assert result.ret == ExitCode.USAGE_ERROR
11951195

11961196

1197+
def test_help_formatter_uses_py_get_terminal_width(testdir, monkeypatch):
1198+
from _pytest.config.argparsing import DropShorterLongHelpFormatter
1199+
1200+
monkeypatch.setenv("COLUMNS", "90")
1201+
formatter = DropShorterLongHelpFormatter("prog")
1202+
assert formatter._width == 90
1203+
1204+
monkeypatch.setattr("py.io.get_terminal_width", lambda: 160)
1205+
formatter = DropShorterLongHelpFormatter("prog")
1206+
assert formatter._width == 160
1207+
1208+
formatter = DropShorterLongHelpFormatter("prog", width=42)
1209+
assert formatter._width == 42
1210+
1211+
11971212
def test_config_does_not_load_blocked_plugin_from_args(testdir):
11981213
"""This tests that pytest's config setup handles "-p no:X"."""
11991214
p = testdir.makepyfile("def test(capfd): pass")

0 commit comments

Comments
 (0)