File: test_optparse.py

package info (click to toggle)
python-rich-argparse 1.6.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 300 kB
  • sloc: python: 2,224; makefile: 3
file content (460 lines) | stat: -rw-r--r-- 18,537 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
from __future__ import annotations

import sys
from optparse import (
    SUPPRESS_HELP,
    HelpFormatter,
    IndentedHelpFormatter,
    OptionGroup,
    OptionParser,
    TitledHelpFormatter,
)
from textwrap import dedent
from unittest.mock import Mock, patch

import pytest
from rich import get_console

import rich_argparse._lazy_rich as r
from rich_argparse.optparse import (
    GENERATE_USAGE,
    IndentedRichHelpFormatter,
    RichHelpFormatter,
    TitledRichHelpFormatter,
)
from tests.conftest import Parsers


# helpers
# =======
class OptionParsers(Parsers[OptionParser, OptionGroup, HelpFormatter]):
    parser_class = OptionParser
    formatter_param_name = "formatter"


# tests
# =====
def test_default_substitution():
    parser = OptionParser(prog="PROG", formatter=IndentedRichHelpFormatter())
    parser.add_option("--option", default="[bold]", help="help of option (default: %default)")

    expected_help_output = """\
    Usage: PROG [options]

    Options:
      -h, --help       show this help message and exit
      --option=OPTION  help of option (default: [bold])
    """
    assert parser.format_help() == dedent(expected_help_output)


@pytest.mark.parametrize("prog", (None, "PROG"), ids=("no_prog", "prog"))
@pytest.mark.parametrize("usage", (None, "USAGE"), ids=("no_usage", "usage"))
@pytest.mark.parametrize("description", (None, "A description."), ids=("no_desc", "desc"))
@pytest.mark.parametrize("epilog", (None, "An epilog."), ids=("no_epilog", "epilog"))
def test_overall_structure(prog, usage, description, epilog):
    # The output must be consistent with the original HelpFormatter in these cases:
    # 1. no markup/emoji codes are used
    # 4. colors are disabled
    parsers = OptionParsers(
        IndentedHelpFormatter(),
        IndentedRichHelpFormatter(),
        prog=prog,
        usage=usage,
        description=description,
        epilog=epilog,
    )
    parsers.add_option("--file", default="-", help="A file (default: %default).")
    parsers.add_option("--spaces", help="Arg   with  weird\n\n whitespaces\t\t.")
    parsers.add_option("--very-very-very-very-very-very-very-very-long-option-name", help="help!")
    parsers.add_option("--very-long-option-that-has-no-help-text")

    # all types of empty groups
    parsers.add_option_group("empty group name", description="empty_group description")
    parsers.add_option_group("no description empty group name")
    parsers.add_option_group("", description="empty_name_empty_group description")
    parsers.add_option_group("spaces group", description=" \tspaces_group description  ")

    # all types of non-empty groups
    groups = parsers.add_option_group("title", description="description")
    groups.add_option("--arg1", help="help inside group")
    no_desc_groups = parsers.add_option_group("title")
    no_desc_groups.add_option("--arg2", help="arg help inside no_desc_group")
    empty_title_group = parsers.add_option_group("", description="description")
    empty_title_group.add_option("--arg3", help="arg help inside empty_title_group")

    parsers.assert_format_help_equal()


def test_padding_and_wrapping():
    parsers = OptionParsers(
        IndentedHelpFormatter(),
        IndentedRichHelpFormatter(),
        prog="PROG",
        description="-" * 120,
        epilog="%" * 120,
    )
    parsers.add_option("--very-long-option-name", metavar="LONG_METAVAR", help="." * 120)
    group_with_descriptions = parsers.add_option_group("Group", description="*" * 120)
    group_with_descriptions.add_option("--arg", help="#" * 120)

    expected_help_output = """\
    Usage: PROG [options]

    --------------------------------------------------------------------------------------------------
    ----------------------

    Options:
      -h, --help            show this help message and exit
      --very-long-option-name=LONG_METAVAR
                            ..........................................................................
                            ..............................................

      Group:
        ******************************************************************************************
        ******************************

        --arg=ARG           ##########################################################################
                            ##############################################

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %%%%%%%%%%%%%%%%%%%%%%
    """

    parsers.assert_format_help_equal(expected=dedent(expected_help_output))


