Skip to content
Myr

test_others.py

This file

Path

tests/test_others.py

257 lines · 7.9 KiB · Python

Last changed by

✨ Add support for custom types and parsers (updates/builds upon PR #443) (#583)John Purviancebefore adoption3e37e01

History of this file

Take it

The walk stopped after 200 commits: lines older than fa9107f point at it.

📝 Update release notesgithub-actionsbefore adoptionfa9107f

lines 1–2why, one step back
1import os
2import subprocess

👷‍♂️ Consistently use `sys.executable` to run subprocesses, needed by OpenSUSE (#408)Matthias Bachbefore adoption416c612

line 3why, one step back
3import sys

✨ Add support for custom types and parsers (updates/builds upon PR #443) (#583)John Purviancebefore adoption3e37e01

line 4why, one step back
4import typing

📝 Update release notesgithub-actionsbefore adoptionfa9107f

lines 5–13why, one step back
5from pathlib import Path
6from unittest import mock78import click9import pytest10import shellingham11import typer12import typer.completion13from typer.main import solve_typer_info_defaults, solve_typer_info_help

✨ Add support for custom types and parsers (updates/builds upon PR #443) (#583)John Purviancebefore adoption3e37e01

line 14why, one step back
14from typer.models import ParameterInfo, TyperInfo

📝 Update release notesgithub-actionsbefore adoptionfa9107f

lines 15–29why, one step back
15from typer.testing import CliRunner
1617runner = CliRunner()181920def test_help_from_info():21 # Mainly for coverage/completeness22 value = solve_typer_info_help(TyperInfo())23 assert value is None242526def test_defaults_from_info():27 # Mainly for coverage/completeness28 value = solve_typer_info_defaults(TyperInfo())29 assert value

✨ Add support for custom types and parsers (updates/builds upon PR #443) (#583)John Purviancebefore adoption3e37e01

lines 30–73why, one step back
30
3132def test_too_may_parsers():33 def custom_parser(value: str) -> int:34 return int(value) # pragma: no cover3536 class CustomClickParser(click.ParamType):37 name = "custom_parser"3839 def convert(40 self,41 value: str,42 param: typing.Optional[click.Parameter],43 ctx: typing.Optional[click.Context],44 ) -> typing.Any:45 return int(value) # pragma: no cover4647 expected_error = (48 "Multiple custom type parsers provided. "49 "`parser` and `click_type` may not both be provided."50 )5152 with pytest.raises(ValueError, match=expected_error):53 ParameterInfo(parser=custom_parser, click_type=CustomClickParser())545556def test_valid_parser_permutations():57 def custom_parser(value: str) -> int:58 return int(value) # pragma: no cover5960 class CustomClickParser(click.ParamType):61 name = "custom_parser"6263 def convert(64 self,65 value: str,66 param: typing.Optional[click.Parameter],67 ctx: typing.Optional[click.Context],68 ) -> typing.Any:69 return int(value) # pragma: no cover7071 ParameterInfo()72 ParameterInfo(parser=custom_parser)73 ParameterInfo(click_type=CustomClickParser())

📝 Update release notesgithub-actionsbefore adoptionfa9107f

lines 74–80why, one step back
74
7576def test_install_invalid_shell():77 app = typer.Typer()7879 @app.command()80 def main():

✨ Richify, add integrations with Rich everywhere (#419)Sebastián Ramírezbefore adoption6208b5b

line 81why, one step back
81 print("Hello World")

📝 Update release notesgithub-actionsbefore adoptionfa9107f

lines 82–112why, one step back
82
83 with mock.patch.object(84 shellingham, "detect_shell", return_value=("xshell", "/usr/bin/xshell")85 ):86 result = runner.invoke(app, ["--install-completion"])87 assert "Shell xshell is not supported." in result.stdout88 result = runner.invoke(app)89 assert "Hello World" in result.stdout909192def test_callback_too_many_parameters():93 app = typer.Typer()9495 def name_callback(ctx, param, val1, val2):96 pass # pragma: nocover9798 @app.command()99 def main(name: str = typer.Option(..., callback=name_callback)):100 pass # pragma: nocover101102 with pytest.raises(click.ClickException) as exc_info:103 runner.invoke(app, ["--name", "Camila"])104 assert (105 exc_info.value.message == "Too many CLI parameter callback function parameters"106 )107108109def test_callback_2_untyped_parameters():110 app = typer.Typer()111112 def name_callback(ctx, value):

✨ Richify, add integrations with Rich everywhere (#419)Sebastián Ramírezbefore adoption6208b5b

lines 113–114why, one step back
113 print(f"info name is: {ctx.info_name}")
114 print(f"value is: {value}")

📝 Update release notesgithub-actionsbefore adoptionfa9107f

lines 115–117why, one step back
115
116 @app.command()117 def main(name: str = typer.Option(..., callback=name_callback)):

✨ Richify, add integrations with Rich everywhere (#419)Sebastián Ramírezbefore adoption6208b5b

line 118why, one step back
118 print("Hello World")

📝 Update release notesgithub-actionsbefore adoptionfa9107f

lines 119–128why, one step back
119
120 result = runner.invoke(app, ["--name", "Camila"])121 assert "info name is: main" in result.stdout122 assert "value is: Camila" in result.stdout123124125def test_callback_3_untyped_parameters():126 app = typer.Typer()127128 def name_callback(ctx, param, value):

✨ Richify, add integrations with Rich everywhere (#419)Sebastián Ramírezbefore adoption6208b5b

lines 129–131why, one step back
129 print(f"info name is: {ctx.info_name}")
130 print(f"param name is: {param.name}")131 print(f"value is: {value}")

📝 Update release notesgithub-actionsbefore adoptionfa9107f

lines 132–134why, one step back
132
133 @app.command()134 def main(name: str = typer.Option(..., callback=name_callback)):

✨ Richify, add integrations with Rich everywhere (#419)Sebastián Ramírezbefore adoption6208b5b

line 135why, one step back
135 print("Hello World")

📝 Update release notesgithub-actionsbefore adoptionfa9107f

lines 136–145why, one step back
136
137 result = runner.invoke(app, ["--name", "Camila"])138 assert "info name is: main" in result.stdout139 assert "param name is: name" in result.stdout140 assert "value is: Camila" in result.stdout141142143def test_completion_untyped_parameters():144 file_path = Path(__file__).parent / "assets/completion_no_types.py"145 result = subprocess.run(

👷‍♂️ Consistently use `sys.executable` to run subprocesses, needed by OpenSUSE (#408)Matthias Bachbefore adoption416c612

line 146why, one step back
146 [sys.executable, "-m", "coverage", "run", str(file_path)],

📝 Update release notesgithub-actionsbefore adoptionfa9107f

lines 147–167why, one step back
147 stdout=subprocess.PIPE,
148 stderr=subprocess.PIPE,149 encoding="utf-8",150 env={151 **os.environ,152 "_COMPLETION_NO_TYPES.PY_COMPLETE": "complete_zsh",153 "_TYPER_COMPLETE_ARGS": "completion_no_types.py --name Sebastian --name Ca",154 "_TYPER_COMPLETE_TESTING": "True",155 },156 )157 assert "info name is: completion_no_types.py" in result.stderr158 # TODO: when deprecating Click 7, remove second option159 assert (160 "args is: []" in result.stderr161 or "args is: ['--name', 'Sebastian', '--name']" in result.stderr162 )163 assert "incomplete is: Ca" in result.stderr164 assert '"Camila":"The reader of books."' in result.stdout165 assert '"Carlos":"The writer of scripts."' in result.stdout166167 result = subprocess.run(

👷‍♂️ Consistently use `sys.executable` to run subprocesses, needed by OpenSUSE (#408)Matthias Bachbefore adoption416c612

line 168why, one step back
168 [sys.executable, "-m", "coverage", "run", str(file_path)],

📝 Update release notesgithub-actionsbefore adoptionfa9107f

lines 169–178why, one step back
169 stdout=subprocess.PIPE,
170 stderr=subprocess.PIPE,171 encoding="utf-8",172 )173 assert "Hello World" in result.stdout174175176def test_completion_untyped_parameters_different_order_correct_names():177 file_path = Path(__file__).parent / "assets/completion_no_types_order.py"178 result = subprocess.run(

👷‍♂️ Consistently use `sys.executable` to run subprocesses, needed by OpenSUSE (#408)Matthias Bachbefore adoption416c612

line 179why, one step back
179 [sys.executable, "-m", "coverage", "run", str(file_path)],

📝 Update release notesgithub-actionsbefore adoptionfa9107f

lines 180–200why, one step back
180 stdout=subprocess.PIPE,
181 stderr=subprocess.PIPE,182 encoding="utf-8",183 env={184 **os.environ,185 "_COMPLETION_NO_TYPES_ORDER.PY_COMPLETE": "complete_zsh",186 "_TYPER_COMPLETE_ARGS": "completion_no_types_order.py --name Sebastian --name Ca",187 "_TYPER_COMPLETE_TESTING": "True",188 },189 )190 assert "info name is: completion_no_types_order.py" in result.stderr191 # TODO: when deprecating Click 7, remove second option192 assert (193 "args is: []" in result.stderr194 or "args is: ['--name', 'Sebastian', '--name']" in result.stderr195 )196 assert "incomplete is: Ca" in result.stderr197 assert '"Camila":"The reader of books."' in result.stdout198 assert '"Carlos":"The writer of scripts."' in result.stdout199200 result = subprocess.run(

👷‍♂️ Consistently use `sys.executable` to run subprocesses, needed by OpenSUSE (#408)Matthias Bachbefore adoption416c612

line 201why, one step back
201 [sys.executable, "-m", "coverage", "run", str(file_path)],

📝 Update release notesgithub-actionsbefore adoptionfa9107f

lines 202–228why, one step back
202 stdout=subprocess.PIPE,
203 stderr=subprocess.PIPE,204 encoding="utf-8",205 )206 assert "Hello World" in result.stdout207208209def test_autocompletion_too_many_parameters():210 app = typer.Typer()211212 def name_callback(ctx, args, incomplete, val2):213 pass # pragma: nocover214215 @app.command()216 def main(name: str = typer.Option(..., autocompletion=name_callback)):217 pass # pragma: nocover218219 with pytest.raises(click.ClickException) as exc_info:220 runner.invoke(app, ["--name", "Camila"])221 assert exc_info.value.message == "Invalid autocompletion callback parameters: val2"222223224def test_forward_references():225 app = typer.Typer()226227 @app.command()228 def main(arg1, arg2: int, arg3: "int", arg4: bool = False, arg5: "bool" = False):

✨ Richify, add integrations with Rich everywhere (#419)Sebastián Ramírezbefore adoption6208b5b

lines 229–233why, one step back
229 print(f"arg1: {type(arg1)} {arg1}")
230 print(f"arg2: {type(arg2)} {arg2}")231 print(f"arg3: {type(arg3)} {arg3}")232 print(f"arg4: {type(arg4)} {arg4}")233 print(f"arg5: {type(arg5)} {arg5}")

📝 Update release notesgithub-actionsbefore adoptionfa9107f

lines 234–238why, one step back
234
235 result = runner.invoke(app, ["Hello", "2", "invalid"])236 # TODO: when deprecating Click 7, remove second option237238 assert (

✨ Richify, add integrations with Rich everywhere (#419)Sebastián Ramírezbefore adoption6208b5b

lines 239–240why, one step back
239 "Invalid value for 'ARG3': 'invalid' is not a valid integer" in result.stdout
240 or "Invalid value for 'ARG3': invalid is not a valid integer" in result.stdout

📝 Update release notesgithub-actionsbefore adoptionfa9107f

lines 241–246why, one step back
241 )
242 result = runner.invoke(app, ["Hello", "2", "3", "--arg4", "--arg5"])243 assert (244 "arg1: <class 'str'> Hello\narg2: <class 'int'> 2\narg3: <class 'int'> 3\narg4: <class 'bool'> True\narg5: <class 'bool'> True\n"245 in result.stdout246 )

🐛 Fix `context_settings` for a Typer app with a single command (#210)Leron Graybefore adoption778d5bd

lines 247–257why, one step back
247
248249def test_context_settings_inheritance_single_command():250 app = typer.Typer(context_settings=dict(help_option_names=["-h", "--help"]))251252 @app.command()253 def main(name: str):254 pass # pragma: nocover255256 result = runner.invoke(app, ["main", "-h"])257 assert "Show this message and exit." in result.stdout