fork/mons

git clone https://git.julia.blue/fork/mons

coloursofnoiseAdd tests to cover new clickExt termui functions4ac910e

misc-fixes
11.5 KiB402 linesraw
1import itertools
2import os
3import shutil
4from urllib.parse import urlparse
5
6import click._termui_impl
7import pytest
8from click.testing import CliRunner
9
10from mons import clickExt
11from mons import install
12
13
14def test_confirm_ext(runner: CliRunner, test_name):
15    @click.command
16    @clickExt.yes_option()
17    @clickExt.force_option()
18    @click.option("--dangerous", is_flag=True)
19    def cli(dangerous):
20        return clickExt.confirm_ext(test_name, default=True, dangerous=dangerous)
21
22    result = runner.invoke(cli)
23    assert result.exception
24    assert "Error: Could not read from stdin" in result.output
25    assert "Use '--yes' to skip confirmation prompts." in result.output
26
27    result = runner.invoke(cli, ["--yes"], standalone_mode=False)
28    assert not result.exception
29    assert not result.output
30    assert result.return_value
31
32    result = runner.invoke(cli, ["--yes", "--dangerous"])
33    assert result.exception
34    assert "Error: Could not read from stdin" in result.output
35    assert "Use '--force' to skip error prompts." in result.output
36
37    result = runner.invoke(cli, ["--force"], standalone_mode=False)
38    assert not result.exception
39    assert not result.output
40    assert result.return_value
41
42    result = runner.invoke(cli, ["--force", "--dangerous"], standalone_mode=False)
43    assert not result.exception
44    assert not result.output
45    assert result.return_value
46
47
48_test_text_lines = """\
49mul
50ti
51ple
52
53li
54n
55es
56"""
57
58"""
59we want to verify when text will "overflow" into the pager, and how many lines will be output.
60for testing purposes, if the text overflows there will be no output.
61
62given `text`:
63```
64AAAAAAAAAA (A*10)
65
66AA
67
68AAAAAA (A*6)
69```
70and `(cols, rows)`, `lines` (lines + 1 because of \n):
71```
72(1, 1), 0
73(1, 100), len(text)
74(100, 1), 1
75``
76"""
77
78_echo_via_pager_text = """\
79AAAAAAAAAA{_ansi}
80
81AA
82{_ansi}
83AAAAAA
84{_ansi}"""
85"""
865 lines (6 with implicit ending nl)
8744 chars (23 printable)
88
89max printable line length: 10
90"""
91
92_echo_via_pager_text_lines = _echo_via_pager_text.count("\n") + 1
93
94
95@pytest.mark.parametrize(
96    ("term_size", "expect_output"),
97    [
98        # extremes
99        ((1, 1), False),
100        ((99, 1), False),
101        ((1, 99), True),
102        ((99, 99), True),
103        # Just big enough
104        ((10, 6), True),
105        # Split twice (two lines split once)
106        ((5, 7), False),
107        ((5, 8), True),
108        # Split three times (first line split twice)
109        ((4, 8), False),
110        ((4, 9), True),
111    ],
112    ids=lambda val: str(val),
113)
114def test_echo_via_pager(monkeypatch, capfd, term_size, expect_output):
115    monkeypatch.setattr(click, "echo_via_pager", lambda *args, **kwargs: None)
116
117    # Don't mess with pytest internals
118    with monkeypatch.context() as m:
119        m.setattr(shutil, "get_terminal_size", lambda: os.terminal_size(term_size))
120
121        clickExt.echo_via_pager(
122            [
123                _echo_via_pager_text.format(
124                    _ansi=click.style("", fg="green", italic=True)
125                )
126            ]
127        )
128
129    out, err = capfd.readouterr()
130    assert not err
131    if expect_output:
132        assert len(out.splitlines(keepends=True)) == _echo_via_pager_text_lines
133    else:
134        assert out == ""
135
136
137@pytest.mark.parametrize(
138    ("input", "expect"),
139    [
140        ("5", (0,)),
141        (("1 2 3 4 5", True), (0, 1, 2, 3, 4)),
142        (("1-3,2-4", True), (0, 1, 2, 3)),
143        (("2-1, 5-4", True), (0, 1, 3, 4)),
144        (("1-3 ^2 ^3-4 5", True), (0, 4)),
145        (("one four five", True), (0, 3, 4)),
146        (("1-2 ^1-2 four", True), (3,)),
147        (("1\t2   3      4\t\t  \t5", True), (0, 1, 2, 3, 4)),
148        (("1 2,3, 4,\t5,", True), (0, 1, 2, 3, 4)),
149        ("", ()),
150        ("1-2-3,,32,...lkejgrerg", ()),
151        ("    \t   ", ()),
152        # case-insensitive matching has to be implemented through the find_index parameter
153        (("One, two, FOUR", True), (1,)),
154    ],
155    ids=lambda v: f"('{v}')" if isinstance(v, str) else str(v),
156)
157def test_prompt_selections(runner, input, expect):
158    reverse = False
159    if isinstance(input, tuple):
160        input, reverse = input
161    expect = set(expect)
162
163    @click.command()
164    def cli():
165        selections = [
166            "one",
167            "two",
168            "three",
169            "four",
170            "five",
171        ]
172
173        def find_index(v):
174            try:
175                return selections.index(v)
176            except ValueError:
177                return None
178
179        return clickExt.prompt_selections(
180            selections, reverse=reverse, find_index=find_index
181        )
182
183    result = runner.invoke(cli, input=input, standalone_mode=False)
184    assert result.return_value == expect
185
186
187@pytest.mark.prioritize
188def test_type_cast_value(ctx, test_name):
189    assert clickExt.type_cast_value(ctx, click.STRING, test_name) == test_name
190    with pytest.raises(click.BadParameter):
191        clickExt.type_cast_value(ctx, click.INT, test_name)
192
193
194def color_cmd():
195    @click.command()
196    @clickExt.color_option()
197    def cmd(color):
198        return color
199
200    return cmd
201
202
203@pytest.mark.parametrize(
204    ("color_arg", "output"),
205    [
206        ("auto", None),
207        ("always", True),
208        ("never", False),
209    ],
210)
211def test_color_option(runner, color_arg, output):
212    result = runner.invoke(color_cmd(), ["--color", color_arg], standalone_mode=False)
213    assert result.exit_code == 0, result.output
214    assert output == result.return_value
215
216
217@pytest.mark.parametrize(("env", "output"), [({}, None), ({"NO_COLOR": "1"}, False)])
218def test_color_option_auto(runner, env, output):
219    result = runner.invoke(color_cmd(), env=env, standalone_mode=False)
220    assert result.exit_code == 0, result.output
221    assert output == result.return_value
222
223
224def test_color_option_bad(runner):
225    result = runner.invoke(color_cmd(), ["--color", "invalid"], standalone_mode=False)
226    assert isinstance(result.exception, click.BadParameter)
227    assert "Possible values: auto, never, always" in result.exception.message
228
229
230class Fake_UserInfo:
231    def __init__(self, installs) -> None:
232        self.installs = installs
233
234
235def parametrize_bools(*args: str, filter_cond=None):
236    def filter_param(param):
237        return not filter_cond or filter_cond(
238            **{arg: val for arg, val in zip(args, param.values)}
239        )
240
241    params = (
242        pytest.param(*i, id=", ".join(itertools.compress(args, i)))
243        for i in itertools.product([False, True], repeat=len(args))
244    )
245
246    params = filter(filter_param, params)
247    return pytest.mark.parametrize(args, params)
248
249
250@parametrize_bools(
251    "exist",
252    "resolve_install",
253    "check_path",
254    filter_cond=lambda exist, resolve_install, **k: not (resolve_install and not exist),
255)
256def test_install_paramtype(
257    monkeypatch,
258    test_name,
259    tmp_path,
260    ctx,
261    exist: bool,
262    resolve_install: bool,
263    check_path,
264):
265    monkeypatch.setattr(clickExt, "UserInfo", Fake_UserInfo)
266    install_path = os.path.join(tmp_path, test_name)
267    if check_path:
268        os.mkdir(install_path)
269        open(os.path.join(install_path, "Celeste.exe"), "x").close()
270    installs = {test_name: install.Install(test_name, install_path)} if exist else {}
271    ctx.obj = Fake_UserInfo(installs)
272    result = clickExt.type_cast_value(
273        ctx,
274        clickExt.Install(
275            exist=exist, resolve_install=resolve_install, check_path=check_path
276        ),
277        test_name,
278    )
279    if resolve_install:
280        assert isinstance(result, install.Install)
281        assert result.name == test_name
282    else:
283        assert result == test_name
284
285
286def test_install_paramtype_fail(monkeypatch, test_name, tmp_path, ctx):
287    monkeypatch.setattr(clickExt, "UserInfo", Fake_UserInfo)
288    install_path = os.path.join(tmp_path, test_name)
289    installs = {test_name: install.Install(test_name, install_path)}
290    ctx.obj = Fake_UserInfo(installs)
291
292    def test_install(value, **kwargs):
293        return clickExt.type_cast_value(ctx, clickExt.Install(**kwargs), value)
294
295    with pytest.raises(ValueError):
296        clickExt.Install(exist=False, resolve_install=True)
297    with pytest.raises(click.ClickException, match="does not have a valid path"):
298        test_install(test_name, check_path=True)
299    with pytest.raises(click.BadParameter, match="does not exist"):
300        test_install(test_name + "_doesnotexist", exist=True, check_path=False)
301    with pytest.raises(click.BadParameter, match="already exists"):
302        test_install(test_name, exist=False)
303
304
305@pytest.mark.parametrize(
306    ("url_arg", "expect"),
307    [
308        ("https://mons.coloursofnoise.ca/file", "{url_arg}"),
309        ("mons.coloursofnoise.ca/file", "file://{url_arg}"),
310    ],
311)
312def test_url_type(runner, url_arg, expect):
313    cmd = click.Command(
314        "cmd",
315        params=[click.Argument(["url"], type=clickExt.URL(default_scheme="file"))],
316        callback=lambda url: url,
317    )
318    result = runner.invoke(cmd, [url_arg], standalone_mode=False)
319    assert not result.exception, result.output
320    assert result.return_value == urlparse(expect.format(url_arg=url_arg))
321
322
323@pytest.mark.parametrize(
324    ("param_args", "err"),
325    [
326        ({"valid_schemes": ["file"]}, "URI scheme 'https' not allowed"),
327        ({"require_path": True}, "Path component required"),
328    ],
329)
330def test_url_type_bad(runner, param_args, err):
331    cmd = click.Command(
332        "cmd", params=[click.Argument(["url"], type=clickExt.URL(**param_args))]
333    )
334    result = runner.invoke(cmd, ["https://mons.coloursofnoise.ca"])
335    assert result.exception
336    assert err in result.output
337
338
339class TestCommandExt:
340    @pytest.mark.parametrize(
341        ("args", "expect"), [([], None), (["--opt"], True), (["--opt=value"], "value")]
342    )
343    def test_default_option(self, runner, args, expect):
344        cmd = clickExt.CommandExt(
345            "cmd",
346            params=[
347                clickExt.ExplicitOption(["--opt"]),
348                clickExt.DefaultOption(["--opt"], is_flag=True),
349            ],
350            callback=lambda opt_default, opt: opt_default or opt,
351        )
352
353        result = runner.invoke(cmd, args, standalone_mode=False)
354        assert result.return_value == expect
355
356    def test_placeholder(self, runner):
357        cmd = clickExt.CommandExt("cmd", params=[clickExt.PlaceHolder(["placeholder"])])
358
359        result = runner.invoke(cmd, standalone_mode=False)
360        assert not result.exception
361
362    @pytest.mark.parametrize(
363        ("default", "exception"),
364        [
365            (None, click.MissingParameter),
366            (lambda: None, click.MissingParameter),
367            ("A Value", None),
368            (lambda: "A Value", None),
369        ],
370    )
371    def test_optionalarg(self, runner, default, exception):
372        cmd = clickExt.CommandExt(
373            "cmd", params=[clickExt.OptionalArg(["arg"], default=default)]
374        )
375
376        result = runner.invoke(cmd, standalone_mode=False)
377        assert exception is None or isinstance(result.exception, exception)
378
379    def test_help(self, runner):
380        @click.command(
381            cls=clickExt.CommandExt,
382            usages=[
383                ["PRIMARY", "USAGE"],
384                ["SECONDARY", "USAGE"],
385            ],
386            meta_options={
387                "Option Category": [
388                    (
389                        "--special-option",
390                        "Special option description.",
391                    ),
392                ]
393            },
394        )
395        @click.option("--flag-metavar", metavar="FLAG_METAVAR", is_flag=True)
396        def cli():
397            """Standard help message."""
398
399        result = runner.invoke(cli, "--help")
400        assert ("SECONDARY USAGE") in result.output
401        assert ("--special-option") in result.output
402        assert ("FLAG_METAVAR") in result.output