@pytest.mark.xfail(reason="rich wraps differently")
def test_wrapping_compatible():
    # needs fixing rich wrapping to be compatible with textwrap.wrap
    parsers = OptionParsers(
        IndentedHelpFormatter(),
        IndentedRichHelpFormatter(),
        prog="PROG",
        description="some text " + "-" * 120,
    )
    parsers.assert_format_help_equal()


@pytest.mark.usefixtures("force_color")
def test_with_colors():
    parser = OptionParser(prog="PROG", formatter=IndentedRichHelpFormatter())
    parser.add_option("--file")
    parser.add_option("--hidden", help=SUPPRESS_HELP)
    parser.add_option("--flag", action="store_true", help="Is flag?")
    parser.add_option("--not-flag", action="store_true", help="Is not flag?")
    parser.add_option("-y", help="Yes.")
    parser.add_option("-n", help="No.")

    expected_help_output = """\
    \x1b[38;5;208mUsage:\x1b[0m PROG [options]

    \x1b[38;5;208mOptions:\x1b[0m
      \x1b[36m-h\x1b[0m, \x1b[36m--help\x1b[0m       \x1b[39mshow this help message and exit\x1b[0m
      \x1b[36m--file\x1b[0m=\x1b[38;5;36mFILE\x1b[0m
      \x1b[36m--flag\x1b[0m           \x1b[39mIs flag?\x1b[0m
      \x1b[36m--not-flag\x1b[0m       \x1b[39mIs not flag?\x1b[0m
      \x1b[36m-y\x1b[0m \x1b[38;5;36mY\x1b[0m             \x1b[39mYes.\x1b[0m
      \x1b[36m-n\x1b[0m \x1b[38;5;36mN\x1b[0m             \x1b[39mNo.\x1b[0m
    """
    assert parser.format_help() == dedent(expected_help_output)


@pytest.mark.parametrize("indent_increment", (1, 3))
@pytest.mark.parametrize("max_help_position", (25, 26, 27))
@pytest.mark.parametrize("width", (None, 70))
@pytest.mark.parametrize("short_first", (1, 0))
def test_help_formatter_args(indent_increment, max_help_position, width, short_first):
    parsers = OptionParsers(
        IndentedHelpFormatter(indent_increment, max_help_position, width, short_first),
        IndentedRichHelpFormatter(indent_increment, max_help_position, width, short_first),
        prog="PROG",
    )
    # Note: the length of the option string is chosen to test edge cases where it is less than,
    # equal to, and bigger than max_help_position
    parsers.add_option(
        "--option-of-certain-size", action="store_true", help="This is the help of the said option"
    )
    parsers.assert_format_help_equal()


def test_return_output():
    parser = OptionParser(prog="prog", formatter=IndentedRichHelpFormatter())
    assert parser.format_help()


@pytest.mark.usefixtures("force_color")
def test_text_highlighter():
    parser = OptionParser(prog="PROG", formatter=IndentedRichHelpFormatter())
    parser.add_option(
        "--arg", action="store_true", help="Did you try `RichHelpFormatter.highlighter`?"
    )

    expected_help_output = """\
    \x1b[38;5;208mUsage:\x1b[0m PROG [options]

    \x1b[38;5;208mOptions:\x1b[0m
      \x1b[36m-h\x1b[0m, \x1b[36m--help\x1b[0m  \x1b[39mshow this help message and exit\x1b[0m
      \x1b[36m--arg\x1b[0m       \x1b[39mDid you try `\x1b[0m\x1b[1;39mRichHelpFormatter.highlighter\x1b[0m\x1b[39m`?\x1b[0m
    """

    # Make sure we can use a style multiple times in regexes
    pattern_with_duplicate_style = r"'(?P<syntax>[^']*)'"
    RichHelpFormatter.highlights.append(pattern_with_duplicate_style)
    assert parser.format_help() == dedent(expected_help_output)
    RichHelpFormatter.highlights.remove(pattern_with_duplicate_style)


