Skip to content
Myr

Split out types tests.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Eddie Girling · committed by Eddie Girling · parent 87f7a31 · Browse files · 13 files+487 added−438 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

13 files+487 added−438 removed

  • tests:+487 added−438 removed

13 files+487 added−438 removed

added:tests/test_exceptions/__init__.py
added:tests/test_exceptions/test_FileError.py+6 added
1import click234def test_file_error_surrogates():5 message = click.FileError(filename="\udcff").format_message()6 assert message == "Could not open file '�': unknown error"
added:tests/test_types/__init__.py
added:tests/test_types/test_Choice.py+7 added
1import click234def test_choice_get_invalid_choice_message():5 choice = click.Choice(["a", "b", "c"])6 message = choice.get_invalid_choice_message("d", ctx=None)7 assert message == "'d' is not one of 'a', 'b', 'c'."
added:tests/test_types/test_convert_type.py+108 added
1import datetime2import uuid34import pytest56import click789@pytest.mark.parametrize(10 "default",11 [12 # Empty sequences fall back to STRING because ``_guess_type`` returns None.13 [],14 (),15 # Container types are guessed from the default but are not natively16 # supported, so they reach STRING through a different code path.17 set(),18 {1, 2},19 frozenset(),20 frozenset(["git"]),21 {},22 {"a": 1},23 ],24)25def test_convert_type_from_container_default(default):26 """Container defaults are not natively supported and fall back to STRING.2728 Refs: https://github.com/pallets/click/issues/303629 """30 assert click.types.convert_type(None, default) is click.STRING313233@pytest.mark.parametrize(34 ("container_type", "value", "expected"),35 [36 (set, "a,b,c", {"a", ",", "b", "c"}),37 (frozenset, "abc", frozenset({"a", "b", "c"})),38 ],39)40def test_explicit_container_type_splits_string(container_type, value, expected):41 """An explicit ``set`` or ``frozenset`` type wraps the builtin in a42 ``FuncParamType``, which splits CLI strings character-wise.4344 Refs: https://github.com/pallets/click/issues/303645 """46 param_type = click.types.convert_type(container_type)47 assert isinstance(param_type, click.types.FuncParamType)48 assert param_type.convert(value, None, None) == expected495051@pytest.mark.parametrize(52 ("default", "expected"),53 [54 # Recognized scalars.55 (None, click.STRING),56 ("git", click.STRING),57 (5, click.INT),58 (1.5, click.FLOAT),59 (True, click.BOOL),60 # An empty sequence gives no item to read.61 ([], click.STRING),62 ((), click.STRING),63 # A sequence gives the type of its first item only.64 ([1, 2], click.INT),65 ((1, 2), click.INT),66 ([1.5, 2.5], click.FLOAT),67 ([1, "git"], click.INT),68 # Everything else falls back to STRING, including types Click ships.69 ({1, 2}, click.STRING),70 (frozenset({1, 2}), click.STRING),71 ({"a": 1}, click.STRING),72 (uuid.UUID(int=0), click.STRING),73 (datetime.datetime(2026, 1, 1), click.STRING),74 (b"git", click.STRING),75 (object(), click.STRING),76 ],77)78def test_type_inferred_from_default(default, expected):79 """Every row of the type-inference table in ``docs/parameter-types.md``.8081 Keep the two in step: a change here is a change to documented behavior.8283 Refs: https://github.com/pallets/click/issues/303684 """85 assert click.types.convert_type(None, default) is expected868788def test_type_inferred_from_nested_sequence_default():89 """A sequence of sequences gives a composite ``Tuple`` of the inner types.9091 This is the one table row that is not a singleton ``ParamType``.9293 Refs: https://github.com/pallets/click/issues/303694 """95 param_type = click.types.convert_type(None, [(1, "git")])96 assert isinstance(param_type, click.Tuple)97 assert param_type.types == [click.INT, click.STRING]9899100def test_explicit_dict_type_rejects_string():101 """An explicit ``dict`` type cannot convert a plain CLI string at all.102103 Refs: https://github.com/pallets/click/issues/3036104 """105 param_type = click.types.convert_type(dict)106 assert isinstance(param_type, click.types.FuncParamType)107 with pytest.raises(click.BadParameter):108 param_type.convert("abc", None, None)
added:tests/test_types/test_File.py+31 added
1import pytest23import click456@pytest.mark.parametrize(7 "type",8 [9 click.File(mode="r"),10 click.File(mode="r", lazy=True),11 ],12)13def test_file_surrogates(type, tmp_path):14 """Ensures that the error handling in ``click.File`` is robust.1516 ``EILSEQ`` shows up with rootless Podman (FUSE-backed paths) and on filesystems17 that reject non-UTF-8 names, like ZFS with ``utf8only=on``.1819 See: https://github.com/pallets/click/issues/263420 """21 path = tmp_path / "\udcff"22 match = (23 # Common case: �': No such file or directory.24 r"(�': No such file or directory"25 # BSD/macOS libc special case (EILSEQ).26 r"|Illegal byte sequence"27 # glibc special case (EILSEQ).28 r"|Invalid or incomplete multibyte or wide character)"29 )30 with pytest.raises(click.BadParameter, match=match):31 type.convert(path, None, None)
added:tests/test_types/test_FloatRange.py+42 added
1import pytest23import click456@pytest.mark.parametrize(7 ("type", "value", "expect"),8 [9 (click.FloatRange(0.5, 1.5), "1.2", 1.2),10 (click.FloatRange(0.5, min_open=True), "0.51", 0.51),11 (click.FloatRange(max=1.5, max_open=True), "1.49", 1.49),12 (click.FloatRange(0.5, clamp=True), "-0.0", 0.5),13 (click.FloatRange(max=1.5, clamp=True), "inf", 1.5),14 ],15)16def test_range(type, value, expect):17 assert type.convert(value, None, None) == expect181920@pytest.mark.parametrize(21 ("type", "value", "expect"),22 [23 (click.FloatRange(0.5, min_open=True), 0.5, "x>0.5"),24 (click.FloatRange(max=1.5, max_open=True), 1.5, "x<1.5"),25 ],26)27def test_range_fail(type, value, expect):28 with pytest.raises(click.BadParameter) as exc_info:29 type.convert(value, None, None)3031 assert expect in exc_info.value.message323334def test_float_range_no_clamp_open():35 with pytest.raises(TypeError):36 click.FloatRange(0, 1, max_open=True, clamp=True)3738 sneaky = click.FloatRange(0, 1, max_open=True)39 sneaky.clamp = True4041 with pytest.raises(RuntimeError):42 sneaky.convert("1.5", None, None)
added:tests/test_types/test_FuncParamType.py+22 added
1import pytest23import click456@pytest.mark.parametrize(7 ("error_message", "expected"),8 [9 ("bad value: nope", "bad value: nope"),10 ("", "nope"),11 ],12)13def test_func_param_type_uses_value_error_message(error_message, expected):14 def parse(value):15 raise ValueError(error_message if error_message else "")1617 func_type = click.types.FuncParamType(parse)1819 with pytest.raises(click.BadParameter) as exc_info:20 func_type.convert("nope", None, None)2122 assert expected in exc_info.value.message
added:tests/test_types/test_IntRange.py+38 added
1import pytest23import click456@pytest.mark.parametrize(7 ("type", "value", "expect"),8 [9 (click.IntRange(0, 5), "3", 3),10 (click.IntRange(5), "5", 5),11 (click.IntRange(5), "100", 100),12 (click.IntRange(max=5), "5", 5),13 (click.IntRange(max=5), "-100", -100),14 (click.IntRange(0, clamp=True), "-1", 0),15 (click.IntRange(max=5, clamp=True), "6", 5),16 (click.IntRange(0, min_open=True, clamp=True), "0", 1),17 (click.IntRange(max=5, max_open=True, clamp=True), "5", 4),18 ],19)20def test_range(type, value, expect):21 assert type.convert(value, None, None) == expect222324@pytest.mark.parametrize(25 ("type", "value", "expect"),26 [27 (click.IntRange(0, 5), "6", "6 is not in the range 0<=x<=5."),28 (click.IntRange(5), "4", "4 is not in the range x>=5."),29 (click.IntRange(max=5), "6", "6 is not in the range x<=5."),30 (click.IntRange(0, 5, min_open=True), 0, "0<x<=5"),31 (click.IntRange(0, 5, max_open=True), 5, "0<=x<5"),32 ],33)34def test_range_fail(type, value, expect):35 with pytest.raises(click.BadParameter) as exc_info:36 type.convert(value, None, None)3738 assert expect in exc_info.value.message
added:tests/test_types/test_ParamType.py+24 added
1import typing as t23import click456def test_param_type_input_parameter_defaults_at_runtime():7 """Omitting the input type parameter works at runtime on every8 supported Python. The ``Any`` default is native (PEP 696) on Python9 3.13+, and backfilled by ``ParamType.__class_getitem__`` before10 that."""11 assert t.get_args(click.ParamType[int]) == (int, t.Any)12 assert t.get_args(click.ParamType[int, str]) == (int, str)131415def test_param_type_subclass_omitting_input_parameter():16 class DoublingType(click.ParamType[int]):17 name = "doubling"1819 def convert(self, value, param, ctx):20 return int(value) * 22122 doubling = DoublingType()23 assert doubling("21") == 4224 assert doubling(None) is None
added:tests/test_types/test_Path.py+185 added
1import os2import pathlib3import platform4import subprocess5import sys6import tempfile78import pytest910import click111213def test_path_dash_no_byteswarning():14 """Detecting the ``-`` dash sentinel must not compare ``bytes`` against15 ``str``, which raises a ``BytesWarning`` under ``python -bb``.1617 The warning is only emitted when the interpreter runs with ``-b``, so this18 has to be checked in a subprocess. ``-bb`` turns the warning into an error,19 so a clean exit means no mismatched comparison happened.20 """21 program = (22 "import click\n"23 "convert = click.Path(allow_dash=True).convert\n"24 "for value in ('-', '', b'-', b''):\n"25 " convert(value, None, None)\n"26 )27 result = subprocess.run(28 [sys.executable, "-bb", "-c", program],29 capture_output=True,30 text=True,31 )32 assert result.returncode == 0, result.stderr33 assert "BytesWarning" not in result.stderr343536def _symlinks_supported():37 with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:38 target = os.path.join(tempdir, "target")39 open(target, "w").close()40 link = os.path.join(tempdir, "link")4142 try:43 os.symlink(target, link)44 return True45 except OSError:46 return False474849@pytest.mark.skipif(50 not _symlinks_supported(), reason="The current OS or FS doesn't support symlinks."51)52def test_path_resolve_symlink(tmp_path, runner):53 test_file = tmp_path / "file"54 test_file_str = os.fspath(test_file)55 test_file.write_text("")5657 path_type = click.Path(resolve_path=True)58 param = click.Argument(["a"], type=path_type)59 ctx = click.Context(click.Command("cli", params=[param]))6061 test_dir = tmp_path / "dir"62 test_dir.mkdir()6364 abs_link = test_dir / "abs"65 abs_link.symlink_to(test_file)66 abs_rv = path_type.convert(os.fspath(abs_link), param, ctx)67 assert abs_rv == test_file_str6869 rel_link = test_dir / "rel"70 rel_link.symlink_to(pathlib.Path("..") / "file")71 rel_rv = path_type.convert(os.fspath(rel_link), param, ctx)72 assert rel_rv == test_file_str737475def _non_utf8_filenames_supported():76 with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:77 try:78 f = open(os.path.join(tempdir, "\udcff"), "w")79 except OSError:80 return False8182 f.close()83 return True848586@pytest.mark.skipif(87 not _non_utf8_filenames_supported(),88 reason="The current OS or FS doesn't support non-UTF-8 filenames.",89)90def test_path_surrogates(tmp_path, monkeypatch):91 monkeypatch.chdir(tmp_path)92 type = click.Path(exists=True)93 path = pathlib.Path("\udcff")9495 with pytest.raises(click.BadParameter, match="'�' does not exist"):96 type.convert(path, None, None)9798 type = click.Path(file_okay=False)99 path.touch()100101 with pytest.raises(click.BadParameter, match="'�' is a file"):102 type.convert(path, None, None)103104 path.unlink()105 type = click.Path(dir_okay=False)106 path.mkdir()107108 with pytest.raises(click.BadParameter, match="'�' is a directory"):109 type.convert(path, None, None)110111 path.rmdir()112113 def no_access(*args, **kwargs):114 """Test environments may be running as root, so we have to fake the result of115 the access tests that use os.access116 """117 p = args[0]118 assert p == path, f"unexpected os.access call on file not under test: {p!r}"119 return False120121 path.touch()122 type = click.Path(readable=True)123124 with pytest.raises(click.BadParameter, match="'�' is not readable"):125 with monkeypatch.context() as m:126 m.setattr(os, "access", no_access)127 type.convert(path, None, None)128129 type = click.Path(readable=False, writable=True)130131 with pytest.raises(click.BadParameter, match="'�' is not writable"):132 with monkeypatch.context() as m:133 m.setattr(os, "access", no_access)134 type.convert(path, None, None)135136 type = click.Path(readable=False, executable=True)137138 with pytest.raises(click.BadParameter, match="'�' is not executable"):139 with monkeypatch.context() as m:140 m.setattr(os, "access", no_access)141 type.convert(path, None, None)142143 path.unlink()144145146def _non_utf8_filenames_supported():147 with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:148 try:149 f = open(os.path.join(tempdir, "\udcff"), "w")150 except OSError:151 return False152153 f.close()154 return True155156157@pytest.mark.skipif(158 platform.system() == "Windows", reason="Filepath syntax differences."159)160def test_invalid_path_with_esc_sequence():161 with pytest.raises(click.BadParameter) as exc_info:162 with tempfile.TemporaryDirectory(prefix="my\ndir") as tempdir:163 click.Path(dir_okay=False).convert(tempdir, None, None)164165 assert "my\\ndir" in exc_info.value.message166167168@pytest.mark.parametrize(169 ("cls", "expect"),170 [171 (None, "a/b/c.txt"),172 (str, "a/b/c.txt"),173 (bytes, b"a/b/c.txt"),174 (pathlib.Path, pathlib.Path("a", "b", "c.txt")),175 ],176)177def test_path_type(runner, cls, expect):178 cli = click.Command(179 "cli",180 params=[click.Argument(["p"], type=click.Path(path_type=cls))],181 callback=lambda p: p,182 )183 result = runner.invoke(cli, ["a/b/c.txt"], standalone_mode=False)184 assert result.exception is None185 assert result.return_value == expect
modified:tests/test_basic.py+24 added
958 unmodified lines
959960 result = runner.invoke(cli, ["--version"], prog_name="mytool")961 assert result.exit_code == 0962 assert result.output == "mytool 1.0\n"963964965@pytest.mark.parametrize(966 ("nargs", "multiple", "default", "expect"),967 [968 (2, False, None, None),969 (2, False, (None, None), (None, None)),970 (None, True, None, ()),971 (None, True, (None, None), (None, None)),972 (2, True, None, ()),973 (2, True, [(None, None)], ((None, None),)),974 (-1, None, None, ()),975 ],976)977def test_cast_multi_default(runner, nargs, multiple, default, expect):978 if nargs == -1:979 param = click.Argument(["a"], nargs=nargs, default=default)980 else:981 param = click.Option(["-a"], nargs=nargs, multiple=multiple, default=default)982983 cli = click.Command("cli", params=[param], callback=lambda a: a)984 result = runner.invoke(cli, standalone_mode=False)985 assert result.exception is None986 assert result.return_value == expect
deleted:tests/test_types.py-438 removed
1import datetime2import os.path3import pathlib4import platform5import subprocess6import sys7import tempfile8import typing as t9import uuid1011import pytest1213import click14from click import FileError15from click.types import convert_type16from click.types import FuncParamType171819@pytest.mark.parametrize(20 ("type", "value", "expect"),21 [22 (click.IntRange(0, 5), "3", 3),23 (click.IntRange(5), "5", 5),24 (click.IntRange(5), "100", 100),25 (click.IntRange(max=5), "5", 5),26 (click.IntRange(max=5), "-100", -100),27 (click.IntRange(0, clamp=True), "-1", 0),28 (click.IntRange(max=5, clamp=True), "6", 5),29 (click.IntRange(0, min_open=True, clamp=True), "0", 1),30 (click.IntRange(max=5, max_open=True, clamp=True), "5", 4),31 (click.FloatRange(0.5, 1.5), "1.2", 1.2),32 (click.FloatRange(0.5, min_open=True), "0.51", 0.51),33 (click.FloatRange(max=1.5, max_open=True), "1.49", 1.49),34 (click.FloatRange(0.5, clamp=True), "-0.0", 0.5),35 (click.FloatRange(max=1.5, clamp=True), "inf", 1.5),36 ],37)38def test_range(type, value, expect):39 assert type.convert(value, None, None) == expect404142@pytest.mark.parametrize(43 ("type", "value", "expect"),44 [45 (click.IntRange(0, 5), "6", "6 is not in the range 0<=x<=5."),46 (click.IntRange(5), "4", "4 is not in the range x>=5."),47 (click.IntRange(max=5), "6", "6 is not in the range x<=5."),48 (click.IntRange(0, 5, min_open=True), 0, "0<x<=5"),49 (click.IntRange(0, 5, max_open=True), 5, "0<=x<5"),50 (click.FloatRange(0.5, min_open=True), 0.5, "x>0.5"),51 (click.FloatRange(max=1.5, max_open=True), 1.5, "x<1.5"),52 ],53)54def test_range_fail(type, value, expect):55 with pytest.raises(click.BadParameter) as exc_info:56 type.convert(value, None, None)5758 assert expect in exc_info.value.message596061@pytest.mark.parametrize(62 ("error_message", "expected"),63 [64 ("bad value: nope", "bad value: nope"),65 ("", "nope"),66 ],67)68def test_func_param_type_uses_value_error_message(error_message, expected):69 def parse(value):70 raise ValueError(error_message if error_message else "")7172 func_type = click.types.FuncParamType(parse)7374 with pytest.raises(click.BadParameter) as exc_info:75 func_type.convert("nope", None, None)7677 assert expected in exc_info.value.message787980def test_float_range_no_clamp_open():81 with pytest.raises(TypeError):82 click.FloatRange(0, 1, max_open=True, clamp=True)8384 sneaky = click.FloatRange(0, 1, max_open=True)85 sneaky.clamp = True8687 with pytest.raises(RuntimeError):88 sneaky.convert("1.5", None, None)899091@pytest.mark.parametrize(92 ("nargs", "multiple", "default", "expect"),93 [94 (2, False, None, None),95 (2, False, (None, None), (None, None)),96 (None, True, None, ()),97 (None, True, (None, None), (None, None)),98 (2, True, None, ()),99 (2, True, [(None, None)], ((None, None),)),100 (-1, None, None, ()),101 ],102)103def test_cast_multi_default(runner, nargs, multiple, default, expect):104 if nargs == -1:105 param = click.Argument(["a"], nargs=nargs, default=default)106 else:107 param = click.Option(["-a"], nargs=nargs, multiple=multiple, default=default)108109 cli = click.Command("cli", params=[param], callback=lambda a: a)110 result = runner.invoke(cli, standalone_mode=False)111 assert result.exception is None112 assert result.return_value == expect113114115@pytest.mark.parametrize(116 ("cls", "expect"),117 [118 (None, "a/b/c.txt"),119 (str, "a/b/c.txt"),120 (bytes, b"a/b/c.txt"),121 (pathlib.Path, pathlib.Path("a", "b", "c.txt")),122 ],123)124def test_path_type(runner, cls, expect):125 cli = click.Command(126 "cli",127 params=[click.Argument(["p"], type=click.Path(path_type=cls))],128 callback=lambda p: p,129 )130 result = runner.invoke(cli, ["a/b/c.txt"], standalone_mode=False)131 assert result.exception is None132 assert result.return_value == expect133134135def test_path_dash_no_byteswarning():136 """Detecting the ``-`` dash sentinel must not compare ``bytes`` against137 ``str``, which raises a ``BytesWarning`` under ``python -bb``.138139 The warning is only emitted when the interpreter runs with ``-b``, so this140 has to be checked in a subprocess. ``-bb`` turns the warning into an error,141 so a clean exit means no mismatched comparison happened.142 """143 program = (144 "import click\n"145 "convert = click.Path(allow_dash=True).convert\n"146 "for value in ('-', '', b'-', b''):\n"147 " convert(value, None, None)\n"148 )149 result = subprocess.run(150 [sys.executable, "-bb", "-c", program],151 capture_output=True,152 text=True,153 )154 assert result.returncode == 0, result.stderr155 assert "BytesWarning" not in result.stderr156157158def _symlinks_supported():159 with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:160 target = os.path.join(tempdir, "target")161 open(target, "w").close()162 link = os.path.join(tempdir, "link")163164 try:165 os.symlink(target, link)166 return True167 except OSError:168 return False169170171@pytest.mark.skipif(172 not _symlinks_supported(), reason="The current OS or FS doesn't support symlinks."173)174def test_path_resolve_symlink(tmp_path, runner):175 test_file = tmp_path / "file"176 test_file_str = os.fspath(test_file)177 test_file.write_text("")178179 path_type = click.Path(resolve_path=True)180 param = click.Argument(["a"], type=path_type)181 ctx = click.Context(click.Command("cli", params=[param]))182183 test_dir = tmp_path / "dir"184 test_dir.mkdir()185186 abs_link = test_dir / "abs"187 abs_link.symlink_to(test_file)188 abs_rv = path_type.convert(os.fspath(abs_link), param, ctx)189 assert abs_rv == test_file_str190191 rel_link = test_dir / "rel"192 rel_link.symlink_to(pathlib.Path("..") / "file")193 rel_rv = path_type.convert(os.fspath(rel_link), param, ctx)194 assert rel_rv == test_file_str195196197def _non_utf8_filenames_supported():198 with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:199 try:200 f = open(os.path.join(tempdir, "\udcff"), "w")201 except OSError:202 return False203204 f.close()205 return True206207208@pytest.mark.skipif(209 not _non_utf8_filenames_supported(),210 reason="The current OS or FS doesn't support non-UTF-8 filenames.",211)212def test_path_surrogates(tmp_path, monkeypatch):213 monkeypatch.chdir(tmp_path)214 type = click.Path(exists=True)215 path = pathlib.Path("\udcff")216217 with pytest.raises(click.BadParameter, match="'�' does not exist"):218 type.convert(path, None, None)219220 type = click.Path(file_okay=False)221 path.touch()222223 with pytest.raises(click.BadParameter, match="'�' is a file"):224 type.convert(path, None, None)225226 path.unlink()227 type = click.Path(dir_okay=False)228 path.mkdir()229230 with pytest.raises(click.BadParameter, match="'�' is a directory"):231 type.convert(path, None, None)232233 path.rmdir()234235 def no_access(*args, **kwargs):236 """Test environments may be running as root, so we have to fake the result of237 the access tests that use os.access238 """239 p = args[0]240 assert p == path, f"unexpected os.access call on file not under test: {p!r}"241 return False242243 path.touch()244 type = click.Path(readable=True)245246 with pytest.raises(click.BadParameter, match="'�' is not readable"):247 with monkeypatch.context() as m:248 m.setattr(os, "access", no_access)249 type.convert(path, None, None)250251 type = click.Path(readable=False, writable=True)252253 with pytest.raises(click.BadParameter, match="'�' is not writable"):254 with monkeypatch.context() as m:255 m.setattr(os, "access", no_access)256 type.convert(path, None, None)257258 type = click.Path(readable=False, executable=True)259260 with pytest.raises(click.BadParameter, match="'�' is not executable"):261 with monkeypatch.context() as m:262 m.setattr(os, "access", no_access)263 type.convert(path, None, None)264265 path.unlink()266267268@pytest.mark.parametrize(269 "type",270 [271 click.File(mode="r"),272 click.File(mode="r", lazy=True),273 ],274)275def test_file_surrogates(type, tmp_path):276 """Ensures that the error handling in ``click.File`` is robust.277278 ``EILSEQ`` shows up with rootless Podman (FUSE-backed paths) and on filesystems279 that reject non-UTF-8 names, like ZFS with ``utf8only=on``.280281 See: https://github.com/pallets/click/issues/2634282 """283 path = tmp_path / "\udcff"284 match = (285 # Common case: �': No such file or directory.286 r"(�': No such file or directory"287 # BSD/macOS libc special case (EILSEQ).288 r"|Illegal byte sequence"289 # glibc special case (EILSEQ).290 r"|Invalid or incomplete multibyte or wide character)"291 )292 with pytest.raises(click.BadParameter, match=match):293 type.convert(path, None, None)294295296def test_file_error_surrogates():297 message = FileError(filename="\udcff").format_message()298 assert message == "Could not open file '�': unknown error"299300301@pytest.mark.skipif(302 platform.system() == "Windows", reason="Filepath syntax differences."303)304def test_invalid_path_with_esc_sequence():305 with pytest.raises(click.BadParameter) as exc_info:306 with tempfile.TemporaryDirectory(prefix="my\ndir") as tempdir:307 click.Path(dir_okay=False).convert(tempdir, None, None)308309 assert "my\\ndir" in exc_info.value.message310311312def test_choice_get_invalid_choice_message():313 choice = click.Choice(["a", "b", "c"])314 message = choice.get_invalid_choice_message("d", ctx=None)315 assert message == "'d' is not one of 'a', 'b', 'c'."316317318def test_param_type_input_parameter_defaults_at_runtime():319 """Omitting the input type parameter works at runtime on every320 supported Python. The ``Any`` default is native (PEP 696) on Python321 3.13+, and backfilled by ``ParamType.__class_getitem__`` before322 that."""323 assert t.get_args(click.ParamType[int]) == (int, t.Any)324 assert t.get_args(click.ParamType[int, str]) == (int, str)325326327def test_param_type_subclass_omitting_input_parameter():328 class DoublingType(click.ParamType[int]):329 name = "doubling"330331 def convert(self, value, param, ctx):332 return int(value) * 2333334 doubling = DoublingType()335 assert doubling("21") == 42336 assert doubling(None) is None337338339@pytest.mark.parametrize(340 "default",341 [342 # Empty sequences fall back to STRING because ``_guess_type`` returns None.343 [],344 (),345 # Container types are guessed from the default but are not natively346 # supported, so they reach STRING through a different code path.347 set(),348 {1, 2},349 frozenset(),350 frozenset(["git"]),351 {},352 {"a": 1},353 ],354)355def test_convert_type_from_container_default(default):356 """Container defaults are not natively supported and fall back to STRING.357358 Refs: https://github.com/pallets/click/issues/3036359 """360 assert convert_type(None, default) is click.STRING361362363@pytest.mark.parametrize(364 ("container_type", "value", "expected"),365 [366 (set, "a,b,c", {"a", ",", "b", "c"}),367 (frozenset, "abc", frozenset({"a", "b", "c"})),368 ],369)370def test_explicit_container_type_splits_string(container_type, value, expected):371 """An explicit ``set`` or ``frozenset`` type wraps the builtin in a372 ``FuncParamType``, which splits CLI strings character-wise.373374 Refs: https://github.com/pallets/click/issues/3036375 """376 param_type = convert_type(container_type)377 assert isinstance(param_type, FuncParamType)378 assert param_type.convert(value, None, None) == expected379380381def test_explicit_dict_type_rejects_string():382 """An explicit ``dict`` type cannot convert a plain CLI string at all.383384 Refs: https://github.com/pallets/click/issues/3036385 """386 param_type = convert_type(dict)387 assert isinstance(param_type, FuncParamType)388 with pytest.raises(click.BadParameter):389 param_type.convert("abc", None, None)390391392@pytest.mark.parametrize(393 ("default", "expected"),394 [395 # Recognized scalars.396 (None, click.STRING),397 ("git", click.STRING),398 (5, click.INT),399 (1.5, click.FLOAT),400 (True, click.BOOL),401 # An empty sequence gives no item to read.402 ([], click.STRING),403 ((), click.STRING),404 # A sequence gives the type of its first item only.405 ([1, 2], click.INT),406 ((1, 2), click.INT),407 ([1.5, 2.5], click.FLOAT),408 ([1, "git"], click.INT),409 # Everything else falls back to STRING, including types Click ships.410 ({1, 2}, click.STRING),411 (frozenset({1, 2}), click.STRING),412 ({"a": 1}, click.STRING),413 (uuid.UUID(int=0), click.STRING),414 (datetime.datetime(2026, 1, 1), click.STRING),415 (b"git", click.STRING),416 (object(), click.STRING),417 ],418)419def test_type_inferred_from_default(default, expected):420 """Every row of the type-inference table in ``docs/parameter-types.md``.421422 Keep the two in step: a change here is a change to documented behavior.423424 Refs: https://github.com/pallets/click/issues/3036425 """426 assert convert_type(None, default) is expected427428429def test_type_inferred_from_nested_sequence_default():430 """A sequence of sequences gives a composite ``Tuple`` of the inner types.431432 This is the one table row that is not a singleton ``ParamType``.433434 Refs: https://github.com/pallets/click/issues/3036435 """436 param_type = convert_type(None, [(1, "git")])437 assert isinstance(param_type, click.Tuple)438 assert param_type.types == [click.INT, click.STRING]