Skip to content
Myr

🐛 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

3 files+128 added−44 removed

modified:tests/test_others.py-32 removed
1import os2import subprocess3from pathlib import Path4from typing import Optional4from unittest import mock56import click7import pytest
6 unmodified lines
1415runner = CliRunner()161719def 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.output484918def test_help_from_info():19 # Mainly for coverage/completeness20 value = solve_typer_info_help(TyperInfo())21 assert value is None
192 unmodified lines
added:tests/test_type_conversion.py+92 added
1from enum import Enum2from pathlib import Path3from typing import List, Optional, Tuple45import pytest6import typer7from typer.testing import CliRunner89runner = CliRunner()101112def test_optional():13 app = typer.Typer()1415 @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")2122 result = runner.invoke(app)23 assert result.exit_code == 024 assert "No user" in result.output2526 result = runner.invoke(app, ["--user", "Camila"])27 assert result.exit_code == 028 assert "User: Camila" in result.output293031def test_no_type():32 app = typer.Typer()3334 @app.command()35 def no_type(user):36 typer.echo(f"User: {user}")3738 result = runner.invoke(app, ["Camila"])39 assert result.exit_code == 040 assert "User: Camila" in result.output414243class SomeEnum(Enum):44 ONE = "one"45 TWO = "two"46 THREE = "three"474849@pytest.mark.parametrize(50 "type_annotation",51 [List[Path], List[SomeEnum], List[str]],52)53def 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()5859 @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)6465 result = runner.invoke(app, ["one", "two", "three"])66 assert result.exit_code == 0676869@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)79def 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()8485 @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)9091 result = runner.invoke(app, ["one", "two"])92 assert result.exit_code == 0
modified:typer/main.py+36 added-12 removed
451 unmodified lines
452 )453 return command454455456def 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 convertor463464465def param_path_convertor(value: Optional[str] = None) -> Optional[Path]:466 if value is not None:467 return Path(value)468 return None469470462def generate_enum_convertor(enum: Type[Enum]) -> Callable[..., Any]:471def generate_enum_convertor(enum: Type[Enum]) -> Callable[[Any], Any]:472 lower_val_map = {str(val.value).lower(): val for val in enum}473474 def convertor(value: Any) -> Any:475 if value is not None:
4 unmodified lines
480481 return convertor482483475def 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]484def 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]489490 return internal_convertor491492493def generate_tuple_convertor(494 types: Sequence[Any],495) -> Callable[[Tuple[Any, ...]], Tuple[Any, ...]]:496 convertors = [determine_type_convertor(type_) for type_ in types]497498 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 )503504 return internal_convertor505506507def get_callback(508 *,509 callback: Optional[Callable[..., Any]] = None,510 params: Sequence[click.Parameter] = [],
144 unmodified lines
655 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 lines
687 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 it
191 unmodified lines