@pytest.mark.usefixtures("force_color")
def test_default_highlights():
    parser = OptionParser(
        "PROG",
        formatter=IndentedRichHelpFormatter(),
        description="Description with `syntax` and --options.",
        epilog="Epilog with `syntax` and --options.",
    )
    # syntax highlights
    parser.add_option("--syntax-normal", action="store_true", help="Start `middle` end")
    parser.add_option("--syntax-start", action="store_true", help="`Start` middle end")
    parser.add_option("--syntax-end", action="store_true", help="Start middle `end`")
    # --options highlights
    parser.add_option("--option-normal", action="store_true", help="Start --middle end")
    parser.add_option("--option-start", action="store_true", help="--Start middle end")
    parser.add_option("--option-end", action="store_true", help="Start middle --end")
    parser.add_option("--option-comma", action="store_true", help="Start --middle, end")
    parser.add_option("--option-multi", action="store_true", help="Start --middle-word end")
    parser.add_option("--option-not", action="store_true", help="Start middle-word end")
    parser.add_option("--option-short", action="store_true", help="Start -middle end")

    expected_help_output = """
    \x1b[39mDescription with `\x1b[0m\x1b[1;39msyntax\x1b[0m\x1b[39m` and \x1b[0m\x1b[36m--options\x1b[0m\x1b[39m.\x1b[0m

    \x1b[38;5;208mOptions:\x1b[0m
      \x1b[36m-h\x1b[0m, \x1b[36m--help\x1b[0m       \x1b[39mshow this help message and exit\x1b[0m
      \x1b[36m--syntax-normal\x1b[0m  \x1b[39mStart `\x1b[0m\x1b[1;39mmiddle\x1b[0m\x1b[39m` end\x1b[0m
      \x1b[36m--syntax-start\x1b[0m   \x1b[39m`\x1b[0m\x1b[1;39mStart\x1b[0m\x1b[39m` middle end\x1b[0m
      \x1b[36m--syntax-end\x1b[0m     \x1b[39mStart middle `\x1b[0m\x1b[1;39mend\x1b[0m\x1b[39m`\x1b[0m
      \x1b[36m--option-normal\x1b[0m  \x1b[39mStart \x1b[0m\x1b[36m--middle\x1b[0m\x1b[39m end\x1b[0m
      \x1b[36m--option-start\x1b[0m   \x1b[36m--Start\x1b[0m\x1b[39m middle end\x1b[0m
      \x1b[36m--option-end\x1b[0m     \x1b[39mStart middle \x1b[0m\x1b[36m--end\x1b[0m
      \x1b[36m--option-comma\x1b[0m   \x1b[39mStart \x1b[0m\x1b[36m--middle\x1b[0m\x1b[39m, end\x1b[0m
      \x1b[36m--option-multi\x1b[0m   \x1b[39mStart \x1b[0m\x1b[36m--middle-word\x1b[0m\x1b[39m end\x1b[0m
      \x1b[36m--option-not\x1b[0m     \x1b[39mStart middle-word end\x1b[0m
      \x1b[36m--option-short\x1b[0m   \x1b[39mStart \x1b[0m\x1b[36m-middle\x1b[0m\x1b[39m end\x1b[0m

    \x1b[39mEpilog with `\x1b[0m\x1b[1;39msyntax\x1b[0m\x1b[39m` and \x1b[0m\x1b[36m--options\x1b[0m\x1b[39m.\x1b[0m
    """
    assert parser.format_help().endswith(dedent(expected_help_output))


def test_empty_fields():
    orig_fmt = IndentedRichHelpFormatter()
    rich_fmt = IndentedRichHelpFormatter()
    assert rich_fmt.format_usage("") == orig_fmt.format_usage("")
    assert rich_fmt.format_heading("") == orig_fmt.format_heading("")
    assert rich_fmt.format_description("") == orig_fmt.format_description("")
    assert rich_fmt.format_epilog("") == orig_fmt.format_epilog("")

    parser = OptionParser()
    option = parser.add_option("--option")
    for fmt in (orig_fmt, rich_fmt):
        fmt.store_option_strings(parser)
        fmt.set_parser(parser)
    assert rich_fmt.format_option(option) == orig_fmt.format_option(option)

    option = parser.add_option("--option2", help="help")
    for fmt in (orig_fmt, rich_fmt):
        fmt.store_option_strings(parser)
        fmt.default_tag = None
    assert rich_fmt.format_option(option) == orig_fmt.format_option(option)


