Skip to content
Myr

test_others.py

This file

Path

tests/test_others.py

277 lines 路 8.4 KiB 路 Python

Last changed by

馃悰 Fix `shell_complete` not working for Arguments (#737)Brian Kohanbefore adoptiondcb45b1

History of this file

Take it

1import os2import subprocess3import sys4import typing5from pathlib import Path6from unittest import mock78import click9import pytest10import shellingham11import typer12import typer.completion13from typer.core import _split_opt14from typer.main import solve_typer_info_defaults, solve_typer_info_help15from typer.models import ParameterInfo, TyperInfo16from typer.testing import CliRunner1718runner = CliRunner()192021def test_help_from_info():22    # Mainly for coverage/completeness23    value = solve_typer_info_help(TyperInfo())24    assert value is None252627def test_defaults_from_info():28    # Mainly for coverage/completeness29    value = solve_typer_info_defaults(TyperInfo())30    assert value313233def test_too_many_parsers():34    def custom_parser(value: str) -> int:35        return int(value)  # pragma: no cover3637    class CustomClickParser(click.ParamType):38        name = "custom_parser"3940        def convert(41            self,42            value: str,43            param: typing.Optional[click.Parameter],44            ctx: typing.Optional[click.Context],45        ) -> typing.Any:46            return int(value)  # pragma: no cover4748    expected_error = (49        "Multiple custom type parsers provided. "50        "`parser` and `click_type` may not both be provided."51    )5253    with pytest.raises(ValueError, match=expected_error):54        ParameterInfo(parser=custom_parser, click_type=CustomClickParser())555657def test_valid_parser_permutations():58    def custom_parser(value: str) -> int:59        return int(value)  # pragma: no cover6061    class CustomClickParser(click.ParamType):62        name = "custom_parser"6364        def convert(65            self,66            value: str,67            param: typing.Optional[click.Parameter],68            ctx: typing.Optional[click.Context],69        ) -> typing.Any:70            return int(value)  # pragma: no cover7172    ParameterInfo()73    ParameterInfo(parser=custom_parser)74    ParameterInfo(click_type=CustomClickParser())757677def test_install_invalid_shell():78    app = typer.Typer()7980    @app.command()81    def main():82        print("Hello World")8384    with mock.patch.object(85        shellingham, "detect_shell", return_value=("xshell", "/usr/bin/xshell")86    ):87        result = runner.invoke(app, ["--install-completion"])88        assert "Shell xshell is not supported." in result.stdout89    result = runner.invoke(app)90    assert "Hello World" in result.stdout919293def test_callback_too_many_parameters():94    app = typer.Typer()9596    def name_callback(ctx, param, val1, val2):97        pass  # pragma: no cover9899    @app.command()100    def main(name: str = typer.Option(..., callback=name_callback)):101        pass  # pragma: no cover102103    with pytest.raises(click.ClickException) as exc_info:104        runner.invoke(app, ["--name", "Camila"])105    assert (106        exc_info.value.message == "Too many CLI parameter callback function parameters"107    )108109110def test_callback_2_untyped_parameters():111    app = typer.Typer()112113    def name_callback(ctx, value):114        print(f"info name is: {ctx.info_name}")115        print(f"value is: {value}")116117    @app.command()118    def main(name: str = typer.Option(..., callback=name_callback)):119        print("Hello World")120121    result = runner.invoke(app, ["--name", "Camila"])122    assert "info name is: main" in result.stdout123    assert "value is: Camila" in result.stdout124125126def test_callback_3_untyped_parameters():127    app = typer.Typer()128129    def name_callback(ctx, param, value):130        print(f"info name is: {ctx.info_name}")131        print(f"param name is: {param.name}")132        print(f"value is: {value}")133134    @app.command()135    def main(name: str = typer.Option(..., callback=name_callback)):136        print("Hello World")137138    result = runner.invoke(app, ["--name", "Camila"])139    assert "info name is: main" in result.stdout140    assert "param name is: name" in result.stdout141    assert "value is: Camila" in result.stdout142143144def test_completion_argument():145    file_path = Path(__file__).parent / "assets/completion_argument.py"146    result = subprocess.run(147        [sys.executable, "-m", "coverage", "run", str(file_path), "E"],148        capture_output=True,149        encoding="utf-8",150        env={151            **os.environ,152            "_COMPLETION_ARGUMENT.PY_COMPLETE": "complete_zsh",153            "_TYPER_COMPLETE_ARGS": "completion_argument.py E",154            "_TYPER_COMPLETE_TESTING": "True",155        },156    )157    assert "Emma" in result.stdout or "_files" in result.stdout158    assert "ctx: completion_argument" in result.stderr159    assert "arg is: name" in result.stderr160    assert "incomplete is: E" in result.stderr161162163def test_completion_untyped_parameters():164    file_path = Path(__file__).parent / "assets/completion_no_types.py"165    result = subprocess.run(166        [sys.executable, "-m", "coverage", "run", str(file_path)],167        capture_output=True,168        encoding="utf-8",169        env={170            **os.environ,171            "_COMPLETION_NO_TYPES.PY_COMPLETE": "complete_zsh",172            "_TYPER_COMPLETE_ARGS": "completion_no_types.py --name Sebastian --name Ca",173        },174    )175    assert "info name is: completion_no_types.py" in result.stderr176    assert "args is: []" in result.stderr177    assert "incomplete is: Ca" in result.stderr178    assert '"Camila":"The reader of books."' in result.stdout179    assert '"Carlos":"The writer of scripts."' in result.stdout180181    result = subprocess.run(182        [sys.executable, "-m", "coverage", "run", str(file_path)],183        capture_output=True,184        encoding="utf-8",185    )186    assert "Hello World" in result.stdout187188189def test_completion_untyped_parameters_different_order_correct_names():190    file_path = Path(__file__).parent / "assets/completion_no_types_order.py"191    result = subprocess.run(192        [sys.executable, "-m", "coverage", "run", str(file_path)],193        capture_output=True,194        encoding="utf-8",195        env={196            **os.environ,197            "_COMPLETION_NO_TYPES_ORDER.PY_COMPLETE": "complete_zsh",198            "_TYPER_COMPLETE_ARGS": "completion_no_types_order.py --name Sebastian --name Ca",199        },200    )201    assert "info name is: completion_no_types_order.py" in result.stderr202    assert "args is: []" in result.stderr203    assert "incomplete is: Ca" in result.stderr204    assert '"Camila":"The reader of books."' in result.stdout205    assert '"Carlos":"The writer of scripts."' in result.stdout206207    result = subprocess.run(208        [sys.executable, "-m", "coverage", "run", str(file_path)],209        capture_output=True,210        encoding="utf-8",211    )212    assert "Hello World" in result.stdout213214215def test_autocompletion_too_many_parameters():216    app = typer.Typer()217218    def name_callback(ctx, args, incomplete, val2):219        pass  # pragma: no cover220221    @app.command()222    def main(name: str = typer.Option(..., autocompletion=name_callback)):223        pass  # pragma: no cover224225    with pytest.raises(click.ClickException) as exc_info:226        runner.invoke(app, ["--name", "Camila"])227    assert exc_info.value.message == "Invalid autocompletion callback parameters: val2"228229230def test_forward_references():231    app = typer.Typer()232233    @app.command()234    def main(arg1, arg2: int, arg3: "int", arg4: bool = False, arg5: "bool" = False):235        print(f"arg1: {type(arg1)} {arg1}")236        print(f"arg2: {type(arg2)} {arg2}")237        print(f"arg3: {type(arg3)} {arg3}")238        print(f"arg4: {type(arg4)} {arg4}")239        print(f"arg5: {type(arg5)} {arg5}")240241    result = runner.invoke(app, ["Hello", "2", "invalid"])242243    assert "Invalid value for 'ARG3': 'invalid' is not a valid integer" in result.stdout244    result = runner.invoke(app, ["Hello", "2", "3", "--arg4", "--arg5"])245    assert (246        "arg1: <class 'str'> Hello\narg2: <class 'int'> 2\narg3: <class 'int'> 3\narg4: <class 'bool'> True\narg5: <class 'bool'> True\n"247        in result.stdout248    )249250251def test_context_settings_inheritance_single_command():252    app = typer.Typer(context_settings={"help_option_names": ["-h", "--help"]})253254    @app.command()255    def main(name: str):256        pass  # pragma: no cover257258    result = runner.invoke(app, ["main", "-h"])259    assert "Show this message and exit." in result.stdout260261262def test_split_opt():263    prefix, opt = _split_opt("--verbose")264    assert prefix == "--"265    assert opt == "verbose"266267    prefix, opt = _split_opt("//verbose")268    assert prefix == "//"269    assert opt == "verbose"270271    prefix, opt = _split_opt("-verbose")272    assert prefix == "-"273    assert opt == "verbose"274275    prefix, opt = _split_opt("verbose")276    assert prefix == ""277    assert opt == "verbose"