Skip to content
Myr

test_others.py

This file

Path

tests/test_others.py

323 lines · 9.5 KiB · Python

Last changed by

🐛 Fix list convertor with an empty list default factory (#1350)Sofie Van Landeghembefore adoptionf34aa4a

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 CliRunner17from typing_extensions import Annotated1819from .utils import requires_completion_permission2021runner = CliRunner()222324def test_help_from_info():25    # Mainly for coverage/completeness26    value = solve_typer_info_help(TyperInfo())27    assert value is None282930def test_defaults_from_info():31    # Mainly for coverage/completeness32    value = solve_typer_info_defaults(TyperInfo())33    assert value343536def test_too_many_parsers():37    def custom_parser(value: str) -> int:38        return int(value)  # pragma: no cover3940    class CustomClickParser(click.ParamType):41        name = "custom_parser"4243        def convert(44            self,45            value: str,46            param: typing.Optional[click.Parameter],47            ctx: typing.Optional[click.Context],48        ) -> typing.Any:49            return int(value)  # pragma: no cover5051    expected_error = (52        "Multiple custom type parsers provided. "53        "`parser` and `click_type` may not both be provided."54    )5556    with pytest.raises(ValueError, match=expected_error):57        ParameterInfo(parser=custom_parser, click_type=CustomClickParser())585960def test_valid_parser_permutations():61    def custom_parser(value: str) -> int:62        return int(value)  # pragma: no cover6364    class CustomClickParser(click.ParamType):65        name = "custom_parser"6667        def convert(68            self,69            value: str,70            param: typing.Optional[click.Parameter],71            ctx: typing.Optional[click.Context],72        ) -> typing.Any:73            return int(value)  # pragma: no cover7475    ParameterInfo()76    ParameterInfo(parser=custom_parser)77    ParameterInfo(click_type=CustomClickParser())787980@requires_completion_permission81def test_install_invalid_shell():82    app = typer.Typer()8384    @app.command()85    def main():86        print("Hello World")8788    with mock.patch.object(89        shellingham, "detect_shell", return_value=("xshell", "/usr/bin/xshell")90    ):91        result = runner.invoke(app, ["--install-completion"])92        assert "Shell xshell is not supported." in result.stdout93    result = runner.invoke(app)94    assert "Hello World" in result.stdout959697def test_callback_too_many_parameters():98    app = typer.Typer()99100    def name_callback(ctx, param, val1, val2):101        pass  # pragma: no cover102103    @app.command()104    def main(name: str = typer.Option(..., callback=name_callback)):105        pass  # pragma: no cover106107    with pytest.raises(click.ClickException) as exc_info:108        runner.invoke(app, ["--name", "Camila"])109    assert (110        exc_info.value.message == "Too many CLI parameter callback function parameters"111    )112113114def test_callback_2_untyped_parameters():115    app = typer.Typer()116117    def name_callback(ctx, value):118        print(f"info name is: {ctx.info_name}")119        print(f"value is: {value}")120121    @app.command()122    def main(name: str = typer.Option(..., callback=name_callback)):123        print("Hello World")124125    result = runner.invoke(app, ["--name", "Camila"])126    assert "info name is: main" in result.stdout127    assert "value is: Camila" in result.stdout128129130def test_callback_3_untyped_parameters():131    app = typer.Typer()132133    def name_callback(ctx, param, value):134        print(f"info name is: {ctx.info_name}")135        print(f"param name is: {param.name}")136        print(f"value is: {value}")137138    @app.command()139    def main(name: str = typer.Option(..., callback=name_callback)):140        print("Hello World")141142    result = runner.invoke(app, ["--name", "Camila"])143    assert "info name is: main" in result.stdout144    assert "param name is: name" in result.stdout145    assert "value is: Camila" in result.stdout146147148def test_callback_4_list_none():149    app = typer.Typer()150151    def names_callback(ctx, param, values: typing.Optional[typing.List[str]]):152        if values is None:153            return values154        return [value.upper() for value in values]155156    @app.command()157    def main(158        names: typing.Optional[typing.List[str]] = typer.Option(159            None, "--name", callback=names_callback160        ),161    ):162        if names is None:163            print("Hello World")164        else:165            print(f"Hello {', '.join(names)}")166167    result = runner.invoke(app, ["--name", "Sideshow", "--name", "Bob"])168    assert "Hello SIDESHOW, BOB" in result.stdout169170    result = runner.invoke(app, [])171    assert "Hello World" in result.stdout172173174def test_empty_list_default_generator():175    def empty_list() -> typing.List[str]:176        return []177178    app = typer.Typer()179180    @app.command()181    def main(182        names: Annotated[typing.List[str], typer.Option(default_factory=empty_list)],183    ):184        print(names)185186    result = runner.invoke(app)187    assert "[]" in result.output188189190def test_completion_argument():191    file_path = Path(__file__).parent / "assets/completion_argument.py"192    result = subprocess.run(193        [sys.executable, "-m", "coverage", "run", str(file_path), "E"],194        capture_output=True,195        encoding="utf-8",196        env={197            **os.environ,198            "_COMPLETION_ARGUMENT.PY_COMPLETE": "complete_zsh",199            "_TYPER_COMPLETE_ARGS": "completion_argument.py E",200            "_TYPER_COMPLETE_TESTING": "True",201        },202    )203    assert "Emma" in result.stdout or "_files" in result.stdout204    assert "ctx: completion_argument" in result.stderr205    assert "arg is: name" in result.stderr206    assert "incomplete is: E" in result.stderr207208209def test_completion_untyped_parameters():210    file_path = Path(__file__).parent / "assets/completion_no_types.py"211    result = subprocess.run(212        [sys.executable, "-m", "coverage", "run", str(file_path)],213        capture_output=True,214        encoding="utf-8",215        env={216            **os.environ,217            "_COMPLETION_NO_TYPES.PY_COMPLETE": "complete_zsh",218            "_TYPER_COMPLETE_ARGS": "completion_no_types.py --name Sebastian --name Ca",219        },220    )221    assert "info name is: completion_no_types.py" in result.stderr222    assert "args is: []" in result.stderr223    assert "incomplete is: Ca" in result.stderr224    assert '"Camila":"The reader of books."' in result.stdout225    assert '"Carlos":"The writer of scripts."' in result.stdout226227    result = subprocess.run(228        [sys.executable, "-m", "coverage", "run", str(file_path)],229        capture_output=True,230        encoding="utf-8",231    )232    assert "Hello World" in result.stdout233234235def test_completion_untyped_parameters_different_order_correct_names():236    file_path = Path(__file__).parent / "assets/completion_no_types_order.py"237    result = subprocess.run(238        [sys.executable, "-m", "coverage", "run", str(file_path)],239        capture_output=True,240        encoding="utf-8",241        env={242            **os.environ,243            "_COMPLETION_NO_TYPES_ORDER.PY_COMPLETE": "complete_zsh",244            "_TYPER_COMPLETE_ARGS": "completion_no_types_order.py --name Sebastian --name Ca",245        },246    )247    assert "info name is: completion_no_types_order.py" in result.stderr248    assert "args is: []" in result.stderr249    assert "incomplete is: Ca" in result.stderr250    assert '"Camila":"The reader of books."' in result.stdout251    assert '"Carlos":"The writer of scripts."' in result.stdout252253    result = subprocess.run(254        [sys.executable, "-m", "coverage", "run", str(file_path)],255        capture_output=True,256        encoding="utf-8",257    )258    assert "Hello World" in result.stdout259260261def test_autocompletion_too_many_parameters():262    app = typer.Typer()263264    def name_callback(ctx, args, incomplete, val2):265        pass  # pragma: no cover266267    @app.command()268    def main(name: str = typer.Option(..., autocompletion=name_callback)):269        pass  # pragma: no cover270271    with pytest.raises(click.ClickException) as exc_info:272        runner.invoke(app, ["--name", "Camila"])273    assert exc_info.value.message == "Invalid autocompletion callback parameters: val2"274275276def test_forward_references():277    app = typer.Typer()278279    @app.command()280    def main(arg1, arg2: int, arg3: "int", arg4: bool = False, arg5: "bool" = False):281        print(f"arg1: {type(arg1)} {arg1}")282        print(f"arg2: {type(arg2)} {arg2}")283        print(f"arg3: {type(arg3)} {arg3}")284        print(f"arg4: {type(arg4)} {arg4}")285        print(f"arg5: {type(arg5)} {arg5}")286287    result = runner.invoke(app, ["Hello", "2", "invalid"])288289    assert "Invalid value for 'ARG3': 'invalid' is not a valid integer" in result.output290    result = runner.invoke(app, ["Hello", "2", "3", "--arg4", "--arg5"])291    assert (292        "arg1: <class 'str'> Hello\narg2: <class 'int'> 2\narg3: <class 'int'> 3\narg4: <class 'bool'> True\narg5: <class 'bool'> True\n"293        in result.stdout294    )295296297def test_context_settings_inheritance_single_command():298    app = typer.Typer(context_settings={"help_option_names": ["-h", "--help"]})299300    @app.command()301    def main(name: str):302        pass  # pragma: no cover303304    result = runner.invoke(app, ["main", "-h"])305    assert "Show this message and exit." in result.stdout306307308def test_split_opt():309    prefix, opt = _split_opt("--verbose")310    assert prefix == "--"311    assert opt == "verbose"312313    prefix, opt = _split_opt("//verbose")314    assert prefix == "//"315    assert opt == "verbose"316317    prefix, opt = _split_opt("-verbose")318    assert prefix == "-"319    assert opt == "verbose"320321    prefix, opt = _split_opt("verbose")322    assert prefix == ""323    assert opt == "verbose"