def test_titled_help_formatter():
    parsers = OptionParsers(
        TitledHelpFormatter(),
        TitledRichHelpFormatter(),
        prog="PROG",
        description="Description.",
        epilog="Epilog.",
    )
    parsers.add_option("--option", help="help")
    groups = parsers.add_option_group("Group")
    groups.add_option("-s", "--short", help="help")
    groups.add_option("-o", "-O", help="help")
    parsers.assert_format_help_equal()


@pytest.mark.usefixtures("force_color")
def test_titled_help_formatter_colors():
    parser = OptionParser(
        prog="PROG",
        description="Description.",
        epilog="Epilog.",
        formatter=TitledRichHelpFormatter(),
    )
    parser.add_option("--option", help="help")
    expected_help_output = """\
    \x1b[38;5;208mUsage\x1b[0m
    \x1b[38;5;208m=====\x1b[0m
      PROG [options]

    \x1b[39mDescription.\x1b[0m

    \x1b[38;5;208mOptions\x1b[0m
    \x1b[38;5;208m=======\x1b[0m
    \x1b[36m--help\x1b[0m, \x1b[36m-h\x1b[0m       \x1b[39mshow this help message and exit\x1b[0m
    \x1b[36m--option\x1b[0m=\x1b[38;5;36mOPTION\x1b[0m  \x1b[39mhelp\x1b[0m

    \x1b[39mEpilog.\x1b[0m
    """
    assert parser.format_help() == dedent(expected_help_output)


def test_rich_lazy_import():
    sys_modules_no_rich = {
        mod_name: mod
        for mod_name, mod in sys.modules.items()
        if mod_name != "rich" and not mod_name.startswith("rich.")
    }
    lazy_rich = {k: v for k, v in r.__dict__.items() if k not in r.__all__}
    with patch.dict(sys.modules, sys_modules_no_rich, clear=True), patch.dict(
        r.__dict__, lazy_rich, clear=True
    ):
        parser = OptionParser(formatter=IndentedRichHelpFormatter())
        parser.add_option("--foo", help="foo help")
        values, args = parser.parse_args(["--foo", "bar"])
        assert values.foo == "bar"
        assert not args
        assert sys.modules
        assert "rich" not in sys.modules  # no help formatting, do not import rich
        for mod_name in sys.modules:
            assert not mod_name.startswith("rich.")
        parser.format_help()
        assert "rich" in sys.modules  # format help has been called

    formatter = IndentedRichHelpFormatter()
    assert formatter._console is None
    formatter.console = get_console()
    assert formatter._console is not None

    with pytest.raises(AttributeError, match="Foo"):
        _ = r.Foo


@pytest.mark.skipif(sys.platform != "win32", reason="windows-only test")
@pytest.mark.usefixtures("force_color")
@pytest.mark.parametrize(
    ("legacy_console", "old_windows", "colors"),
    (
        pytest.param(True, False, True, id="legacy_console-new_windows"),
        pytest.param(True, True, False, id="legacy_console-old_windows"),
        pytest.param(False, None, True, id="new_console"),
    ),
)
def test_legacy_windows(legacy_console, old_windows, colors):  # pragma: win32 cover
    expected_output = {
        False: """\
        Usage: PROG [options]

        Options:
          -h, --help  show this help message and exit
        """,
        True: """\
        \x1b[38;5;208mUsage:\x1b[0m PROG [options]

        \x1b[38;5;208mOptions:\x1b[0m
          \x1b[36m-h\x1b[0m, \x1b[36m--help\x1b[0m  \x1b[39mshow this help message and exit\x1b[0m
        """,
    }[colors]

    init_win_colors = Mock(return_value=not old_windows)
    parser = OptionParser(prog="PROG", formatter=IndentedRichHelpFormatter())
    with patch("rich.console.detect_legacy_windows", return_value=legacy_console), patch(
        "rich_argparse._common._initialize_win_colors", init_win_colors
    ):
        assert parser.format_help() == dedent(expected_output)
    if legacy_console:
        init_win_colors.assert_called_with()
    else:
        init_win_colors.assert_not_called()


