🐛 Fix type conversion for `List` and `Tuple` and their internal types (#143)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Irvin Ho · committed by GitHub · parent b0fc0f0 · Browse files · 3 files·+128 added−44 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Diff stats
3 files+128 added−44 removed
- tests:+92 added−32 removed
- other:+36 added−12 removed
Provenance
- Commit
722a4fe- Tree
ca9d958- Author
Irvin Ho <8572372+hellowhistler@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
b0fc0f0
3 files changed+128 added−44 removed
modified:tests/test_others.py-32 removed
1 import os2 import subprocess3 from pathlib import Path4-from typing import Optional4 from unittest import mock5 6 import click7 import pytest6 unmodified lines14 15 runner = CliRunner()16 17 19-def test_optional():20- app = typer.Typer()21-22- @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")28-29- result = runner.invoke(app)30- assert result.exit_code == 031- assert "No user" in result.output32-33- result = runner.invoke(app, ["--user", "Camila"])34- assert result.exit_code == 035- assert "User: Camila" in result.output36-37-38-def test_no_type():39- app = typer.Typer()40-41- @app.command()42- def no_type(user):43- typer.echo(f"User: {user}")44-45- result = runner.invoke(app, ["Camila"])46- assert result.exit_code == 047- assert "User: Camila" in result.output48-49-18 def test_help_from_info():19 # Mainly for coverage/completeness20 value = solve_typer_info_help(TyperInfo())21 assert value is None192 unmodified linesadded:tests/test_type_conversion.py+92 added
1+from enum import Enum2+from pathlib import Path3+from typing import List, Optional, Tuple4+5+import pytest6+import typer7+from typer.testing import CliRunner8+9+runner = CliRunner()10+11+12+def test_optional():13+ app = typer.Typer()14+15+ @app.command()16+ def opt(user: Optional[str] = None):17+ if user:18+ typer.echo(f"User: {user}")19+ else:20+ typer.echo("No user")21+22+ result = runner.invoke(app)23+ assert result.exit_code == 024+ assert "No user" in result.output25+26+ result = runner.invoke(app, ["--user", "Camila"])27+ assert result.exit_code == 028+ assert "User: Camila" in result.output29+30+31+def test_no_type():32+ app = typer.Typer()33+34+ @app.command()35+ def no_type(user):36+ typer.echo(f"User: {user}")37+38+ result = runner.invoke(app, ["Camila"])39+ assert result.exit_code == 040+ assert "User: Camila" in result.output41+42+43+class SomeEnum(Enum):44+ ONE = "one"45+ TWO = "two"46+ THREE = "three"47+48+49+@pytest.mark.parametrize(50+ "type_annotation",51+ [List[Path], List[SomeEnum], List[str]],52+)53+def test_list_parameters_convert_to_lists(type_annotation):54+ # Lists containing objects that are converted by Click (i.e. not Path or Enum)55+ # should not be inadvertently converted to tuples56+ expected_element_type = type_annotation.__args__[0]57+ app = typer.Typer()58+59+ @app.command()60+ def list_conversion(container: type_annotation):61+ assert isinstance(container, list)62+ for element in container:63+ assert isinstance(element, expected_element_type)64+65+ result = runner.invoke(app, ["one", "two", "three"])66+ assert result.exit_code == 067+68+69+@pytest.mark.parametrize(70+ "type_annotation",71+ [72+ Tuple[str, str],73+ Tuple[str, Path],74+ Tuple[Path, Path],75+ Tuple[str, SomeEnum],76+ Tuple[SomeEnum, SomeEnum],77+ ],78+)79+def test_tuple_parameter_elements_are_converted_recursively(type_annotation):80+ # Tuple elements that aren't converted by Click (i.e. Path or Enum)81+ # should be recursively converted by Typer82+ expected_element_types = type_annotation.__args__83+ app = typer.Typer()84+85+ @app.command()86+ def tuple_recursive_conversion(container: type_annotation):87+ assert isinstance(container, tuple)88+ for element, expected_type in zip(container, expected_element_types):89+ assert isinstance(element, expected_type)90+91+ result = runner.invoke(app, ["one", "two"])92+ assert result.exit_code == 0modified:typer/main.py+36 added-12 removed
451 unmodified lines452 )453 return command454 455 456+def determine_type_convertor(type_: Any) -> Optional[Callable[[Any], Any]]:457+ convertor: Optional[Callable[[Any], Any]] = None458+ if lenient_issubclass(type_, Path):459+ convertor = param_path_convertor460+ if lenient_issubclass(type_, Enum):461+ convertor = generate_enum_convertor(type_)462+ return convertor463+464+465 def param_path_convertor(value: Optional[str] = None) -> Optional[Path]:466 if value is not None:467 return Path(value)468 return None469 470 462-def generate_enum_convertor(enum: Type[Enum]) -> Callable[..., Any]:471+def generate_enum_convertor(enum: Type[Enum]) -> Callable[[Any], Any]:472 lower_val_map = {str(val.value).lower(): val for val in enum}473 474 def convertor(value: Any) -> Any:475 if value is not None:4 unmodified lines480 481 return convertor482 483 475-def generate_iter_convertor(convertor: Callable[[Any], Any]) -> Callable[..., Any]:476- def internal_convertor(value: Any) -> List[Any]:477- return [convertor(v) for v in value]484+def generate_list_convertor(485+ convertor: Optional[Callable[[Any], Any]]486+) -> Callable[[Sequence[Any]], List[Any]]:487+ def internal_convertor(value: Sequence[Any]) -> List[Any]:488+ return [convertor(v) if convertor else v for v in value]489 490 return internal_convertor491 492 493+def generate_tuple_convertor(494+ types: Sequence[Any],495+) -> Callable[[Tuple[Any, ...]], Tuple[Any, ...]]:496+ convertors = [determine_type_convertor(type_) for type_ in types]497+498+ def internal_convertor(param_args: Tuple[Any, ...]) -> Tuple[Any, ...]:499+ return tuple(500+ convertor(arg) if convertor else arg501+ for (convertor, arg) in zip(convertors, param_args)502+ )503+504+ return internal_convertor505+506+507 def get_callback(508 *,509 callback: Optional[Callable[..., Any]] = None,510 params: Sequence[click.Parameter] = [],144 unmodified lines655 else:656 annotation = str657 main_type = annotation658 is_list = False659+ is_tuple = False660 parameter_type: Any = None661 is_flag = None662 origin = getattr(main_type, "__origin__", None)663 if origin is not None:23 unmodified lines687 types.append(688 get_click_type(annotation=type_, parameter_info=parameter_info)689 )690 parameter_type = tuple(types)691+ is_tuple = True692 if parameter_type is None:693 parameter_type = get_click_type(694 annotation=main_type, parameter_info=parameter_info695 )669- convertor = None670- if lenient_issubclass(main_type, Path):671- convertor = param_path_convertor672- if lenient_issubclass(main_type, Enum):673- convertor = generate_enum_convertor(main_type)674- if convertor and is_list:675- convertor = generate_iter_convertor(convertor)676- # TODO: handle recursive conversion for tuples696+ convertor = determine_type_convertor(main_type)697+ if is_list:698+ convertor = generate_list_convertor(convertor)699+ if is_tuple:700+ convertor = generate_tuple_convertor(main_type.__args__)701 if isinstance(parameter_info, OptionInfo):702 if main_type is bool and not (parameter_info.is_flag is False):703 is_flag = True704 # Click doesn't accept a flag of type bool, only None, and then it sets it191 unmodified lines