Skip to content
Myr

⬆️ 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

32 files+167 added−46 removed

modified:.github/workflows/test.yml+1 added
modified:docs/tutorial/testing.md+1 added-1 removed
69 unmodified lines
70Then we check that the text printed to "standard output" contains the text that our CLI program prints.7172/// tip7374You 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.74You 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.7576///7778/// info
136 unmodified lines
modified:docs_src/testing/app01/test_main.py+2 added-2 removed
6 unmodified lines
78def 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.output
modified:docs_src/testing/app02/test_main.py+1 added-1 removed
6 unmodified lines
78def 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.output
modified:docs_src/testing/app02_an/test_main.py+1 added-1 removed
6 unmodified lines
78def 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.output
modified:docs_src/testing/app03/test_main.py+1 added-1 removed
10 unmodified lines
1112def 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.output
modified:tests/test_completion/test_completion_show.py+1 added-1 removed
144 unmodified lines
145 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.output
modified:tests/test_tutorial/test_commands/test_index/test_tutorial003.py-1 removed
10 unmodified lines
111213def 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.output
21 unmodified lines
modified:tests/test_tutorial/test_options/test_callback/test_tutorial001_an.py+2 added-1 removed
19 unmodified lines
2021def 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.output262728def test_script():29 result = subprocess.run(
5 unmodified lines
modified:tests/test_tutorial/test_options/test_callback/test_tutorial001.py+2 added-1 removed
19 unmodified lines
2021def 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.output262728def test_script():29 result = subprocess.run(
5 unmodified lines
modified:tests/test_tutorial/test_options/test_callback/test_tutorial003_an.py+2 added-1 removed
21 unmodified lines
2223def 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.output282930def test_script():31 result = subprocess.run(
20 unmodified lines
modified:tests/test_tutorial/test_options/test_callback/test_tutorial003.py+2 added-1 removed
21 unmodified lines
2223def 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.output282930def test_script():31 result = subprocess.run(
20 unmodified lines
modified:tests/test_tutorial/test_options/test_callback/test_tutorial004_an.py+2 added-1 removed
21 unmodified lines
2223def 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.output282930def test_script():31 result = subprocess.run(
20 unmodified lines
modified:tests/test_tutorial/test_options/test_callback/test_tutorial004.py+2 added-1 removed
21 unmodified lines
2223def 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.output282930def test_script():31 result = subprocess.run(
20 unmodified lines
modified:tests/test_tutorial/test_options/test_required/test_tutorial001_an.py+1 added-1 removed
14 unmodified lines
1516def 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.output202122def test_option_lastname():23 result = runner.invoke(app, ["Camila", "--lastname", "Gutiérrez"])
30 unmodified lines
modified:tests/test_tutorial/test_options/test_required/test_tutorial001.py+1 added-1 removed
14 unmodified lines
1516def 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.output202122def test_option_lastname():23 result = runner.invoke(app, ["Camila", "--lastname", "Gutiérrez"])
30 unmodified lines
modified:tests/test_tutorial/test_options/test_version/test_tutorial003_an.py+2 added-1 removed
20 unmodified lines
2122def 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.output272829def test_3():30 result = runner.invoke(app, ["--name", "Camila"])
26 unmodified lines
modified:tests/test_tutorial/test_options/test_version/test_tutorial003.py+2 added-1 removed
20 unmodified lines
2122def 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.output272829def test_3():30 result = runner.invoke(app, ["--name", "Camila"])
26 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_enum/test_tutorial001.py+10 added-2 removed
24 unmodified lines
25 assert result.exit_code == 026 assert "Training neural network of type: conv" in result.output272829def test_main_default():30 result = runner.invoke(app)31 assert result.exit_code == 032 assert "Training neural network of type: simple" in result.output333435def 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.output434445def 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 lines
modified:tests/test_tutorial/test_parameter_types/test_index/test_tutorial001.py+2 added-1 removed
33 unmodified lines
3435def 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.output404142def test_script():43 result = subprocess.run(
5 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_number/test_tutorial001_an.py+4 added-5 removed
51 unmodified lines
5253def 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.output585960def 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.output656667def test_negative_score():68 result = runner.invoke(app, ["5", "--age", "20", "--score", "-5"])
13 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_number/test_tutorial001.py+4 added-5 removed
51 unmodified lines
5253def 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.output585960def 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.output656667def test_negative_score():68 result = runner.invoke(app, ["5", "--age", "20", "--score", "-5"])
13 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_path/test_tutorial002_an.py+4 added-2 removed
17 unmodified lines
18 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.output252627def test_exists(tmpdir):
7 unmodified lines
3536def 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.output414243def test_script():44 result = subprocess.run(
5 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_path/test_tutorial002.py+4 added-2 removed
17 unmodified lines
18 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.output252627def test_exists(tmpdir):
7 unmodified lines
3536def 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.output414243def test_script():44 result = subprocess.run(
5 unmodified lines
added:tests/test_types.py+34 added
1from enum import Enum23import typer4from typer.testing import CliRunner56app = typer.Typer(context_settings={"token_normalize_func": str.lower})789class User(str, Enum):10 rick = "Rick"11 morty = "Morty"121314@app.command()15def hello(name: User = User.rick) -> None:16 print(f"Hello {name.value}!")171819runner = CliRunner()202122def 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.output2728 result = runner.invoke(app, ["--name", "Rick"])29 assert result.exit_code == 030 assert "Hello Rick!" in result.output3132 result = runner.invoke(app, ["--name", "RICK"])33 assert result.exit_code == 034 assert "Hello Rick!" in result.output
modified:typer/_completion_classes.py+12 added-4 removed
15 unmodified lines
16 Shells,17)1819try:20 from click.shell_completion import split_arg_string as click_split_arg_string21except 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 )2627try:28 import shellingham29except ImportError: # pragma: no cover30 shellingham = None31
18 unmodified lines
50 "prog_name": self.prog_name,51 }5253 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]5758 try:
28 unmodified lines
87 }8889 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 lines
138 }139140 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 lines
192193 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, incomplete199200 def format_completion(self, item: click.shell_completion.CompletionItem) -> str:
11 unmodified lines
added:typer/_types.py+27 added
1from enum import Enum2from typing import Generic, TypeVar, Union34import click56ParamTypeValue = TypeVar("ParamTypeValue")789class 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)2021 if ctx is not None and ctx.token_normalize_func is not None:22 normed_value = ctx.token_normalize_func(normed_value)2324 if not self.case_sensitive:25 normed_value = normed_value.casefold()2627 return normed_value
modified:typer/core.py+21 added-4 removed
327 unmodified lines
328 # 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.envvar
37 unmodified lines
374375 help = f"{help} {extra_str}" if help else f"{extra_str}"376 return name, help377378 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 lines
488 self, *, ctx: click.Context489 ) -> Optional[Union[Any, Callable[[], Any]]]:490 return _extract_default_help_str(self, ctx=ctx)491492 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]499500 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-false
10 unmodified lines
514 if any_slashes:515 any_prefix_is_slash = True516517 if not self.is_flag and not self.count:501 rv += f" {self.make_metavar()}"518 rv += f" {self.make_metavar(ctx=ctx)}"519520 return rv521522 rv = [_write_opts(self.opts)]
259 unmodified lines
modified:typer/main.py+7 added-1 removed
13 unmodified lines
14from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Type, Union15from uuid import UUID1617import click18from typer._types import TyperChoice1920from ._typing import get_args, get_origin, is_union21from .completion import get_completion_inspect_parameters22from .core import (
764 unmodified lines
787 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 cover
345 unmodified lines
modified:typer/rich_utils.py+7 added-1 removed
368 unmodified lines
369 secondary_opt_short_strs.append(opt_str)370371 # 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]380381 # Do it ourselves if this is a positional argument382 if (383 isinstance(param, click.Argument)
358 unmodified lines
added:.env+4 added
1# Environment variables automatically read by VS Code, e.g. running tests23# For tests, a large terminal width4TERMINAL_WIDTH=3000
modified:pyproject.toml+1 added-1 removed
32 unmodified lines
33 "Programming Language :: Python :: 3.13",34 "License :: OSI Approved :: MIT License",35]36dependencies = [37 "click >= 8.0.0,<8.2",37 "click >= 8.0.0",38 "typing-extensions >= 3.7.4.3",39]40readme = "README.md"41[project.urls]
162 unmodified lines