@pytest.mark.parametrize(
    ("formatter", "description", "nb_o", "expected"),
    (
        pytest.param(
            IndentedRichHelpFormatter(),
            None,
            2,
            """\
            \x1b[38;5;208mUsage:\x1b[0m \x1b[38;5;244mPROG\x1b[0m [\x1b[36m-h\x1b[0m] [\x1b[36m--foo\x1b[0m \x1b[38;5;36mFOO\x1b[0m]

            \x1b[38;5;208mOptions:\x1b[0m
              \x1b[36m-h\x1b[0m, \x1b[36m--help\x1b[0m  \x1b[39mshow this help message and exit\x1b[0m
              \x1b[36m--foo\x1b[0m=\x1b[38;5;36mFOO\x1b[0m   \x1b[39mfoo help\x1b[0m
            """,
            id="indented",
        ),
        pytest.param(
            IndentedRichHelpFormatter(),
            "A description.",
            2,
            """\
            \x1b[38;5;208mUsage:\x1b[0m \x1b[38;5;244mPROG\x1b[0m [\x1b[36m-h\x1b[0m] [\x1b[36m--foo\x1b[0m \x1b[38;5;36mFOO\x1b[0m]

            \x1b[39mA description.\x1b[0m

            \x1b[38;5;208mOptions:\x1b[0m
              \x1b[36m-h\x1b[0m, \x1b[36m--help\x1b[0m  \x1b[39mshow this help message and exit\x1b[0m
              \x1b[36m--foo\x1b[0m=\x1b[38;5;36mFOO\x1b[0m   \x1b[39mfoo help\x1b[0m
            """,
            id="indented-desc",
        ),
        pytest.param(
            IndentedRichHelpFormatter(),
            None,
            30,
            """\
            \x1b[38;5;208mUsage:\x1b[0m \x1b[38;5;244mPROG\x1b[0m [\x1b[36m-h\x1b[0m]
                        [\x1b[36m--foooooooooooooooooooooooooooooo\x1b[0m \x1b[38;5;36mFOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO\x1b[0m]

            \x1b[38;5;208mOptions:\x1b[0m
              \x1b[36m-h\x1b[0m, \x1b[36m--help\x1b[0m            \x1b[39mshow this help message and exit\x1b[0m
              \x1b[36m--foooooooooooooooooooooooooooooo\x1b[0m=\x1b[38;5;36mFOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO\x1b[0m
                                    \x1b[39mfoo help\x1b[0m
            """,
            id="indented-long",
        ),
        pytest.param(
            TitledRichHelpFormatter(),
            None,
            2,
            """\
            \x1b[38;5;208mUsage\x1b[0m
            \x1b[38;5;208m=====\x1b[0m
              \x1b[38;5;244mPROG\x1b[0m [\x1b[36m-h\x1b[0m] [\x1b[36m--foo\x1b[0m \x1b[38;5;36mFOO\x1b[0m]

            \x1b[38;5;208mOptions\x1b[0m
            \x1b[38;5;208m=======\x1b[0m
            \x1b[36m--help\x1b[0m, \x1b[36m-h\x1b[0m  \x1b[39mshow this help message and exit\x1b[0m
            \x1b[36m--foo\x1b[0m=\x1b[38;5;36mFOO\x1b[0m   \x1b[39mfoo help\x1b[0m
            """,
            id="titled",
        ),
    ),
)
@pytest.mark.usefixtures("force_color")
def test_generated_usage(formatter, description, nb_o, expected):
    parser = OptionParser(
        prog="PROG", formatter=formatter, usage=GENERATE_USAGE, description=description
    )
    parser.add_option("--f" + "o" * nb_o, help="foo help")
    parser.add_option("--bar", help=SUPPRESS_HELP)
    assert parser.format_help() == dedent(expected)


def test_generated_usage_no_parser():
    formatter = IndentedRichHelpFormatter()
    with pytest.raises(TypeError) as exc_info:
        formatter.format_usage(GENERATE_USAGE)
    assert str(exc_info.value) == "Cannot generate usage if parser is not set"