Split out types tests. (#3850)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents 87f7a31, b8a4486 · 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
Provenance
- Commit
7ecc8d7- Tree
37517ba- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
87f7a31- Parent 2
b8a4486
13 files changed+487 added−438 removed
added:tests/test_exceptions/__init__.py
added:tests/test_exceptions/test_FileError.py+6 added
1+import click2+3+4+def 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
1+import click2+3+4+def 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
1+import datetime2+import uuid3+4+import pytest5+6+import click7+8+9+@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+)25+def test_convert_type_from_container_default(default):26+ """Container defaults are not natively supported and fall back to STRING.27+28+ Refs: https://github.com/pallets/click/issues/303629+ """30+ assert click.types.convert_type(None, default) is click.STRING31+32+33+@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+)40+def 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.43+44+ 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) == expected49+50+51+@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+)78+def test_type_inferred_from_default(default, expected):79+ """Every row of the type-inference table in ``docs/parameter-types.md``.80+81+ Keep the two in step: a change here is a change to documented behavior.82+83+ Refs: https://github.com/pallets/click/issues/303684+ """85+ assert click.types.convert_type(None, default) is expected86+87+88+def test_type_inferred_from_nested_sequence_default():89+ """A sequence of sequences gives a composite ``Tuple`` of the inner types.90+91+ This is the one table row that is not a singleton ``ParamType``.92+93+ 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]98+99+100+def test_explicit_dict_type_rejects_string():101+ """An explicit ``dict`` type cannot convert a plain CLI string at all.102+103+ 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
1+import pytest2+3+import click4+5+6+@pytest.mark.parametrize(7+ "type",8+ [9+ click.File(mode="r"),10+ click.File(mode="r", lazy=True),11+ ],12+)13+def test_file_surrogates(type, tmp_path):14+ """Ensures that the error handling in ``click.File`` is robust.15+16+ ``EILSEQ`` shows up with rootless Podman (FUSE-backed paths) and on filesystems17+ that reject non-UTF-8 names, like ZFS with ``utf8only=on``.18+19+ 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
1+import pytest2+3+import click4+5+6+@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+)16+def test_range(type, value, expect):17+ assert type.convert(value, None, None) == expect18+19+20+@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+)27+def test_range_fail(type, value, expect):28+ with pytest.raises(click.BadParameter) as exc_info:29+ type.convert(value, None, None)30+31+ assert expect in exc_info.value.message32+33+34+def test_float_range_no_clamp_open():35+ with pytest.raises(TypeError):36+ click.FloatRange(0, 1, max_open=True, clamp=True)37+38+ sneaky = click.FloatRange(0, 1, max_open=True)39+ sneaky.clamp = True40+41+ with pytest.raises(RuntimeError):42+ sneaky.convert("1.5", None, None)added:tests/test_types/test_FuncParamType.py+22 added
1+import pytest2+3+import click4+5+6+@pytest.mark.parametrize(7+ ("error_message", "expected"),8+ [9+ ("bad value: nope", "bad value: nope"),10+ ("", "nope"),11+ ],12+)13+def test_func_param_type_uses_value_error_message(error_message, expected):14+ def parse(value):15+ raise ValueError(error_message if error_message else "")16+17+ func_type = click.types.FuncParamType(parse)18+19+ with pytest.raises(click.BadParameter) as exc_info:20+ func_type.convert("nope", None, None)21+22+ assert expected in exc_info.value.messageadded:tests/test_types/test_IntRange.py+38 added
1+import pytest2+3+import click4+5+6+@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+)20+def test_range(type, value, expect):21+ assert type.convert(value, None, None) == expect22+23+24+@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+)34+def test_range_fail(type, value, expect):35+ with pytest.raises(click.BadParameter) as exc_info:36+ type.convert(value, None, None)37+38+ assert expect in exc_info.value.messageadded:tests/test_types/test_ParamType.py+24 added
1+import typing as t2+3+import click4+5+6+def 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)13+14+15+def test_param_type_subclass_omitting_input_parameter():16+ class DoublingType(click.ParamType[int]):17+ name = "doubling"18+19+ def convert(self, value, param, ctx):20+ return int(value) * 221+22+ doubling = DoublingType()23+ assert doubling("21") == 4224+ assert doubling(None) is Noneadded:tests/test_types/test_Path.py+185 added
1+import os2+import pathlib3+import platform4+import subprocess5+import sys6+import tempfile7+8+import pytest9+10+import click11+12+13+def test_path_dash_no_byteswarning():14+ """Detecting the ``-`` dash sentinel must not compare ``bytes`` against15+ ``str``, which raises a ``BytesWarning`` under ``python -bb``.16+17+ 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.stderr34+35+36+def _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")41+42+ try:43+ os.symlink(target, link)44+ return True45+ except OSError:46+ return False47+48+49+@pytest.mark.skipif(50+ not _symlinks_supported(), reason="The current OS or FS doesn't support symlinks."51+)52+def 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("")56+57+ path_type = click.Path(resolve_path=True)58+ param = click.Argument(["a"], type=path_type)59+ ctx = click.Context(click.Command("cli", params=[param]))60+61+ test_dir = tmp_path / "dir"62+ test_dir.mkdir()63+64+ 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_str68+69+ 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_str73+74+75+def _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 False81+82+ f.close()83+ return True84+85+86+@pytest.mark.skipif(87+ not _non_utf8_filenames_supported(),88+ reason="The current OS or FS doesn't support non-UTF-8 filenames.",89+)90+def test_path_surrogates(tmp_path, monkeypatch):91+ monkeypatch.chdir(tmp_path)92+ type = click.Path(exists=True)93+ path = pathlib.Path("\udcff")94+95+ with pytest.raises(click.BadParameter, match="'�' does not exist"):96+ type.convert(path, None, None)97+98+ type = click.Path(file_okay=False)99+ path.touch()100+101+ with pytest.raises(click.BadParameter, match="'�' is a file"):102+ type.convert(path, None, None)103+104+ path.unlink()105+ type = click.Path(dir_okay=False)106+ path.mkdir()107+108+ with pytest.raises(click.BadParameter, match="'�' is a directory"):109+ type.convert(path, None, None)110+111+ path.rmdir()112+113+ 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 False120+121+ path.touch()122+ type = click.Path(readable=True)123+124+ 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)128+129+ type = click.Path(readable=False, writable=True)130+131+ 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)135+136+ type = click.Path(readable=False, executable=True)137+138+ 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)142+143+ path.unlink()144+145+146+def _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 False152+153+ f.close()154+ return True155+156+157+@pytest.mark.skipif(158+ platform.system() == "Windows", reason="Filepath syntax differences."159+)160+def 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)164+165+ assert "my\\ndir" in exc_info.value.message166+167+168+@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+)177+def 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 == expectmodified:tests/test_basic.py+24 added
958 unmodified lines959 960 result = runner.invoke(cli, ["--version"], prog_name="mytool")961 assert result.exit_code == 0962 assert result.output == "mytool 1.0\n"963+964+965+@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+)977+def 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)982+983+ 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 == expectdeleted:tests/test_types.py-438 removed
1-import datetime2-import os.path3-import pathlib4-import platform5-import subprocess6-import sys7-import tempfile8-import typing as t9-import uuid10-11-import pytest12-13-import click14-from click import FileError15-from click.types import convert_type16-from click.types import FuncParamType17-18-19-@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-)38-def test_range(type, value, expect):39- assert type.convert(value, None, None) == expect40-41-42-@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-)54-def test_range_fail(type, value, expect):55- with pytest.raises(click.BadParameter) as exc_info:56- type.convert(value, None, None)57-58- assert expect in exc_info.value.message59-60-61-@pytest.mark.parametrize(62- ("error_message", "expected"),63- [64- ("bad value: nope", "bad value: nope"),65- ("", "nope"),66- ],67-)68-def test_func_param_type_uses_value_error_message(error_message, expected):69- def parse(value):70- raise ValueError(error_message if error_message else "")71-72- func_type = click.types.FuncParamType(parse)73-74- with pytest.raises(click.BadParameter) as exc_info:75- func_type.convert("nope", None, None)76-77- assert expected in exc_info.value.message78-79-80-def test_float_range_no_clamp_open():81- with pytest.raises(TypeError):82- click.FloatRange(0, 1, max_open=True, clamp=True)83-84- sneaky = click.FloatRange(0, 1, max_open=True)85- sneaky.clamp = True86-87- with pytest.raises(RuntimeError):88- sneaky.convert("1.5", None, None)89-90-91-@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-)103-def 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)108-109- 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 == expect113-114-115-@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-)124-def 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 == expect133-134-135-def test_path_dash_no_byteswarning():136- """Detecting the ``-`` dash sentinel must not compare ``bytes`` against137- ``str``, which raises a ``BytesWarning`` under ``python -bb``.138-139- 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.stderr156-157-158-def _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")163-164- try:165- os.symlink(target, link)166- return True167- except OSError:168- return False169-170-171-@pytest.mark.skipif(172- not _symlinks_supported(), reason="The current OS or FS doesn't support symlinks."173-)174-def 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("")178-179- path_type = click.Path(resolve_path=True)180- param = click.Argument(["a"], type=path_type)181- ctx = click.Context(click.Command("cli", params=[param]))182-183- test_dir = tmp_path / "dir"184- test_dir.mkdir()185-186- 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_str190-191- 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_str195-196-197-def _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 False203-204- f.close()205- return True206-207-208-@pytest.mark.skipif(209- not _non_utf8_filenames_supported(),210- reason="The current OS or FS doesn't support non-UTF-8 filenames.",211-)212-def test_path_surrogates(tmp_path, monkeypatch):213- monkeypatch.chdir(tmp_path)214- type = click.Path(exists=True)215- path = pathlib.Path("\udcff")216-217- with pytest.raises(click.BadParameter, match="'�' does not exist"):218- type.convert(path, None, None)219-220- type = click.Path(file_okay=False)221- path.touch()222-223- with pytest.raises(click.BadParameter, match="'�' is a file"):224- type.convert(path, None, None)225-226- path.unlink()227- type = click.Path(dir_okay=False)228- path.mkdir()229-230- with pytest.raises(click.BadParameter, match="'�' is a directory"):231- type.convert(path, None, None)232-233- path.rmdir()234-235- 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 False242-243- path.touch()244- type = click.Path(readable=True)245-246- 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)250-251- type = click.Path(readable=False, writable=True)252-253- 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)257-258- type = click.Path(readable=False, executable=True)259-260- 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)264-265- path.unlink()266-267-268-@pytest.mark.parametrize(269- "type",270- [271- click.File(mode="r"),272- click.File(mode="r", lazy=True),273- ],274-)275-def test_file_surrogates(type, tmp_path):276- """Ensures that the error handling in ``click.File`` is robust.277-278- ``EILSEQ`` shows up with rootless Podman (FUSE-backed paths) and on filesystems279- that reject non-UTF-8 names, like ZFS with ``utf8only=on``.280-281- 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)294-295-296-def test_file_error_surrogates():297- message = FileError(filename="\udcff").format_message()298- assert message == "Could not open file '�': unknown error"299-300-301-@pytest.mark.skipif(302- platform.system() == "Windows", reason="Filepath syntax differences."303-)304-def 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)308-309- assert "my\\ndir" in exc_info.value.message310-311-312-def 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'."316-317-318-def 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)325-326-327-def test_param_type_subclass_omitting_input_parameter():328- class DoublingType(click.ParamType[int]):329- name = "doubling"330-331- def convert(self, value, param, ctx):332- return int(value) * 2333-334- doubling = DoublingType()335- assert doubling("21") == 42336- assert doubling(None) is None337-338-339-@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-)355-def test_convert_type_from_container_default(default):356- """Container defaults are not natively supported and fall back to STRING.357-358- Refs: https://github.com/pallets/click/issues/3036359- """360- assert convert_type(None, default) is click.STRING361-362-363-@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-)370-def 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.373-374- 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) == expected379-380-381-def test_explicit_dict_type_rejects_string():382- """An explicit ``dict`` type cannot convert a plain CLI string at all.383-384- 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)390-391-392-@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-)419-def test_type_inferred_from_default(default, expected):420- """Every row of the type-inference table in ``docs/parameter-types.md``.421-422- Keep the two in step: a change here is a change to documented behavior.423-424- Refs: https://github.com/pallets/click/issues/3036425- """426- assert convert_type(None, default) is expected427-428-429-def test_type_inferred_from_nested_sequence_default():430- """A sequence of sequences gives a composite ``Tuple`` of the inner types.431-432- This is the one table row that is not a singleton ``ParamType``.433-434- 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]