Skip to content
Myr

test_others.py

This file

Path

tests/test_others.py

224 lines 路 6.8 KiB 路 Python

Last changed by

:sparkles: Add support for forward references (#93)Sebasti谩n Ram铆rezbefore adoptiona93e6b2

History of this file

Take it

1import os2import subprocess3from pathlib import Path4from typing import Optional5from unittest import mock67import click8import pytest9import shellingham10import typer11import typer.completion12from typer.main import solve_typer_info_defaults, solve_typer_info_help13from typer.models import TyperInfo14from typer.testing import CliRunner1516runner = CliRunner()171819def test_optional():20    app = typer.Typer()2122    @app.command()23    def opt(user: Optional[str] = None):24        if user:25            typer.echo(f"User: {user}")26        else:27            typer.echo("No user")2829    result = runner.invoke(app)30    assert result.exit_code == 031    assert "No user" in result.output3233    result = runner.invoke(app, ["--user", "Camila"])34    assert result.exit_code == 035    assert "User: Camila" in result.output363738def test_no_type():39    app = typer.Typer()4041    @app.command()42    def no_type(user):43        typer.echo(f"User: {user}")4445    result = runner.invoke(app, ["Camila"])46    assert result.exit_code == 047    assert "User: Camila" in result.output484950def test_help_from_info():51    # Mainly for coverage/completeness52    value = solve_typer_info_help(TyperInfo())53    assert value is None545556def test_defaults_from_info():57    # Mainly for coverage/completeness58    value = solve_typer_info_defaults(TyperInfo())59    assert value606162def test_install_invalid_shell():63    app = typer.Typer()6465    @app.command()66    def main():67        typer.echo("Hello World")6869    with mock.patch.object(70        shellingham, "detect_shell", return_value=("xshell", "/usr/bin/xshell")71    ):72        result = runner.invoke(app, ["--install-completion"])73        assert "Shell xshell is not supported." in result.stdout74    result = runner.invoke(app)75    assert "Hello World" in result.stdout767778def test_callback_too_many_parameters():79    app = typer.Typer()8081    def name_callback(ctx, param, val1, val2):82        pass  # pragma: nocover8384    @app.command()85    def main(name: str = typer.Option(..., callback=name_callback)):86        pass  # pragma: nocover8788    with pytest.raises(click.ClickException) as exc_info:89        runner.invoke(app, ["--name", "Camila"])90    assert (91        exc_info.value.message == "Too many CLI parameter callback function parameters"92    )939495def test_callback_2_untyped_parameters():96    app = typer.Typer()9798    def name_callback(ctx, value):99        typer.echo(f"info name is: {ctx.info_name}")100        typer.echo(f"value is: {value}")101102    @app.command()103    def main(name: str = typer.Option(..., callback=name_callback)):104        typer.echo("Hello World")105106    result = runner.invoke(app, ["--name", "Camila"])107    assert "info name is: main" in result.stdout108    assert "value is: Camila" in result.stdout109110111def test_callback_3_untyped_parameters():112    app = typer.Typer()113114    def name_callback(ctx, param, value):115        typer.echo(f"info name is: {ctx.info_name}")116        typer.echo(f"param name is: {param.name}")117        typer.echo(f"value is: {value}")118119    @app.command()120    def main(name: str = typer.Option(..., callback=name_callback)):121        typer.echo("Hello World")122123    result = runner.invoke(app, ["--name", "Camila"])124    assert "info name is: main" in result.stdout125    assert "param name is: name" in result.stdout126    assert "value is: Camila" in result.stdout127128129def test_completion_untyped_parameters():130    file_path = Path(__file__).parent / "assets/completion_no_types.py"131    result = subprocess.run(132        ["coverage", "run", str(file_path)],133        stdout=subprocess.PIPE,134        stderr=subprocess.PIPE,135        encoding="utf-8",136        env={137            **os.environ,138            "_COMPLETION_NO_TYPES.PY_COMPLETE": "complete_zsh",139            "_TYPER_COMPLETE_ARGS": "completion_no_types.py --name Sebastian --name Ca",140            "_TYPER_COMPLETE_TESTING": "True",141        },142    )143    assert "info name is: completion_no_types.py" in result.stderr144    assert "args is: ['--name', 'Sebastian', '--name']" in result.stderr145    assert "incomplete is: Ca" in result.stderr146    assert '"Camila":"The reader of books."' in result.stdout147    assert '"Carlos":"The writer of scripts."' in result.stdout148    assert '"Sebastian":"The type hints guy."' in result.stdout149150    result = subprocess.run(151        ["coverage", "run", str(file_path)],152        stdout=subprocess.PIPE,153        stderr=subprocess.PIPE,154        encoding="utf-8",155    )156    assert "Hello World" in result.stdout157158159def test_completion_untyped_parameters_different_order_correct_names():160    file_path = Path(__file__).parent / "assets/completion_no_types_order.py"161    result = subprocess.run(162        ["coverage", "run", str(file_path)],163        stdout=subprocess.PIPE,164        stderr=subprocess.PIPE,165        encoding="utf-8",166        env={167            **os.environ,168            "_COMPLETION_NO_TYPES_ORDER.PY_COMPLETE": "complete_zsh",169            "_TYPER_COMPLETE_ARGS": "completion_no_types_order.py --name Sebastian --name Ca",170            "_TYPER_COMPLETE_TESTING": "True",171        },172    )173    assert "info name is: completion_no_types_order.py" in result.stderr174    assert "args is: ['--name', 'Sebastian', '--name']" in result.stderr175    assert "incomplete is: Ca" in result.stderr176    assert '"Camila":"The reader of books."' in result.stdout177    assert '"Carlos":"The writer of scripts."' in result.stdout178    assert '"Sebastian":"The type hints guy."' in result.stdout179180    result = subprocess.run(181        ["coverage", "run", str(file_path)],182        stdout=subprocess.PIPE,183        stderr=subprocess.PIPE,184        encoding="utf-8",185    )186    assert "Hello World" in result.stdout187188189def test_autocompletion_too_many_parameters():190    app = typer.Typer()191192    def name_callback(ctx, args, incomplete, val2):193        pass  # pragma: nocover194195    @app.command()196    def main(name: str = typer.Option(..., autocompletion=name_callback)):197        pass  # pragma: nocover198199    with pytest.raises(click.ClickException) as exc_info:200        runner.invoke(app, ["--name", "Camila"])201    assert exc_info.value.message == "Invalid autocompletion callback parameters: val2"202203204def test_forward_references():205    app = typer.Typer()206207    @app.command()208    def main(arg1, arg2: int, arg3: "int", arg4: bool = False, arg5: "bool" = False):209        typer.echo(f"arg1: {type(arg1)} {arg1}")210        typer.echo(f"arg2: {type(arg2)} {arg2}")211        typer.echo(f"arg3: {type(arg3)} {arg3}")212        typer.echo(f"arg4: {type(arg4)} {arg4}")213        typer.echo(f"arg5: {type(arg5)} {arg5}")214215    result = runner.invoke(app, ["Hello", "2", "invalid"])216    assert (217        "Error: Invalid value for 'ARG3': invalid is not a valid integer"218        in result.stdout219    )220    result = runner.invoke(app, ["Hello", "2", "3", "--arg4", "--arg5"])221    assert (222        "arg1: <class 'str'> Hello\narg2: <class 'int'> 2\narg3: <class 'int'> 3\narg4: <class 'bool'> True\narg5: <class 'bool'> True\n"223        in result.stdout224    )