test_others.py
This file
Path
tests/test_others.py
280 lines · 8.5 KiB · Python
Last changed by
✅ Only run completion installation tests when the env var `_TYPER_RUN_INSTALL_COMPLETION_TESTS` is set (#995)Sofie Van Landeghembefore adoption9f9047d
History of this fileTake 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 CliRunner1718from .utils import requires_completion_permission1920runner = CliRunner()212223def test_help_from_info():24 # Mainly for coverage/completeness25 value = solve_typer_info_help(TyperInfo())26 assert value is None272829def test_defaults_from_info():30 # Mainly for coverage/completeness31 value = solve_typer_info_defaults(TyperInfo())32 assert value333435def test_too_many_parsers():36 def custom_parser(value: str) -> int:37 return int(value) # pragma: no cover3839 class CustomClickParser(click.ParamType):40 name = "custom_parser"4142 def convert(43 self,44 value: str,45 param: typing.Optional[click.Parameter],46 ctx: typing.Optional[click.Context],47 ) -> typing.Any:48 return int(value) # pragma: no cover4950 expected_error = (51 "Multiple custom type parsers provided. "52 "`parser` and `click_type` may not both be provided."53 )5455 with pytest.raises(ValueError, match=expected_error):56 ParameterInfo(parser=custom_parser, click_type=CustomClickParser())575859def test_valid_parser_permutations():60 def custom_parser(value: str) -> int:61 return int(value) # pragma: no cover6263 class CustomClickParser(click.ParamType):64 name = "custom_parser"6566 def convert(67 self,68 value: str,69 param: typing.Optional[click.Parameter],70 ctx: typing.Optional[click.Context],71 ) -> typing.Any:72 return int(value) # pragma: no cover7374 ParameterInfo()75 ParameterInfo(parser=custom_parser)76 ParameterInfo(click_type=CustomClickParser())777879@requires_completion_permission80def test_install_invalid_shell():81 app = typer.Typer()8283 @app.command()84 def main():85 print("Hello World")8687 with mock.patch.object(88 shellingham, "detect_shell", return_value=("xshell", "/usr/bin/xshell")89 ):90 result = runner.invoke(app, ["--install-completion"])91 assert "Shell xshell is not supported." in result.stdout92 result = runner.invoke(app)93 assert "Hello World" in result.stdout949596def test_callback_too_many_parameters():97 app = typer.Typer()9899 def name_callback(ctx, param, val1, val2):100 pass # pragma: no cover101102 @app.command()103 def main(name: str = typer.Option(..., callback=name_callback)):104 pass # pragma: no cover105106 with pytest.raises(click.ClickException) as exc_info:107 runner.invoke(app, ["--name", "Camila"])108 assert (109 exc_info.value.message == "Too many CLI parameter callback function parameters"110 )111112113def test_callback_2_untyped_parameters():114 app = typer.Typer()115116 def name_callback(ctx, value):117 print(f"info name is: {ctx.info_name}")118 print(f"value is: {value}")119120 @app.command()121 def main(name: str = typer.Option(..., callback=name_callback)):122 print("Hello World")123124 result = runner.invoke(app, ["--name", "Camila"])125 assert "info name is: main" in result.stdout126 assert "value is: Camila" in result.stdout127128129def test_callback_3_untyped_parameters():130 app = typer.Typer()131132 def name_callback(ctx, param, value):133 print(f"info name is: {ctx.info_name}")134 print(f"param name is: {param.name}")135 print(f"value is: {value}")136137 @app.command()138 def main(name: str = typer.Option(..., callback=name_callback)):139 print("Hello World")140141 result = runner.invoke(app, ["--name", "Camila"])142 assert "info name is: main" in result.stdout143 assert "param name is: name" in result.stdout144 assert "value is: Camila" in result.stdout145146147def test_completion_argument():148 file_path = Path(__file__).parent / "assets/completion_argument.py"149 result = subprocess.run(150 [sys.executable, "-m", "coverage", "run", str(file_path), "E"],151 capture_output=True,152 encoding="utf-8",153 env={154 **os.environ,155 "_COMPLETION_ARGUMENT.PY_COMPLETE": "complete_zsh",156 "_TYPER_COMPLETE_ARGS": "completion_argument.py E",157 "_TYPER_COMPLETE_TESTING": "True",158 },159 )160 assert "Emma" in result.stdout or "_files" in result.stdout161 assert "ctx: completion_argument" in result.stderr162 assert "arg is: name" in result.stderr163 assert "incomplete is: E" in result.stderr164165166def test_completion_untyped_parameters():167 file_path = Path(__file__).parent / "assets/completion_no_types.py"168 result = subprocess.run(169 [sys.executable, "-m", "coverage", "run", str(file_path)],170 capture_output=True,171 encoding="utf-8",172 env={173 **os.environ,174 "_COMPLETION_NO_TYPES.PY_COMPLETE": "complete_zsh",175 "_TYPER_COMPLETE_ARGS": "completion_no_types.py --name Sebastian --name Ca",176 },177 )178 assert "info name is: completion_no_types.py" in result.stderr179 assert "args is: []" in result.stderr180 assert "incomplete is: Ca" in result.stderr181 assert '"Camila":"The reader of books."' in result.stdout182 assert '"Carlos":"The writer of scripts."' in result.stdout183184 result = subprocess.run(185 [sys.executable, "-m", "coverage", "run", str(file_path)],186 capture_output=True,187 encoding="utf-8",188 )189 assert "Hello World" in result.stdout190191192def test_completion_untyped_parameters_different_order_correct_names():193 file_path = Path(__file__).parent / "assets/completion_no_types_order.py"194 result = subprocess.run(195 [sys.executable, "-m", "coverage", "run", str(file_path)],196 capture_output=True,197 encoding="utf-8",198 env={199 **os.environ,200 "_COMPLETION_NO_TYPES_ORDER.PY_COMPLETE": "complete_zsh",201 "_TYPER_COMPLETE_ARGS": "completion_no_types_order.py --name Sebastian --name Ca",202 },203 )204 assert "info name is: completion_no_types_order.py" in result.stderr205 assert "args is: []" in result.stderr206 assert "incomplete is: Ca" in result.stderr207 assert '"Camila":"The reader of books."' in result.stdout208 assert '"Carlos":"The writer of scripts."' in result.stdout209210 result = subprocess.run(211 [sys.executable, "-m", "coverage", "run", str(file_path)],212 capture_output=True,213 encoding="utf-8",214 )215 assert "Hello World" in result.stdout216217218def test_autocompletion_too_many_parameters():219 app = typer.Typer()220221 def name_callback(ctx, args, incomplete, val2):222 pass # pragma: no cover223224 @app.command()225 def main(name: str = typer.Option(..., autocompletion=name_callback)):226 pass # pragma: no cover227228 with pytest.raises(click.ClickException) as exc_info:229 runner.invoke(app, ["--name", "Camila"])230 assert exc_info.value.message == "Invalid autocompletion callback parameters: val2"231232233def test_forward_references():234 app = typer.Typer()235236 @app.command()237 def main(arg1, arg2: int, arg3: "int", arg4: bool = False, arg5: "bool" = False):238 print(f"arg1: {type(arg1)} {arg1}")239 print(f"arg2: {type(arg2)} {arg2}")240 print(f"arg3: {type(arg3)} {arg3}")241 print(f"arg4: {type(arg4)} {arg4}")242 print(f"arg5: {type(arg5)} {arg5}")243244 result = runner.invoke(app, ["Hello", "2", "invalid"])245246 assert "Invalid value for 'ARG3': 'invalid' is not a valid integer" in result.stdout247 result = runner.invoke(app, ["Hello", "2", "3", "--arg4", "--arg5"])248 assert (249 "arg1: <class 'str'> Hello\narg2: <class 'int'> 2\narg3: <class 'int'> 3\narg4: <class 'bool'> True\narg5: <class 'bool'> True\n"250 in result.stdout251 )252253254def test_context_settings_inheritance_single_command():255 app = typer.Typer(context_settings={"help_option_names": ["-h", "--help"]})256257 @app.command()258 def main(name: str):259 pass # pragma: no cover260261 result = runner.invoke(app, ["main", "-h"])262 assert "Show this message and exit." in result.stdout263264265def test_split_opt():266 prefix, opt = _split_opt("--verbose")267 assert prefix == "--"268 assert opt == "verbose"269270 prefix, opt = _split_opt("//verbose")271 assert prefix == "//"272 assert opt == "verbose"273274 prefix, opt = _split_opt("-verbose")275 assert prefix == "-"276 assert opt == "verbose"277278 prefix, opt = _split_opt("verbose")279 assert prefix == ""280 assert opt == "verbose"