Skip to content
Myr

test_others.py

This file

Path

tests/test_others.py

213 lines 路 6.7 KiB 路 Python

Last changed by

馃悰 Fix type conversion for `List` and `Tuple` and their internal types (#143)Irvin Hobefore adoption722a4fe

History of this file

Take it

1import os2import subprocess3from pathlib import Path4from unittest import mock56import click7import pytest8import shellingham9import typer10import typer.completion11from typer.main import solve_typer_info_defaults, solve_typer_info_help12from typer.models import TyperInfo13from typer.testing import CliRunner1415runner = CliRunner()161718def test_help_from_info():19    # Mainly for coverage/completeness20    value = solve_typer_info_help(TyperInfo())21    assert value is None222324def test_defaults_from_info():25    # Mainly for coverage/completeness26    value = solve_typer_info_defaults(TyperInfo())27    assert value282930def test_install_invalid_shell():31    app = typer.Typer()3233    @app.command()34    def main():35        typer.echo("Hello World")3637    with mock.patch.object(38        shellingham, "detect_shell", return_value=("xshell", "/usr/bin/xshell")39    ):40        result = runner.invoke(app, ["--install-completion"])41        assert "Shell xshell is not supported." in result.stdout42    result = runner.invoke(app)43    assert "Hello World" in result.stdout444546def test_callback_too_many_parameters():47    app = typer.Typer()4849    def name_callback(ctx, param, val1, val2):50        pass  # pragma: nocover5152    @app.command()53    def main(name: str = typer.Option(..., callback=name_callback)):54        pass  # pragma: nocover5556    with pytest.raises(click.ClickException) as exc_info:57        runner.invoke(app, ["--name", "Camila"])58    assert (59        exc_info.value.message == "Too many CLI parameter callback function parameters"60    )616263def test_callback_2_untyped_parameters():64    app = typer.Typer()6566    def name_callback(ctx, value):67        typer.echo(f"info name is: {ctx.info_name}")68        typer.echo(f"value is: {value}")6970    @app.command()71    def main(name: str = typer.Option(..., callback=name_callback)):72        typer.echo("Hello World")7374    result = runner.invoke(app, ["--name", "Camila"])75    assert "info name is: main" in result.stdout76    assert "value is: Camila" in result.stdout777879def test_callback_3_untyped_parameters():80    app = typer.Typer()8182    def name_callback(ctx, param, value):83        typer.echo(f"info name is: {ctx.info_name}")84        typer.echo(f"param name is: {param.name}")85        typer.echo(f"value is: {value}")8687    @app.command()88    def main(name: str = typer.Option(..., callback=name_callback)):89        typer.echo("Hello World")9091    result = runner.invoke(app, ["--name", "Camila"])92    assert "info name is: main" in result.stdout93    assert "param name is: name" in result.stdout94    assert "value is: Camila" in result.stdout959697def test_completion_untyped_parameters():98    file_path = Path(__file__).parent / "assets/completion_no_types.py"99    result = subprocess.run(100        ["coverage", "run", str(file_path)],101        stdout=subprocess.PIPE,102        stderr=subprocess.PIPE,103        encoding="utf-8",104        env={105            **os.environ,106            "_COMPLETION_NO_TYPES.PY_COMPLETE": "complete_zsh",107            "_TYPER_COMPLETE_ARGS": "completion_no_types.py --name Sebastian --name Ca",108            "_TYPER_COMPLETE_TESTING": "True",109        },110    )111    assert "info name is: completion_no_types.py" in result.stderr112    # TODO: when deprecating Click 7, remove second option113    assert (114        "args is: []" in result.stderr115        or "args is: ['--name', 'Sebastian', '--name']" in result.stderr116    )117    assert "incomplete is: Ca" in result.stderr118    assert '"Camila":"The reader of books."' in result.stdout119    assert '"Carlos":"The writer of scripts."' in result.stdout120121    result = subprocess.run(122        ["coverage", "run", str(file_path)],123        stdout=subprocess.PIPE,124        stderr=subprocess.PIPE,125        encoding="utf-8",126    )127    assert "Hello World" in result.stdout128129130def test_completion_untyped_parameters_different_order_correct_names():131    file_path = Path(__file__).parent / "assets/completion_no_types_order.py"132    result = subprocess.run(133        ["coverage", "run", str(file_path)],134        stdout=subprocess.PIPE,135        stderr=subprocess.PIPE,136        encoding="utf-8",137        env={138            **os.environ,139            "_COMPLETION_NO_TYPES_ORDER.PY_COMPLETE": "complete_zsh",140            "_TYPER_COMPLETE_ARGS": "completion_no_types_order.py --name Sebastian --name Ca",141            "_TYPER_COMPLETE_TESTING": "True",142        },143    )144    assert "info name is: completion_no_types_order.py" in result.stderr145    # TODO: when deprecating Click 7, remove second option146    assert (147        "args is: []" in result.stderr148        or "args is: ['--name', 'Sebastian', '--name']" in result.stderr149    )150    assert "incomplete is: Ca" in result.stderr151    assert '"Camila":"The reader of books."' in result.stdout152    assert '"Carlos":"The writer of scripts."' in result.stdout153154    result = subprocess.run(155        ["coverage", "run", str(file_path)],156        stdout=subprocess.PIPE,157        stderr=subprocess.PIPE,158        encoding="utf-8",159    )160    assert "Hello World" in result.stdout161162163def test_autocompletion_too_many_parameters():164    app = typer.Typer()165166    def name_callback(ctx, args, incomplete, val2):167        pass  # pragma: nocover168169    @app.command()170    def main(name: str = typer.Option(..., autocompletion=name_callback)):171        pass  # pragma: nocover172173    with pytest.raises(click.ClickException) as exc_info:174        runner.invoke(app, ["--name", "Camila"])175    assert exc_info.value.message == "Invalid autocompletion callback parameters: val2"176177178def test_forward_references():179    app = typer.Typer()180181    @app.command()182    def main(arg1, arg2: int, arg3: "int", arg4: bool = False, arg5: "bool" = False):183        typer.echo(f"arg1: {type(arg1)} {arg1}")184        typer.echo(f"arg2: {type(arg2)} {arg2}")185        typer.echo(f"arg3: {type(arg3)} {arg3}")186        typer.echo(f"arg4: {type(arg4)} {arg4}")187        typer.echo(f"arg5: {type(arg5)} {arg5}")188189    result = runner.invoke(app, ["Hello", "2", "invalid"])190    # TODO: when deprecating Click 7, remove second option191192    assert (193        "Error: Invalid value for 'ARG3': 'invalid' is not a valid integer"194        in result.stdout195        or "Error: Invalid value for 'ARG3': invalid is not a valid integer"196        in result.stdout197    )198    result = runner.invoke(app, ["Hello", "2", "3", "--arg4", "--arg5"])199    assert (200        "arg1: <class 'str'> Hello\narg2: <class 'int'> 2\narg3: <class 'int'> 3\narg4: <class 'bool'> True\narg5: <class 'bool'> True\n"201        in result.stdout202    )203204205def test_context_settings_inheritance_single_command():206    app = typer.Typer(context_settings=dict(help_option_names=["-h", "--help"]))207208    @app.command()209    def main(name: str):210        pass  # pragma: nocover211212    result = runner.invoke(app, ["main", "-h"])213    assert "Show this message and exit." in result.stdout