⬆️ Add compatibility with Click 8.2 (#1222)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sebastián Ramírez · committed by GitHub · parent 3ce5032 · Browse files · 32 files·+167 added−46 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
32 files+167 added−46 removed
- tests:+81 added−29 removed
- other:+86 added−17 removed
Provenance
- Commit
74e0923- Tree
a28626c- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
3ce5032
32 files changed+167 added−46 removed
modified:.github/workflows/test.yml+1 added
55 unmodified lines56575859606162636465 unmodified lines55 unmodified lines pyproject.toml - name: Install Dependencies run: uv pip install -r requirements-tests.txt - name: Lint if: matrix.python-version != '3.7' && matrix.python-version != '3.8' && matrix.python-version != '3.9' run: bash scripts/lint.sh - run: mkdir coverage - run: bash ./scripts/test-files.sh - name: Test65 unmodified linesmodified:docs/tutorial/testing.md+1 added-1 removed
69 unmodified lines70 Then we check that the text printed to "standard output" contains the text that our CLI program prints.71 72 /// tip73 74-You could also check output sent to "standard error" (`stderr`) instead of "standard output" (`stdout`). To do so, make sure your `CliRunner` instance is created with the `mix_stderr=False` argument. You need this setting to be able to access `result.stderr` in tests.74+You could also check the output sent to "standard error" (`stderr`) or "standard output" (`stdout`) independently by accessing `result.stdout` and `result.stderr` in your tests.75 76 ///77 78 /// info136 unmodified linesmodified:docs_src/testing/app01/test_main.py+2 added-2 removed
6 unmodified lines7 8 def test_app():9 result = runner.invoke(app, ["Camila", "--city", "Berlin"])10 assert result.exit_code == 011- assert "Hello Camila" in result.stdout12- assert "Let's have a coffee in Berlin" in result.stdout11+ assert "Hello Camila" in result.output12+ assert "Let's have a coffee in Berlin" in result.outputmodified:docs_src/testing/app02/test_main.py+1 added-1 removed
6 unmodified lines7 8 def test_app():9 result = runner.invoke(app, ["Camila"], input="camila@example.com\n")10 assert result.exit_code == 011- assert "Hello Camila, your email is: camila@example.com" in result.stdout11+ assert "Hello Camila, your email is: camila@example.com" in result.outputmodified:docs_src/testing/app02_an/test_main.py+1 added-1 removed
6 unmodified lines7 8 def test_app():9 result = runner.invoke(app, ["Camila"], input="camila@example.com\n")10 assert result.exit_code == 011- assert "Hello Camila, your email is: camila@example.com" in result.stdout11+ assert "Hello Camila, your email is: camila@example.com" in result.outputmodified:docs_src/testing/app03/test_main.py+1 added-1 removed
10 unmodified lines11 12 def test_app():13 result = runner.invoke(app, ["--name", "Camila"])14 assert result.exit_code == 015- assert "Hello Camila" in result.stdout15+ assert "Hello Camila" in result.outputmodified:tests/test_completion/test_completion_show.py+1 added-1 removed
144 unmodified lines145 with mock.patch.object(146 shellingham, "detect_shell", return_value=("xshell", "/usr/bin/xshell")147 ):148 result = runner.invoke(app, ["--show-completion"])149- assert "Shell xshell not supported" in result.stdout149+ assert "Shell xshell not supported" in result.outputmodified:tests/test_tutorial/test_commands/test_index/test_tutorial003.py-1 removed
10 unmodified lines11 12 13 def test_no_arg():14 result = runner.invoke(app)15- assert result.exit_code == 015 assert "[OPTIONS] COMMAND [ARGS]..." in result.output16 assert "Commands" in result.output17 assert "create" in result.output18 assert "delete" in result.output21 unmodified linesmodified:tests/test_tutorial/test_options/test_callback/test_tutorial001_an.py+2 added-1 removed
19 unmodified lines20 21 def test_2():22 result = runner.invoke(app, ["--name", "rick"])23 assert result.exit_code != 024- assert "Invalid value for '--name': Only Camila is allowed" in result.output24+ assert "Invalid value for '--name'" in result.output25+ assert "Only Camila is allowed" in result.output26 27 28 def test_script():29 result = subprocess.run(5 unmodified linesmodified:tests/test_tutorial/test_options/test_callback/test_tutorial001.py+2 added-1 removed
19 unmodified lines20 21 def test_2():22 result = runner.invoke(app, ["--name", "rick"])23 assert result.exit_code != 024- assert "Invalid value for '--name': Only Camila is allowed" in result.output24+ assert "Invalid value for '--name'" in result.output25+ assert "Only Camila is allowed" in result.output26 27 28 def test_script():29 result = subprocess.run(5 unmodified linesmodified:tests/test_tutorial/test_options/test_callback/test_tutorial003_an.py+2 added-1 removed
21 unmodified lines22 23 def test_2():24 result = runner.invoke(app, ["--name", "rick"])25 assert result.exit_code != 026- assert "Invalid value for '--name': Only Camila is allowed" in result.output26+ assert "Invalid value for '--name'" in result.output27+ assert "Only Camila is allowed" in result.output28 29 30 def test_script():31 result = subprocess.run(20 unmodified linesmodified:tests/test_tutorial/test_options/test_callback/test_tutorial003.py+2 added-1 removed
21 unmodified lines22 23 def test_2():24 result = runner.invoke(app, ["--name", "rick"])25 assert result.exit_code != 026- assert "Invalid value for '--name': Only Camila is allowed" in result.output26+ assert "Invalid value for '--name'" in result.output27+ assert "Only Camila is allowed" in result.output28 29 30 def test_script():31 result = subprocess.run(20 unmodified linesmodified:tests/test_tutorial/test_options/test_callback/test_tutorial004_an.py+2 added-1 removed
21 unmodified lines22 23 def test_2():24 result = runner.invoke(app, ["--name", "rick"])25 assert result.exit_code != 026- assert "Invalid value for '--name': Only Camila is allowed" in result.output26+ assert "Invalid value for '--name'" in result.output27+ assert "Only Camila is allowed" in result.output28 29 30 def test_script():31 result = subprocess.run(20 unmodified linesmodified:tests/test_tutorial/test_options/test_callback/test_tutorial004.py+2 added-1 removed
21 unmodified lines22 23 def test_2():24 result = runner.invoke(app, ["--name", "rick"])25 assert result.exit_code != 026- assert "Invalid value for '--name': Only Camila is allowed" in result.output26+ assert "Invalid value for '--name'" in result.output27+ assert "Only Camila is allowed" in result.output28 29 30 def test_script():31 result = subprocess.run(20 unmodified linesmodified:tests/test_tutorial/test_options/test_required/test_tutorial001_an.py+1 added-1 removed
14 unmodified lines15 16 def test_1():17 result = runner.invoke(app, ["Camila"])18 assert result.exit_code != 019- assert "Missing option '--lastname'." in result.output19+ assert "Missing option '--lastname'" in result.output20 21 22 def test_option_lastname():23 result = runner.invoke(app, ["Camila", "--lastname", "Gutiérrez"])30 unmodified linesmodified:tests/test_tutorial/test_options/test_required/test_tutorial001.py+1 added-1 removed
14 unmodified lines15 16 def test_1():17 result = runner.invoke(app, ["Camila"])18 assert result.exit_code != 019- assert "Missing option '--lastname'." in result.output19+ assert "Missing option '--lastname'" in result.output20 21 22 def test_option_lastname():23 result = runner.invoke(app, ["Camila", "--lastname", "Gutiérrez"])30 unmodified linesmodified:tests/test_tutorial/test_options/test_version/test_tutorial003_an.py+2 added-1 removed
20 unmodified lines21 22 def test_2():23 result = runner.invoke(app, ["--name", "rick"])24 assert result.exit_code != 025- assert "Invalid value for '--name': Only Camila is allowed" in result.output25+ assert "Invalid value for '--name'" in result.output26+ assert "Only Camila is allowed" in result.output27 28 29 def test_3():30 result = runner.invoke(app, ["--name", "Camila"])26 unmodified linesmodified:tests/test_tutorial/test_options/test_version/test_tutorial003.py+2 added-1 removed
20 unmodified lines21 22 def test_2():23 result = runner.invoke(app, ["--name", "rick"])24 assert result.exit_code != 025- assert "Invalid value for '--name': Only Camila is allowed" in result.output25+ assert "Invalid value for '--name'" in result.output26+ assert "Only Camila is allowed" in result.output27 28 29 def test_3():30 result = runner.invoke(app, ["--name", "Camila"])26 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_enum/test_tutorial001.py+10 added-2 removed
24 unmodified lines25 assert result.exit_code == 026 assert "Training neural network of type: conv" in result.output27 28 29+def test_main_default():30+ result = runner.invoke(app)31+ assert result.exit_code == 032+ assert "Training neural network of type: simple" in result.output33+34+35 def test_invalid_case():36 result = runner.invoke(app, ["--network", "CONV"])37 assert result.exit_code != 032- assert "Invalid value for '--network': 'CONV' is not one of" in result.output38+ assert "Invalid value for '--network'" in result.output39+ assert "'CONV' is not one of" in result.output40 assert "simple" in result.output41 assert "conv" in result.output42 assert "lstm" in result.output43 44 45 def test_invalid_other():46 result = runner.invoke(app, ["--network", "capsule"])47 assert result.exit_code != 041- assert "Invalid value for '--network': 'capsule' is not one of" in result.output48+ assert "Invalid value for '--network'" in result.output49+ assert "'capsule' is not one of" in result.output50 assert "simple" in result.output51 assert "conv" in result.output52 assert "lstm" in result.output53 8 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_index/test_tutorial001.py+2 added-1 removed
33 unmodified lines34 35 def test_invalid():36 result = runner.invoke(app, ["Camila", "--age", "15.3"])37 assert result.exit_code != 038- assert "Invalid value for '--age': '15.3' is not a valid integer" in result.output38+ assert "Invalid value for '--age'" in result.output39+ assert "'15.3' is not a valid integer" in result.output40 41 42 def test_script():43 result = subprocess.run(5 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_number/test_tutorial001_an.py+4 added-5 removed
51 unmodified lines52 53 def test_invalid_age():54 result = runner.invoke(app, ["5", "--age", "15"])55 assert result.exit_code != 056- assert "Invalid value for '--age': 15 is not in the range x>=18" in result.output56+ assert "Invalid value for '--age'" in result.output57+ assert "15 is not in the range x>=18" in result.output58 59 60 def test_invalid_score():61 result = runner.invoke(app, ["5", "--age", "20", "--score", "100.5"])62 assert result.exit_code != 062- assert (63- "Invalid value for '--score': 100.5 is not in the range x<=100."64- in result.output65- )63+ assert "Invalid value for '--score'" in result.output64+ assert "100.5 is not in the range x<=100." in result.output65 66 67 def test_negative_score():68 result = runner.invoke(app, ["5", "--age", "20", "--score", "-5"])13 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_number/test_tutorial001.py+4 added-5 removed
51 unmodified lines52 53 def test_invalid_age():54 result = runner.invoke(app, ["5", "--age", "15"])55 assert result.exit_code != 056- assert "Invalid value for '--age': 15 is not in the range x>=18" in result.output56+ assert "Invalid value for '--age'" in result.output57+ assert "15 is not in the range x>=18" in result.output58 59 60 def test_invalid_score():61 result = runner.invoke(app, ["5", "--age", "20", "--score", "100.5"])62 assert result.exit_code != 062- assert (63- "Invalid value for '--score': 100.5 is not in the range x<=100."64- in result.output65- )63+ assert "Invalid value for '--score'" in result.output64+ assert "100.5 is not in the range x<=100." in result.output65 66 67 def test_negative_score():68 result = runner.invoke(app, ["5", "--age", "20", "--score", "-5"])13 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_path/test_tutorial002_an.py+4 added-2 removed
17 unmodified lines18 if config_file.exists(): # pragma: no cover19 config_file.unlink()20 result = runner.invoke(app, ["--config", f"{config_file}"])21 assert result.exit_code != 022- assert "Invalid value for '--config': File" in result.output22+ assert "Invalid value for '--config'" in result.output23+ assert "File" in result.output24 assert "does not exist" in result.output25 26 27 def test_exists(tmpdir):7 unmodified lines35 36 def test_dir():37 result = runner.invoke(app, ["--config", "./"])38 assert result.exit_code != 038- assert "Invalid value for '--config': File './' is a directory." in result.output39+ assert "Invalid value for '--config'" in result.output40+ assert "File './' is a directory." in result.output41 42 43 def test_script():44 result = subprocess.run(5 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_path/test_tutorial002.py+4 added-2 removed
17 unmodified lines18 if config_file.exists(): # pragma: no cover19 config_file.unlink()20 result = runner.invoke(app, ["--config", f"{config_file}"])21 assert result.exit_code != 022- assert "Invalid value for '--config': File" in result.output22+ assert "Invalid value for '--config'" in result.output23+ assert "File" in result.output24 assert "does not exist" in result.output25 26 27 def test_exists(tmpdir):7 unmodified lines35 36 def test_dir():37 result = runner.invoke(app, ["--config", "./"])38 assert result.exit_code != 038- assert "Invalid value for '--config': File './' is a directory." in result.output39+ assert "Invalid value for '--config'" in result.output40+ assert "File './' is a directory." in result.output41 42 43 def test_script():44 result = subprocess.run(5 unmodified linesadded:tests/test_types.py+34 added
1+from enum import Enum2+3+import typer4+from typer.testing import CliRunner5+6+app = typer.Typer(context_settings={"token_normalize_func": str.lower})7+8+9+class User(str, Enum):10+ rick = "Rick"11+ morty = "Morty"12+13+14+@app.command()15+def hello(name: User = User.rick) -> None:16+ print(f"Hello {name.value}!")17+18+19+runner = CliRunner()20+21+22+def test_enum_choice() -> None:23+ # This test is only for coverage of the new custom TyperChoice class24+ result = runner.invoke(app, ["--name", "morty"], catch_exceptions=False)25+ assert result.exit_code == 026+ assert "Hello Morty!" in result.output27+28+ result = runner.invoke(app, ["--name", "Rick"])29+ assert result.exit_code == 030+ assert "Hello Rick!" in result.output31+32+ result = runner.invoke(app, ["--name", "RICK"])33+ assert result.exit_code == 034+ assert "Hello Rick!" in result.outputmodified:typer/_completion_classes.py+12 added-4 removed
15 unmodified lines16 Shells,17 )18 19 try:20+ from click.shell_completion import split_arg_string as click_split_arg_string21+except ImportError: # pragma: no cover22+ # TODO: when removing support for Click < 8.2, remove this import23+ from click.parser import ( # type: ignore[no-redef]24+ split_arg_string as click_split_arg_string,25+ )26+27+try:28 import shellingham29 except ImportError: # pragma: no cover30 shellingham = None31 18 unmodified lines50 "prog_name": self.prog_name,51 }52 53 def get_completion_args(self) -> Tuple[List[str], str]:46- cwords = click.parser.split_arg_string(os.environ["COMP_WORDS"])54+ cwords = click_split_arg_string(os.environ["COMP_WORDS"])55 cword = int(os.environ["COMP_CWORD"])56 args = cwords[1:cword]57 58 try:28 unmodified lines87 }88 89 def get_completion_args(self) -> Tuple[List[str], str]:90 completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")83- cwords = click.parser.split_arg_string(completion_args)91+ cwords = click_split_arg_string(completion_args)92 args = cwords[1:]93 if args and not completion_args.endswith(" "):94 incomplete = args[-1]95 args = args[:-1]42 unmodified lines138 }139 140 def get_completion_args(self) -> Tuple[List[str], str]:141 completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")134- cwords = click.parser.split_arg_string(completion_args)142+ cwords = click_split_arg_string(completion_args)143 args = cwords[1:]144 if args and not completion_args.endswith(" "):145 incomplete = args[-1]146 args = args[:-1]45 unmodified lines192 193 def get_completion_args(self) -> Tuple[List[str], str]:194 completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")195 incomplete = os.getenv("_TYPER_COMPLETE_WORD_TO_COMPLETE", "")188- cwords = click.parser.split_arg_string(completion_args)196+ cwords = click_split_arg_string(completion_args)197 args = cwords[1:-1] if incomplete else cwords[1:]198 return args, incomplete199 200 def format_completion(self, item: click.shell_completion.CompletionItem) -> str:11 unmodified linesadded:typer/_types.py+27 added
1+from enum import Enum2+from typing import Generic, TypeVar, Union3+4+import click5+6+ParamTypeValue = TypeVar("ParamTypeValue")7+8+9+class TyperChoice(click.Choice, Generic[ParamTypeValue]): # type: ignore[type-arg]10+ def normalize_choice(11+ self, choice: ParamTypeValue, ctx: Union[click.Context, None]12+ ) -> str:13+ # Click 8.2.0 added a new method `normalize_choice` to the `Choice` class14+ # to support enums, but it uses the enum names, while Typer has always used the15+ # enum values.16+ # This class overrides that method to maintain the previous behavior.17+ # In Click:18+ # normed_value = choice.name if isinstance(choice, Enum) else str(choice)19+ normed_value = str(choice.value) if isinstance(choice, Enum) else str(choice)20+21+ if ctx is not None and ctx.token_normalize_func is not None:22+ normed_value = ctx.token_normalize_func(normed_value)23+24+ if not self.case_sensitive:25+ normed_value = normed_value.casefold()26+27+ return normed_valuemodified:typer/core.py+21 added-4 removed
327 unmodified lines328 # Modified version of click.core.Option.get_help_record()329 # to support Arguments330 if self.hidden:331 return None332- name = self.make_metavar()332+ name = self.make_metavar(ctx=ctx)333 help = self.help or ""334 extra = []335 if self.show_envvar:336 envvar = self.envvar37 unmodified lines374 375 help = f"{help} {extra_str}" if help else f"{extra_str}"376 return name, help377 378- def make_metavar(self) -> str:378+ def make_metavar(self, ctx: Union[click.Context, None] = None) -> str:379 # Modified version of click.core.Argument.make_metavar()380 # to include Argument name381 if self.metavar is not None:382 return self.metavar383 var = (self.name or "").upper()384 if not self.required:385 var = f"[{var}]"386+ # TODO: When deprecating Click < 8.2, remove this387+ signature = inspect.signature(self.type.get_metavar)388+ if "ctx" in signature.parameters:389+ # Click >= 8.2390+ type_var = self.type.get_metavar(self, ctx=ctx) # type: ignore[arg-type]391+ else:392+ # Click < 8.2386- type_var = self.type.get_metavar(self)393+ type_var = self.type.get_metavar(self) # type: ignore[call-arg]394+ # TODO: /When deprecating Click < 8.2, remove this, uncomment the line below395+ # type_var = self.type.get_metavar(self, ctx=ctx)396 if type_var:397 var += f":{type_var}"398 if self.nargs != 1:399 var += "..."88 unmodified lines488 self, *, ctx: click.Context489 ) -> Optional[Union[Any, Callable[[], Any]]]:490 return _extract_default_help_str(self, ctx=ctx)491 492+ def make_metavar(self, ctx: Union[click.Context, None] = None) -> str:493+ signature = inspect.signature(super().make_metavar)494+ if "ctx" in signature.parameters:495+ # Click >= 8.2496+ return super().make_metavar(ctx=ctx) # type: ignore[arg-type]497+ # Click < 8.2498+ return super().make_metavar() # type: ignore[call-arg]499+500 def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]:501 # Duplicate all of Click's logic only to modify a single line, to allow boolean502 # flags with only names for False values as it's currently supported by Typer503 # Ref: https://typer.tiangolo.com/tutorial/parameter-types/bool/#only-names-for-false10 unmodified lines514 if any_slashes:515 any_prefix_is_slash = True516 517 if not self.is_flag and not self.count:501- rv += f" {self.make_metavar()}"518+ rv += f" {self.make_metavar(ctx=ctx)}"519 520 return rv521 522 rv = [_write_opts(self.opts)]259 unmodified linesmodified:typer/main.py+7 added-1 removed
13 unmodified lines14 from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Type, Union15 from uuid import UUID16 17 import click18+from typer._types import TyperChoice19 20 from ._typing import get_args, get_origin, is_union21 from .completion import get_completion_inspect_parameters22 from .core import (764 unmodified lines787 lazy=parameter_info.lazy,788 atomic=parameter_info.atomic,789 )790 elif lenient_issubclass(annotation, Enum):791+ # The custom TyperChoice is only needed for Click < 8.2.0, to parse the792+ # command line values matching them to the enum values. Click 8.2.0 added793+ # support for enum values but reading enum names.794+ # Passing here the list of enum values (instead of just the enum) accounts for795+ # Click < 8.2.0.790- return click.Choice(796+ return TyperChoice(797 [item.value for item in annotation],798 case_sensitive=parameter_info.case_sensitive,799 )800 raise RuntimeError(f"Type not yet supported: {annotation}") # pragma: no cover345 unmodified linesmodified:typer/rich_utils.py+7 added-1 removed
368 unmodified lines369 secondary_opt_short_strs.append(opt_str)370 371 # Column for a metavar, if we have one372 metavar = Text(style=STYLE_METAVAR, overflow="fold")373+ # TODO: when deprecating Click < 8.2, make ctx required374+ signature = inspect.signature(param.make_metavar)375+ if "ctx" in signature.parameters:373- metavar_str = param.make_metavar()376+ metavar_str = param.make_metavar(ctx=ctx)377+ else:378+ # Click < 8.2379+ metavar_str = param.make_metavar() # type: ignore[call-arg]380 381 # Do it ourselves if this is a positional argument382 if (383 isinstance(param, click.Argument)358 unmodified linesadded:.env+4 added
1+# Environment variables automatically read by VS Code, e.g. running tests2+3+# For tests, a large terminal width4+TERMINAL_WIDTH=3000modified:pyproject.toml+1 added-1 removed
32 unmodified lines33 "Programming Language :: Python :: 3.13",34 "License :: OSI Approved :: MIT License",35 ]36 dependencies = [37- "click >= 8.0.0,<8.2",37+ "click >= 8.0.0",38 "typing-extensions >= 3.7.4.3",39 ]40 readme = "README.md"41 [project.urls]162 unmodified lines