test_types.py
This file
Path
tests/test_types.py
285 lines · 8.7 KiB · Python
Last changed by
Accept ZFS error-message for non-UTF-8 names (#3526)Rowlando13before adoption567d7e9
History of this fileTake it
1import os.path2import pathlib3import platform4import tempfile56import pytest78import click9from click import FileError101112@pytest.mark.parametrize(13 ("type", "value", "expect"),14 [15 (click.IntRange(0, 5), "3", 3),16 (click.IntRange(5), "5", 5),17 (click.IntRange(5), "100", 100),18 (click.IntRange(max=5), "5", 5),19 (click.IntRange(max=5), "-100", -100),20 (click.IntRange(0, clamp=True), "-1", 0),21 (click.IntRange(max=5, clamp=True), "6", 5),22 (click.IntRange(0, min_open=True, clamp=True), "0", 1),23 (click.IntRange(max=5, max_open=True, clamp=True), "5", 4),24 (click.FloatRange(0.5, 1.5), "1.2", 1.2),25 (click.FloatRange(0.5, min_open=True), "0.51", 0.51),26 (click.FloatRange(max=1.5, max_open=True), "1.49", 1.49),27 (click.FloatRange(0.5, clamp=True), "-0.0", 0.5),28 (click.FloatRange(max=1.5, clamp=True), "inf", 1.5),29 ],30)31def test_range(type, value, expect):32 assert type.convert(value, None, None) == expect333435@pytest.mark.parametrize(36 ("type", "value", "expect"),37 [38 (click.IntRange(0, 5), "6", "6 is not in the range 0<=x<=5."),39 (click.IntRange(5), "4", "4 is not in the range x>=5."),40 (click.IntRange(max=5), "6", "6 is not in the range x<=5."),41 (click.IntRange(0, 5, min_open=True), 0, "0<x<=5"),42 (click.IntRange(0, 5, max_open=True), 5, "0<=x<5"),43 (click.FloatRange(0.5, min_open=True), 0.5, "x>0.5"),44 (click.FloatRange(max=1.5, max_open=True), 1.5, "x<1.5"),45 ],46)47def test_range_fail(type, value, expect):48 with pytest.raises(click.BadParameter) as exc_info:49 type.convert(value, None, None)5051 assert expect in exc_info.value.message525354@pytest.mark.parametrize(55 ("error_message", "expected"),56 [57 ("bad value: nope", "bad value: nope"),58 ("", "nope"),59 ],60)61def test_func_param_type_uses_value_error_message(error_message, expected):62 def parse(value):63 raise ValueError(error_message if error_message else "")6465 func_type = click.types.FuncParamType(parse)6667 with pytest.raises(click.BadParameter) as exc_info:68 func_type.convert("nope", None, None)6970 assert expected in exc_info.value.message717273def test_float_range_no_clamp_open():74 with pytest.raises(TypeError):75 click.FloatRange(0, 1, max_open=True, clamp=True)7677 sneaky = click.FloatRange(0, 1, max_open=True)78 sneaky.clamp = True7980 with pytest.raises(RuntimeError):81 sneaky.convert("1.5", None, None)828384@pytest.mark.parametrize(85 ("nargs", "multiple", "default", "expect"),86 [87 (2, False, None, None),88 (2, False, (None, None), (None, None)),89 (None, True, None, ()),90 (None, True, (None, None), (None, None)),91 (2, True, None, ()),92 (2, True, [(None, None)], ((None, None),)),93 (-1, None, None, ()),94 ],95)96def test_cast_multi_default(runner, nargs, multiple, default, expect):97 if nargs == -1:98 param = click.Argument(["a"], nargs=nargs, default=default)99 else:100 param = click.Option(["-a"], nargs=nargs, multiple=multiple, default=default)101102 cli = click.Command("cli", params=[param], callback=lambda a: a)103 result = runner.invoke(cli, standalone_mode=False)104 assert result.exception is None105 assert result.return_value == expect106107108@pytest.mark.parametrize(109 ("cls", "expect"),110 [111 (None, "a/b/c.txt"),112 (str, "a/b/c.txt"),113 (bytes, b"a/b/c.txt"),114 (pathlib.Path, pathlib.Path("a", "b", "c.txt")),115 ],116)117def test_path_type(runner, cls, expect):118 cli = click.Command(119 "cli",120 params=[click.Argument(["p"], type=click.Path(path_type=cls))],121 callback=lambda p: p,122 )123 result = runner.invoke(cli, ["a/b/c.txt"], standalone_mode=False)124 assert result.exception is None125 assert result.return_value == expect126127128def _symlinks_supported():129 with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:130 target = os.path.join(tempdir, "target")131 open(target, "w").close()132 link = os.path.join(tempdir, "link")133134 try:135 os.symlink(target, link)136 return True137 except OSError:138 return False139140141@pytest.mark.skipif(142 not _symlinks_supported(), reason="The current OS or FS doesn't support symlinks."143)144def test_path_resolve_symlink(tmp_path, runner):145 test_file = tmp_path / "file"146 test_file_str = os.fspath(test_file)147 test_file.write_text("")148149 path_type = click.Path(resolve_path=True)150 param = click.Argument(["a"], type=path_type)151 ctx = click.Context(click.Command("cli", params=[param]))152153 test_dir = tmp_path / "dir"154 test_dir.mkdir()155156 abs_link = test_dir / "abs"157 abs_link.symlink_to(test_file)158 abs_rv = path_type.convert(os.fspath(abs_link), param, ctx)159 assert abs_rv == test_file_str160161 rel_link = test_dir / "rel"162 rel_link.symlink_to(pathlib.Path("..") / "file")163 rel_rv = path_type.convert(os.fspath(rel_link), param, ctx)164 assert rel_rv == test_file_str165166167def _non_utf8_filenames_supported():168 with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:169 try:170 f = open(os.path.join(tempdir, "\udcff"), "w")171 except OSError:172 return False173174 f.close()175 return True176177178@pytest.mark.skipif(179 not _non_utf8_filenames_supported(),180 reason="The current OS or FS doesn't support non-UTF-8 filenames.",181)182def test_path_surrogates(tmp_path, monkeypatch):183 monkeypatch.chdir(tmp_path)184 type = click.Path(exists=True)185 path = pathlib.Path("\udcff")186187 with pytest.raises(click.BadParameter, match="'�' does not exist"):188 type.convert(path, None, None)189190 type = click.Path(file_okay=False)191 path.touch()192193 with pytest.raises(click.BadParameter, match="'�' is a file"):194 type.convert(path, None, None)195196 path.unlink()197 type = click.Path(dir_okay=False)198 path.mkdir()199200 with pytest.raises(click.BadParameter, match="'�' is a directory"):201 type.convert(path, None, None)202203 path.rmdir()204205 def no_access(*args, **kwargs):206 """Test environments may be running as root, so we have to fake the result of207 the access tests that use os.access208 """209 p = args[0]210 assert p == path, f"unexpected os.access call on file not under test: {p!r}"211 return False212213 path.touch()214 type = click.Path(readable=True)215216 with pytest.raises(click.BadParameter, match="'�' is not readable"):217 with monkeypatch.context() as m:218 m.setattr(os, "access", no_access)219 type.convert(path, None, None)220221 type = click.Path(readable=False, writable=True)222223 with pytest.raises(click.BadParameter, match="'�' is not writable"):224 with monkeypatch.context() as m:225 m.setattr(os, "access", no_access)226 type.convert(path, None, None)227228 type = click.Path(readable=False, executable=True)229230 with pytest.raises(click.BadParameter, match="'�' is not executable"):231 with monkeypatch.context() as m:232 m.setattr(os, "access", no_access)233 type.convert(path, None, None)234235 path.unlink()236237238@pytest.mark.parametrize(239 "type",240 [241 click.File(mode="r"),242 click.File(mode="r", lazy=True),243 ],244)245def test_file_surrogates(type, tmp_path):246 """Ensures that the error handling in ``click.File`` is robust.247248 ``EILSEQ`` shows up with rootless Podman (FUSE-backed paths) and on filesystems249 that reject non-UTF-8 names, like ZFS with ``utf8only=on``.250251 See: https://github.com/pallets/click/issues/2634252 """253 path = tmp_path / "\udcff"254 match = (255 # Common case: �': No such file or directory.256 r"(�': No such file or directory"257 # BSD/macOS libc special case (EILSEQ).258 r"|Illegal byte sequence"259 # glibc special case (EILSEQ).260 r"|Invalid or incomplete multibyte or wide character)"261 )262 with pytest.raises(click.BadParameter, match=match):263 type.convert(path, None, None)264265266def test_file_error_surrogates():267 message = FileError(filename="\udcff").format_message()268 assert message == "Could not open file '�': unknown error"269270271@pytest.mark.skipif(272 platform.system() == "Windows", reason="Filepath syntax differences."273)274def test_invalid_path_with_esc_sequence():275 with pytest.raises(click.BadParameter) as exc_info:276 with tempfile.TemporaryDirectory(prefix="my\ndir") as tempdir:277 click.Path(dir_okay=False).convert(tempdir, None, None)278279 assert "my\\ndir" in exc_info.value.message280281282def test_choice_get_invalid_choice_message():283 choice = click.Choice(["a", "b", "c"])284 message = choice.get_invalid_choice_message("d", ctx=None)285 assert message == "'d' is not one of 'a', 'b', 'c'."