Debian Codegraph @

tests/test_types.py

raw
1 import os.path
2 import pathlib
3 import platform
4 import tempfile
5
6 import pytest
7
8 import click
9 from click import FileError
10
11
12 @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 )
31 def test_range(type, value, expect):
32 assert type.convert(value, None, None) == expect
33
34
35 @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 )
47 def test_range_fail(type, value, expect):
48 with pytest.raises(click.BadParameter) as exc_info:
49 type.convert(value, None, None)
50
51 assert expect in exc_info.value.message
52
53
54 def test_float_range_no_clamp_open():
55 with pytest.raises(TypeError):
56 click.FloatRange(0, 1, max_open=True, clamp=True)
57
58 sneaky = click.FloatRange(0, 1, max_open=True)
59 sneaky.clamp = True
60
61 with pytest.raises(RuntimeError):
62 sneaky.convert("1.5", None, None)
63
64
65 @pytest.mark.parametrize(
66 ("nargs", "multiple", "default", "expect"),
67 [
68 (2, False, None, None),
69 (2, False, (None, None), (None, None)),
70 (None, True, None, ()),
71 (None, True, (None, None), (None, None)),
72 (2, True, None, ()),
73 (2, True, [(None, None)], ((None, None),)),
74 (-1, None, None, ()),
75 ],
76 )
77 def test_cast_multi_default(runner, nargs, multiple, default, expect):
78 if nargs == -1:
79 param = click.Argument(["a"], nargs=nargs, default=default)
80 else:
81 param = click.Option(["-a"], nargs=nargs, multiple=multiple, default=default)
82
83 cli = click.Command("cli", params=[param], callback=lambda a: a)
84 result = runner.invoke(cli, standalone_mode=False)
85 assert result.exception is None
86 assert result.return_value == expect
87
88
89 @pytest.mark.parametrize(
90 ("cls", "expect"),
91 [
92 (None, "a/b/c.txt"),
93 (str, "a/b/c.txt"),
94 (bytes, b"a/b/c.txt"),
95 (pathlib.Path, pathlib.Path("a", "b", "c.txt")),
96 ],
97 )
98 def test_path_type(runner, cls, expect):
99 cli = click.Command(
100 "cli",
101 params=[click.Argument(["p"], type=click.Path(path_type=cls))],
102 callback=lambda p: p,
103 )
104 result = runner.invoke(cli, ["a/b/c.txt"], standalone_mode=False)
105 assert result.exception is None
106 assert result.return_value == expect
107
108
109 def _symlinks_supported():
110 with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:
111 target = os.path.join(tempdir, "target")
112 open(target, "w").close()
113 link = os.path.join(tempdir, "link")
114
115 try:
116 os.symlink(target, link)
117 return True
118 except OSError:
119 return False
120
121
122 @pytest.mark.skipif(
123 not _symlinks_supported(), reason="The current OS or FS doesn't support symlinks."
124 )
125 def test_path_resolve_symlink(tmp_path, runner):
126 test_file = tmp_path / "file"
127 test_file_str = os.fspath(test_file)
128 test_file.write_text("")
129
130 path_type = click.Path(resolve_path=True)
131 param = click.Argument(["a"], type=path_type)
132 ctx = click.Context(click.Command("cli", params=[param]))
133
134 test_dir = tmp_path / "dir"
135 test_dir.mkdir()
136
137 abs_link = test_dir / "abs"
138 abs_link.symlink_to(test_file)
139 abs_rv = path_type.convert(os.fspath(abs_link), param, ctx)
140 assert abs_rv == test_file_str
141
142 rel_link = test_dir / "rel"
143 rel_link.symlink_to(pathlib.Path("..") / "file")
144 rel_rv = path_type.convert(os.fspath(rel_link), param, ctx)
145 assert rel_rv == test_file_str
146
147
148 def _non_utf8_filenames_supported():
149 with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:
150 try:
151 f = open(os.path.join(tempdir, "\udcff"), "w")
152 except OSError:
153 return False
154
155 f.close()
156 return True
157
158
159 @pytest.mark.skipif(
160 not _non_utf8_filenames_supported(),
161 reason="The current OS or FS doesn't support non-UTF-8 filenames.",
162 )
163 def test_path_surrogates(tmp_path, monkeypatch):
164 monkeypatch.chdir(tmp_path)
165 type = click.Path(exists=True)
166 path = pathlib.Path("\udcff")
167
168 with pytest.raises(click.BadParameter, match="'�' does not exist"):
169 type.convert(path, None, None)
170
171 type = click.Path(file_okay=False)
172 path.touch()
173
174 with pytest.raises(click.BadParameter, match="'�' is a file"):
175 type.convert(path, None, None)
176
177 path.unlink()
178 type = click.Path(dir_okay=False)
179 path.mkdir()
180
181 with pytest.raises(click.BadParameter, match="'�' is a directory"):
182 type.convert(path, None, None)
183
184 path.rmdir()
185
186 def no_access(*args, **kwargs):
187 """Test environments may be running as root, so we have to fake the result of
188 the access tests that use os.access
189 """
190 p = args[0]
191 assert p == path, f"unexpected os.access call on file not under test: {p!r}"
192 return False
193
194 path.touch()
195 type = click.Path(readable=True)
196
197 with pytest.raises(click.BadParameter, match="'�' is not readable"):
198 with monkeypatch.context() as m:
199 m.setattr(os, "access", no_access)
200 type.convert(path, None, None)
201
202 type = click.Path(readable=False, writable=True)
203
204 with pytest.raises(click.BadParameter, match="'�' is not writable"):
205 with monkeypatch.context() as m:
206 m.setattr(os, "access", no_access)
207 type.convert(path, None, None)
208
209 type = click.Path(readable=False, executable=True)
210
211 with pytest.raises(click.BadParameter, match="'�' is not executable"):
212 with monkeypatch.context() as m:
213 m.setattr(os, "access", no_access)
214 type.convert(path, None, None)
215
216 path.unlink()
217
218
219 @pytest.mark.parametrize(
220 "type",
221 [
222 click.File(mode="r"),
223 click.File(mode="r", lazy=True),
224 ],
225 )
226 def test_file_surrogates(type, tmp_path):
227 path = tmp_path / "\udcff"
228
229 # - common case: �': No such file or directory
230 # - special case: Illegal byte sequence
231 # The spacial case is seen with rootless Podman. The root cause is most
232 # likely that the path is handled by a user-space program (FUSE).
233 match = r"(�': No such file or directory|Illegal byte sequence)"
234 with pytest.raises(click.BadParameter, match=match):
235 type.convert(path, None, None)
236
237
238 def test_file_error_surrogates():
239 message = FileError(filename="\udcff").format_message()
240 assert message == "Could not open file '�': unknown error"
241
242
243 @pytest.mark.skipif(
244 platform.system() == "Windows", reason="Filepath syntax differences."
245 )
246 def test_invalid_path_with_esc_sequence():
247 with pytest.raises(click.BadParameter) as exc_info:
248 with tempfile.TemporaryDirectory(prefix="my\ndir") as tempdir:
249 click.Path(dir_okay=False).convert(tempdir, None, None)
250
251 assert "my\\ndir" in exc_info.value.message
252
253
254 def test_choice_get_invalid_choice_message():
255 choice = click.Choice(["a", "b", "c"])
256 message = choice.get_invalid_choice_message("d", ctx=None)
257 assert message == "'d' is not one of 'a', 'b', 'c'."