test_types.py
This file
Path
tests/test_types.py
332 lines · 10.2 KiB · Python
Last changed by
`click.prompt` typing clarifications / improvements (#3407)Rowlando13before adoption5e906a8
History of this fileTake it
1import os.path2import pathlib3import platform4import subprocess5import sys6import tempfile7import typing as t89import pytest1011import click12from click import FileError131415@pytest.mark.parametrize(16 ("type", "value", "expect"),17 [18 (click.IntRange(0, 5), "3", 3),19 (click.IntRange(5), "5", 5),20 (click.IntRange(5), "100", 100),21 (click.IntRange(max=5), "5", 5),22 (click.IntRange(max=5), "-100", -100),23 (click.IntRange(0, clamp=True), "-1", 0),24 (click.IntRange(max=5, clamp=True), "6", 5),25 (click.IntRange(0, min_open=True, clamp=True), "0", 1),26 (click.IntRange(max=5, max_open=True, clamp=True), "5", 4),27 (click.FloatRange(0.5, 1.5), "1.2", 1.2),28 (click.FloatRange(0.5, min_open=True), "0.51", 0.51),29 (click.FloatRange(max=1.5, max_open=True), "1.49", 1.49),30 (click.FloatRange(0.5, clamp=True), "-0.0", 0.5),31 (click.FloatRange(max=1.5, clamp=True), "inf", 1.5),32 ],33)34def test_range(type, value, expect):35 assert type.convert(value, None, None) == expect363738@pytest.mark.parametrize(39 ("type", "value", "expect"),40 [41 (click.IntRange(0, 5), "6", "6 is not in the range 0<=x<=5."),42 (click.IntRange(5), "4", "4 is not in the range x>=5."),43 (click.IntRange(max=5), "6", "6 is not in the range x<=5."),44 (click.IntRange(0, 5, min_open=True), 0, "0<x<=5"),45 (click.IntRange(0, 5, max_open=True), 5, "0<=x<5"),46 (click.FloatRange(0.5, min_open=True), 0.5, "x>0.5"),47 (click.FloatRange(max=1.5, max_open=True), 1.5, "x<1.5"),48 ],49)50def test_range_fail(type, value, expect):51 with pytest.raises(click.BadParameter) as exc_info:52 type.convert(value, None, None)5354 assert expect in exc_info.value.message555657@pytest.mark.parametrize(58 ("error_message", "expected"),59 [60 ("bad value: nope", "bad value: nope"),61 ("", "nope"),62 ],63)64def test_func_param_type_uses_value_error_message(error_message, expected):65 def parse(value):66 raise ValueError(error_message if error_message else "")6768 func_type = click.types.FuncParamType(parse)6970 with pytest.raises(click.BadParameter) as exc_info:71 func_type.convert("nope", None, None)7273 assert expected in exc_info.value.message747576def test_float_range_no_clamp_open():77 with pytest.raises(TypeError):78 click.FloatRange(0, 1, max_open=True, clamp=True)7980 sneaky = click.FloatRange(0, 1, max_open=True)81 sneaky.clamp = True8283 with pytest.raises(RuntimeError):84 sneaky.convert("1.5", None, None)858687@pytest.mark.parametrize(88 ("nargs", "multiple", "default", "expect"),89 [90 (2, False, None, None),91 (2, False, (None, None), (None, None)),92 (None, True, None, ()),93 (None, True, (None, None), (None, None)),94 (2, True, None, ()),95 (2, True, [(None, None)], ((None, None),)),96 (-1, None, None, ()),97 ],98)99def test_cast_multi_default(runner, nargs, multiple, default, expect):100 if nargs == -1:101 param = click.Argument(["a"], nargs=nargs, default=default)102 else:103 param = click.Option(["-a"], nargs=nargs, multiple=multiple, default=default)104105 cli = click.Command("cli", params=[param], callback=lambda a: a)106 result = runner.invoke(cli, standalone_mode=False)107 assert result.exception is None108 assert result.return_value == expect109110111@pytest.mark.parametrize(112 ("cls", "expect"),113 [114 (None, "a/b/c.txt"),115 (str, "a/b/c.txt"),116 (bytes, b"a/b/c.txt"),117 (pathlib.Path, pathlib.Path("a", "b", "c.txt")),118 ],119)120def test_path_type(runner, cls, expect):121 cli = click.Command(122 "cli",123 params=[click.Argument(["p"], type=click.Path(path_type=cls))],124 callback=lambda p: p,125 )126 result = runner.invoke(cli, ["a/b/c.txt"], standalone_mode=False)127 assert result.exception is None128 assert result.return_value == expect129130131def test_path_dash_no_byteswarning():132 """Detecting the ``-`` dash sentinel must not compare ``bytes`` against133 ``str``, which raises a ``BytesWarning`` under ``python -bb``.134135 The warning is only emitted when the interpreter runs with ``-b``, so this136 has to be checked in a subprocess. ``-bb`` turns the warning into an error,137 so a clean exit means no mismatched comparison happened.138 """139 program = (140 "import click\n"141 "convert = click.Path(allow_dash=True).convert\n"142 "for value in ('-', '', b'-', b''):\n"143 " convert(value, None, None)\n"144 )145 result = subprocess.run(146 [sys.executable, "-bb", "-c", program],147 capture_output=True,148 text=True,149 )150 assert result.returncode == 0, result.stderr151 assert "BytesWarning" not in result.stderr152153154def _symlinks_supported():155 with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:156 target = os.path.join(tempdir, "target")157 open(target, "w").close()158 link = os.path.join(tempdir, "link")159160 try:161 os.symlink(target, link)162 return True163 except OSError:164 return False165166167@pytest.mark.skipif(168 not _symlinks_supported(), reason="The current OS or FS doesn't support symlinks."169)170def test_path_resolve_symlink(tmp_path, runner):171 test_file = tmp_path / "file"172 test_file_str = os.fspath(test_file)173 test_file.write_text("")174175 path_type = click.Path(resolve_path=True)176 param = click.Argument(["a"], type=path_type)177 ctx = click.Context(click.Command("cli", params=[param]))178179 test_dir = tmp_path / "dir"180 test_dir.mkdir()181182 abs_link = test_dir / "abs"183 abs_link.symlink_to(test_file)184 abs_rv = path_type.convert(os.fspath(abs_link), param, ctx)185 assert abs_rv == test_file_str186187 rel_link = test_dir / "rel"188 rel_link.symlink_to(pathlib.Path("..") / "file")189 rel_rv = path_type.convert(os.fspath(rel_link), param, ctx)190 assert rel_rv == test_file_str191192193def _non_utf8_filenames_supported():194 with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:195 try:196 f = open(os.path.join(tempdir, "\udcff"), "w")197 except OSError:198 return False199200 f.close()201 return True202203204@pytest.mark.skipif(205 not _non_utf8_filenames_supported(),206 reason="The current OS or FS doesn't support non-UTF-8 filenames.",207)208def test_path_surrogates(tmp_path, monkeypatch):209 monkeypatch.chdir(tmp_path)210 type = click.Path(exists=True)211 path = pathlib.Path("\udcff")212213 with pytest.raises(click.BadParameter, match="'�' does not exist"):214 type.convert(path, None, None)215216 type = click.Path(file_okay=False)217 path.touch()218219 with pytest.raises(click.BadParameter, match="'�' is a file"):220 type.convert(path, None, None)221222 path.unlink()223 type = click.Path(dir_okay=False)224 path.mkdir()225226 with pytest.raises(click.BadParameter, match="'�' is a directory"):227 type.convert(path, None, None)228229 path.rmdir()230231 def no_access(*args, **kwargs):232 """Test environments may be running as root, so we have to fake the result of233 the access tests that use os.access234 """235 p = args[0]236 assert p == path, f"unexpected os.access call on file not under test: {p!r}"237 return False238239 path.touch()240 type = click.Path(readable=True)241242 with pytest.raises(click.BadParameter, match="'�' is not readable"):243 with monkeypatch.context() as m:244 m.setattr(os, "access", no_access)245 type.convert(path, None, None)246247 type = click.Path(readable=False, writable=True)248249 with pytest.raises(click.BadParameter, match="'�' is not writable"):250 with monkeypatch.context() as m:251 m.setattr(os, "access", no_access)252 type.convert(path, None, None)253254 type = click.Path(readable=False, executable=True)255256 with pytest.raises(click.BadParameter, match="'�' is not executable"):257 with monkeypatch.context() as m:258 m.setattr(os, "access", no_access)259 type.convert(path, None, None)260261 path.unlink()262263264@pytest.mark.parametrize(265 "type",266 [267 click.File(mode="r"),268 click.File(mode="r", lazy=True),269 ],270)271def test_file_surrogates(type, tmp_path):272 """Ensures that the error handling in ``click.File`` is robust.273274 ``EILSEQ`` shows up with rootless Podman (FUSE-backed paths) and on filesystems275 that reject non-UTF-8 names, like ZFS with ``utf8only=on``.276277 See: https://github.com/pallets/click/issues/2634278 """279 path = tmp_path / "\udcff"280 match = (281 # Common case: �': No such file or directory.282 r"(�': No such file or directory"283 # BSD/macOS libc special case (EILSEQ).284 r"|Illegal byte sequence"285 # glibc special case (EILSEQ).286 r"|Invalid or incomplete multibyte or wide character)"287 )288 with pytest.raises(click.BadParameter, match=match):289 type.convert(path, None, None)290291292def test_file_error_surrogates():293 message = FileError(filename="\udcff").format_message()294 assert message == "Could not open file '�': unknown error"295296297@pytest.mark.skipif(298 platform.system() == "Windows", reason="Filepath syntax differences."299)300def test_invalid_path_with_esc_sequence():301 with pytest.raises(click.BadParameter) as exc_info:302 with tempfile.TemporaryDirectory(prefix="my\ndir") as tempdir:303 click.Path(dir_okay=False).convert(tempdir, None, None)304305 assert "my\\ndir" in exc_info.value.message306307308def test_choice_get_invalid_choice_message():309 choice = click.Choice(["a", "b", "c"])310 message = choice.get_invalid_choice_message("d", ctx=None)311 assert message == "'d' is not one of 'a', 'b', 'c'."312313314def test_param_type_input_parameter_defaults_at_runtime():315 """Omitting the input type parameter works at runtime on every316 supported Python. The ``Any`` default is native (PEP 696) on Python317 3.13+, and backfilled by ``ParamType.__class_getitem__`` before318 that."""319 assert t.get_args(click.ParamType[int]) == (int, t.Any)320 assert t.get_args(click.ParamType[int, str]) == (int, str)321322323def test_param_type_subclass_omitting_input_parameter():324 class DoublingType(click.ParamType[int]):325 name = "doubling"326327 def convert(self, value, param, ctx):328 return int(value) * 2329330 doubling = DoublingType()331 assert doubling("21") == 42332 assert doubling(None) is None