Debian Codegraph @

tests/tox_env/python/pip/req/test_file.py

raw
1 from __future__ import annotations
2
3 import os
4 import sys
5 from contextlib import contextmanager
6 from io import BytesIO
7 from typing import IO, TYPE_CHECKING, Any
8
9 import pytest
10
11 from tox.tox_env.python.pip.req.file import ParsedRequirement, RequirementsFile
12
13 if TYPE_CHECKING:
14 from collections.abc import Iterator
15 from pathlib import Path
16
17 from pytest_mock import MockerFixture
18
19 from tox.pytest import CaptureFixture, MonkeyPatch
20
21 _REQ_FILE_TEST_CASES = [
22 pytest.param("--pre", {"pre": True}, [], ["--pre"], id="pre"),
23 pytest.param("--no-index", {"index_url": []}, [], ["--no-index"], id="no-index"),
24 pytest.param("--no-index\n-i a\n--no-index", {"index_url": []}, [], ["--no-index"], id="no-index overwrites index"),
25 pytest.param("--prefer-binary", {"prefer_binary": True}, [], ["--prefer-binary"], id="prefer-binary"),
26 pytest.param("--require-hashes", {"require_hashes": True}, [], ["--require-hashes"], id="requires-hashes"),
27 pytest.param("--pre ", {"pre": True}, [], ["--pre"], id="space after"),
28 pytest.param(" --pre", {"pre": True}, [], ["--pre"], id="space before"),
29 pytest.param("--pre\\\n", {"pre": True}, [], ["--pre"], id="newline after"),
30 pytest.param("--pre # magic", {"pre": True}, [], ["--pre"], id="comment after space"),
31 pytest.param("--pre\t# magic", {"pre": True}, [], ["--pre"], id="comment after tab"),
32 pytest.param(
33 "--find-links /my/local/archives",
34 {"find_links": ["/my/local/archives"]},
35 [],
36 ["-f", "/my/local/archives"],
37 id="find-links path",
38 ),
39 pytest.param(
40 "--find-links /my/local/archives --find-links /my/local/archives",
41 {"find_links": ["/my/local/archives"]},
42 [],
43 ["-f", "/my/local/archives"],
44 id="find-links duplicate same line",
45 ),
46 pytest.param(
47 "--find-links /my/local/archives\n--find-links /my/local/archives",
48 {"find_links": ["/my/local/archives"]},
49 [],
50 ["-f", "/my/local/archives"],
51 id="find-links duplicate different line",
52 ),
53 pytest.param(
54 "--find-links \\\n/my/local/archives",
55 {"find_links": ["/my/local/archives"]},
56 [],
57 ["-f", "/my/local/archives"],
58 id="find-links newline path",
59 ),
60 pytest.param(
61 "--find-links http://some.archives.com/archives",
62 {"find_links": ["http://some.archives.com/archives"]},
63 [],
64 ["-f", "http://some.archives.com/archives"],
65 id="find-links url",
66 ),
67 pytest.param(
68 "--index-url a --find-links http://some.archives.com/archives",
69 {
70 "index_url": ["a"],
71 "find_links": ["http://some.archives.com/archives"],
72 },
73 [],
74 ["-i", "a", "-f", "http://some.archives.com/archives"],
75 id="index and find",
76 ),
77 pytest.param("-i a", {"index_url": ["a"]}, [], ["-i", "a"], id="index url short"),
78 pytest.param("--index-url a", {"index_url": ["a"]}, [], ["-i", "a"], id="index url long"),
79 pytest.param("-i a -i b\n-i c", {"index_url": ["c"]}, [], ["-i", "c"], id="index url multiple"),
80 pytest.param(
81 "--extra-index-url a",
82 {"index_url": ["https://pypi.org/simple", "a"]},
83 [],
84 ["--extra-index-url", "a"],
85 id="extra-index-url",
86 ),
87 pytest.param(
88 "--extra-index-url a --extra-index-url a",
89 {"index_url": ["https://pypi.org/simple", "a"]},
90 [],
91 ["--extra-index-url", "a"],
92 id="extra-index-url dup same line",
93 ),
94 pytest.param(
95 "--extra-index-url a\n--extra-index-url a",
96 {"index_url": ["https://pypi.org/simple", "a"]},
97 [],
98 ["--extra-index-url", "a"],
99 id="extra-index-url dup different line",
100 ),
101 pytest.param("-e a", {}, ["-e a"], ["-e", "a"], id="e"),
102 pytest.param("--editable a", {}, ["-e a"], ["-e", "a"], id="editable"),
103 pytest.param("--editable .[2,1]", {}, ["-e .[1,2]"], ["-e", ".[1,2]"], id="editable extra"),
104 pytest.param(".[\t, a1. , B2-\t, C3_, ]", {}, [".[B2-,C3_,a1.]"], [".[B2-,C3_,a1.]"], id="path with extra"),
105 pytest.param(".[a.1]", {}, [f".{os.sep}.[a.1]"], [f".{os.sep}.[a.1]"], id="path with invalid extra is path"),
106 pytest.param("-f a", {"find_links": ["a"]}, [], ["-f", "a"], id="f"),
107 pytest.param("--find-links a", {"find_links": ["a"]}, [], ["-f", "a"], id="find-links"),
108 pytest.param("--trusted-host a", {"trusted_hosts": ["a"]}, [], ["--trusted-host", "a"], id="trusted-host"),
109 pytest.param(
110 "--trusted-host a --trusted-host a",
111 {"trusted_hosts": ["a"]},
112 [],
113 ["--trusted-host", "a"],
114 id="trusted-host dup same line",
115 ),
116 pytest.param(
117 "--trusted-host a\n--trusted-host a",
118 {"trusted_hosts": ["a"]},
119 [],
120 ["--trusted-host", "a"],
121 id="trusted-host dup different line",
122 ),
123 pytest.param(
124 "--use-feature 2020-resolver",
125 {"features_enabled": ["2020-resolver"]},
126 [],
127 ["--use-feature", "2020-resolver"],
128 id="use-feature space",
129 ),
130 pytest.param(
131 "--use-feature=fast-deps",
132 {"features_enabled": ["fast-deps"]},
133 [],
134 ["--use-feature", "fast-deps"],
135 id="use-feature equal",
136 ),
137 pytest.param(
138 "--use-feature=fast-deps --use-feature 2020-resolver",
139 {"features_enabled": ["2020-resolver", "fast-deps"]},
140 [],
141 ["--use-feature", "2020-resolver", "--use-feature", "fast-deps"],
142 id="use-feature multiple same line",
143 ),
144 pytest.param(
145 "--use-feature=fast-deps\n--use-feature 2020-resolver",
146 {"features_enabled": ["2020-resolver", "fast-deps"]},
147 [],
148 ["--use-feature", "2020-resolver", "--use-feature", "fast-deps"],
149 id="use-feature multiple different line",
150 ),
151 pytest.param(
152 "--use-feature=fast-deps\n--use-feature 2020-resolver\n" * 2,
153 {"features_enabled": ["2020-resolver", "fast-deps"]},
154 [],
155 ["--use-feature", "2020-resolver", "--use-feature", "fast-deps"],
156 id="use-feature multiple duplicate different line",
157 ),
158 pytest.param("--no-binary :all:", {"no_binary": {":all:"}}, [], ["--no-binary", {":all:"}], id="no-binary all"),
159 pytest.param("--no-binary :none:", {"no_binary": {":none:"}}, [], [], id="no-binary none"),
160 pytest.param(
161 "--only-binary :all:",
162 {"only_binary": {":all:"}},
163 [],
164 ["--only-binary", {":all:"}],
165 id="only-binary all",
166 ),
167 pytest.param(
168 "--only-binary :none:",
169 {"only_binary": {":none:"}},
170 [],
171 [],
172 id="only-binary none",
173 ),
174 pytest.param(
175 "--no-binary=foo --only-binary=foo",
176 {"only_binary": {"foo"}},
177 [],
178 ["--only-binary", {"foo"}],
179 id="no-binary-and-only-binary",
180 ),
181 pytest.param(
182 "--no-binary=foo --no-binary=:none:",
183 {},
184 [],
185 [],
186 id="no-binary-none-last",
187 ),
188 pytest.param(
189 "--only-binary=:none: --no-binary=foo",
190 {"no_binary": {"foo"}},
191 [],
192 ["--no-binary", {"foo"}],
193 id="no-binary-none-first",
194 ),
195 pytest.param(
196 "--only-binary foo; sys_platform == 'aix'",
197 {"only_binary": {"foo;"}},
198 [],
199 ["--only-binary", {"foo;"}],
200 id="only-binary-and-env-marker",
201 ),
202 pytest.param("####### example-requirements.txt #######", {}, [], [], id="comment"),
203 pytest.param("\t##### Requirements without Version Specifiers ######", {}, [], [], id="tab and comment"),
204 pytest.param(" # start", {}, [], [], id="space and comment"),
205 pytest.param("nose", {}, ["nose"], ["nose"], id="req"),
206 pytest.param("nose\nnose", {}, ["nose"], ["nose"], id="req dup"),
207 pytest.param(
208 "numpy[2,1] @ file://./downloads/numpy-1.9.2-cp34-none-win32.whl",
209 {},
210 ["numpy[1,2] @ file://./downloads/numpy-1.9.2-cp34-none-win32.whl"],
211 ["numpy[1,2] @ file://./downloads/numpy-1.9.2-cp34-none-win32.whl"],
212 id="path with name-extra-protocol",
213 ),
214 pytest.param(
215 "docopt == 0.6.1 # Version Matching. Must be version 0.6.1",
216 {},
217 ["docopt==0.6.1"],
218 ["docopt==0.6.1"],
219 id="req equal comment",
220 ),
221 pytest.param(
222 "keyring >= 4.1.1 # Minimum version 4.1.1",
223 {},
224 ["keyring>=4.1.1"],
225 ["keyring>=4.1.1"],
226 id="req ge comment",
227 ),
228 pytest.param(
229 "coverage != 3.5 # Version Exclusion. Anything except version 3.5",
230 {},
231 ["coverage!=3.5"],
232 ["coverage!=3.5"],
233 id="req ne comment",
234 ),
235 pytest.param(
236 "Mopidy-Dirble ~= 1.1 # Compatible release. Same as >= 1.1, == 1.*",
237 {},
238 ["Mopidy-Dirble~=1.1"],
239 ["Mopidy-Dirble~=1.1"],
240 id="req approx comment",
241 ),
242 pytest.param("b==1.3", {}, ["b==1.3"], ["b==1.3"], id="req eq"),
243 pytest.param("c >=1.2,<2.0", {}, ["c<2.0,>=1.2"], ["c<2.0,>=1.2"], id="req ge lt"),
244 pytest.param("d[bar,foo]", {}, ["d[bar,foo]"], ["d[bar,foo]"], id="req extras"),
245 pytest.param("d[foo, bar]", {}, ["d[bar,foo]"], ["d[bar,foo]"], id="req extras space"),
246 pytest.param("d[foo,\tbar]", {}, ["d[bar,foo]"], ["d[bar,foo]"], id="req extras tab"),
247 pytest.param("e~=1.4.2", {}, ["e~=1.4.2"], ["e~=1.4.2"], id="req approx"),
248 pytest.param(
249 "f ==5.4 ; python_version < '2.7'",
250 {},
251 ['f==5.4; python_version < "2.7"'],
252 ['f==5.4; python_version < "2.7"'],
253 id="python version filter",
254 ),
255 pytest.param(
256 "g; sys_platform == 'win32'",
257 {},
258 ['g; sys_platform == "win32"'],
259 ['g; sys_platform == "win32"'],
260 id="platform filter",
261 ),
262 pytest.param(
263 "http://w.org/w_P-3.0.3.dev1820+49a8884-cp34-none-win_amd64.whl",
264 {},
265 ["http://w.org/w_P-3.0.3.dev1820+49a8884-cp34-none-win_amd64.whl"],
266 ["http://w.org/w_P-3.0.3.dev1820+49a8884-cp34-none-win_amd64.whl"],
267 id="http URI",
268 ),
269 pytest.param(
270 "git+https://git.example.com/MyProject#egg=MyProject",
271 {},
272 ["git+https://git.example.com/MyProject#egg=MyProject"],
273 ["git+https://git.example.com/MyProject#egg=MyProject"],
274 id="vcs with https",
275 ),
276 pytest.param(
277 "git+ssh://git.example.com/MyProject#egg=MyProject",
278 {},
279 ["git+ssh://git.example.com/MyProject#egg=MyProject"],
280 ["git+ssh://git.example.com/MyProject#egg=MyProject"],
281 id="vcs with ssh",
282 ),
283 pytest.param(
284 "git+https://git.example.com/MyProject.git@da39a3ee5e6b4b0d3255bfef95601890afd80709#egg=MyProject",
285 {},
286 ["git+https://git.example.com/MyProject.git@da39a3ee5e6b4b0d3255bfef95601890afd80709#egg=MyProject"],
287 ["git+https://git.example.com/MyProject.git@da39a3ee5e6b4b0d3255bfef95601890afd80709#egg=MyProject"],
288 id="vcs with commit hash pin",
289 ),
290 pytest.param(
291 "attrs --hash sha384:142d9b02f3f4511ccabf6c14bd34d2b0a9ed043a898228b48343cfdf4eb10856ef7ad5e2ff2c528ecae04"
292 "912224782ab\t--hash=sha256:af957b369adcd07e5b3c64d2cdb76d6808c5e0b16c35ca41c79c8eee34808152 # ok",
293 {},
294 [
295 (
296 "attrs --hash sha256:af957b369adcd07e5b3c64d2cdb76d6808c5e0b16c35ca41c79c8eee34808152 --hash sha384:"
297 "142d9b02f3f4511ccabf6c14bd34d2b0a9ed043a898228b48343cfdf4eb10856ef7ad5e2ff2c528ecae04912224782ab"
298 ),
299 ],
300 ["attrs"],
301 id="hash",
302 ),
303 pytest.param(
304 "attrs --hash=sha256:af957b369adcd07e5b3c64d2cdb76d6808c5e0b16c35ca41c79c8eee34808152\\\n "
305 "--hash sha384:142d9b02f3f4511ccabf6c14bd34d2b0a9ed043a898228b48343cfdf4eb10856ef7ad5"
306 "e2ff2c528ecae04912224782ab\n",
307 {},
308 [
309 (
310 "attrs --hash sha256:af957b369adcd07e5b3c64d2cdb76d6808c5e0b16c35ca41c79c8eee34808152 --hash sha384:"
311 "142d9b02f3f4511ccabf6c14bd34d2b0a9ed043a898228b48343cfdf4eb10856ef7ad5e2ff2c528ecae04912224782ab"
312 ),
313 ],
314 ["attrs"],
315 id="hash with escaped newline",
316 ),
317 pytest.param(
318 "attrs --hash=sha512:7a91e5a3d1a1238525e477385ef5ee6cecdc8f8fcc2a79d1b35a9f57ad15c814"
319 "dada670026f41fdd62e5e10b3fd75d6112704a9521c3df105f0b6f3bb11b128a",
320 {},
321 [
322 (
323 "attrs --hash sha512:7a91e5a3d1a1238525e477385ef5ee6cecdc8f8fcc2a79d1b35a9f57ad15c814"
324 "dada670026f41fdd62e5e10b3fd75d6112704a9521c3df105f0b6f3bb11b128a"
325 ),
326 ],
327 ["attrs"],
328 id="sha512 hash is supported",
329 ),
330 pytest.param(
331 "\tp @ https://github.com/a/b/c/d.zip ",
332 {},
333 ["p @ https://github.com/a/b/c/d.zip"],
334 ["p @ https://github.com/a/b/c/d.zip"],
335 id="whitespace around",
336 ),
337 ]
338
339
340 @pytest.mark.parametrize(("req", "opts", "requirements", "as_args"), _REQ_FILE_TEST_CASES)
341 def test_req_file(tmp_path: Path, req: str, opts: dict[str, Any], requirements: list[str], as_args: list[str]) -> None:
342 requirements_txt = tmp_path / "req.txt"
343 requirements_txt.write_text(req)
344 req_file = RequirementsFile(requirements_txt, constraint=False)
345 assert req_file.as_root_args == as_args
346 assert str(req_file) == f"-r {requirements_txt}"
347 assert vars(req_file.options) == (opts if {":none:"} not in opts.values() else {})
348 found = [str(i) for i in req_file.requirements]
349 assert found == requirements
350
351
352 def test_requirements_env_var_present(monkeypatch: MonkeyPatch, tmp_path: Path) -> None:
353 monkeypatch.setenv("ENV_VAR", "beta")
354 requirements_file = tmp_path / "req.txt"
355 requirements_file.write_text("${ENV_VAR} >= 1")
356 req_file = RequirementsFile(requirements_file, constraint=False)
357 assert vars(req_file.options) == {}
358 found = [str(i) for i in req_file.requirements]
359 assert found == ["beta>=1"]
360
361
362 def test_requirements_env_var_missing(monkeypatch: MonkeyPatch, tmp_path: Path) -> None:
363 monkeypatch.delenv("ENV_VAR", raising=False)
364 requirements_file = tmp_path / "req.txt"
365 requirements_file.write_text("${ENV_VAR}")
366 req_file = RequirementsFile(requirements_file, constraint=False)
367 assert vars(req_file.options) == {}
368 found = [str(i) for i in req_file.requirements]
369 assert found == [f".{os.sep}${{ENV_VAR}}"]
370
371
372 @pytest.mark.parametrize("flag", ["-r", "--requirement"])
373 def test_requirements_txt_transitive(tmp_path: Path, flag: str) -> None:
374 other_req = tmp_path / "other-requirements.txt"
375 other_req.write_text("magic\nmagical")
376 requirements_file = tmp_path / "req.txt"
377 requirements_file.write_text(f"{flag} other-requirements.txt\n{flag} other-requirements.txt")
378 req_file = RequirementsFile(requirements_file, constraint=False)
379 assert req_file.as_root_args == ["-r", "other-requirements.txt"]
380 assert req_file.as_root_args is req_file.as_root_args # check it's cached
381 assert vars(req_file.options) == {}
382 found = [str(i) for i in req_file.requirements]
383 assert found == ["magic", "magical"]
384
385
386 @pytest.mark.parametrize(
387 ("raw", "error"),
388 [
389 ("--pre something", "unrecognized arguments: something"),
390 ("--missing", "unrecognized arguments: --missing"),
391 ("--index-url a b", "unrecognized arguments: b"),
392 ("--index-url", "argument -i/--index-url/--pypi-url: expected one argument"),
393 ("-k", "unrecognized arguments: -k"),
394 ],
395 )
396 def test_bad_line(tmp_path: Path, raw: str, capfd: CaptureFixture, error: str) -> None:
397 requirements_file = tmp_path / "req.txt"
398 requirements_file.write_text(raw)
399 req_file = RequirementsFile(requirements_file, constraint=False)
400 with pytest.raises(ValueError, match=f"^{error}$"):
401 assert req_file.options
402 out, err = capfd.readouterr()
403 assert not out
404 assert not err
405
406
407 def test_requirements_file_missing(tmp_path: Path) -> None:
408 requirements_file = tmp_path / "req.txt"
409 requirements_file.write_text("-r one.txt")
410 req_file = RequirementsFile(requirements_file, constraint=False)
411 with pytest.raises(ValueError, match=r"No such file or directory: .*one.txt"):
412 assert req_file.options
413
414
415 @pytest.mark.parametrize("flag", ["-c", "--constraint"])
416 def test_constraint_txt_expanded(tmp_path: Path, flag: str) -> None:
417 other_req = tmp_path / "other.txt"
418 other_req.write_text("magic\nmagical\n-i a")
419 requirements_file = tmp_path / "req.txt"
420 requirements_file.write_text(f"{flag} other.txt\n{flag} other.txt")
421 req_file = RequirementsFile(requirements_file, constraint=True)
422 assert req_file.as_root_args == ["-c", "other.txt"]
423 assert vars(req_file.options) == {"index_url": ["a"]}
424 found = [str(i) for i in req_file.requirements]
425 assert found == ["-c magic", "-c magical"]
426
427
428 @pytest.mark.skipif(sys.platform == "win32", reason=r"on windows the escaped \ is overloaded by path separator")
429 def test_req_path_with_space_escape(tmp_path: Path) -> None:
430 dep_requirements_file = tmp_path / "a b"
431 dep_requirements_file.write_text("c")
432 path = f"-r {dep_requirements_file!s}"
433 path = f"{path[: -len('a b')]}a\\ b"
434
435 requirements_file = tmp_path / "req.txt"
436 requirements_file.write_text(path)
437 req_file = RequirementsFile(requirements_file, constraint=False)
438
439 assert vars(req_file.options) == {}
440 found = [str(i) for i in req_file.requirements]
441 assert found == ["c"]
442
443
444 @pytest.mark.parametrize(
445 "hash_value",
446 [
447 "sha256:a",
448 "sha256:xxxxxxxxxx123456789012345678901234567890123456789012345678901234",
449 (
450 "sha512:thisshouldfail8525e477385ef5ee6cecdc8f8fcc2a79d1b35a9f57ad15c814"
451 "dada670026f41fdd62e5e10b3fd75d6112704a9521c3df105f0b6f3bb11b128a"
452 ),
453 ],
454 )
455 def test_bad_hash(hash_value: str, tmp_path: Path) -> None:
456 requirements_txt = tmp_path / "req.txt"
457 requirements_txt.write_text(f"attrs --hash {hash_value}")
458 req_file = RequirementsFile(requirements_txt, constraint=False)
459 with pytest.raises(ValueError, match=f"^argument --hash: {hash_value}$"):
460 assert req_file.requirements
461
462
463 @pytest.mark.parametrize("codec", ["utf-8", "utf-16", "utf-32"])
464 def test_custom_file_encoding(codec: str, tmp_path: Path) -> None:
465 requirements_file = tmp_path / "r.txt"
466 raw = "art".encode(codec)
467 requirements_file.write_bytes(raw)
468 req_file = RequirementsFile(requirements_file, constraint=False)
469 assert [str(i) for i in req_file.requirements] == ["art"]
470
471
472 def test_non_utf8_file_encoding_falls_back_to_locale(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
473 monkeypatch.setattr("tox.tox_env.python.pip.req.file.locale.getpreferredencoding", lambda **_: "latin-1")
474 requirements_file = tmp_path / "r.txt"
475 requirements_file.write_bytes(b"art # \xe9\n")
476 req_file = RequirementsFile(requirements_file, constraint=False)
477 assert [str(i) for i in req_file.requirements] == ["art"]
478
479
480 def test_parsed_requirement_properties(tmp_path: Path) -> None:
481 req = ParsedRequirement("a", {"b": 1}, str(tmp_path), 1)
482 assert req.options == {"b": 1}
483 assert str(req.requirement) == "a"
484 assert req.from_file == str(tmp_path)
485 assert req.lineno == 1
486
487
488 def test_parsed_requirement_repr_with_opt(tmp_path: Path) -> None:
489 req = ParsedRequirement("a", {"b": 1}, str(tmp_path), 1)
490 assert repr(req) == "ParsedRequirement(requirement=a, options={'b': 1})"
491
492
493 def test_parsed_requirement_repr_no_opt(tmp_path: Path) -> None:
494 assert repr(ParsedRequirement("a", {}, str(tmp_path), 2)) == "ParsedRequirement(requirement=a)"
495
496
497 @pytest.mark.parametrize("flag", ["-r", "--requirement", "-c", "--constraint"])
498 def test_req_over_http(tmp_path: Path, flag: str, mocker: MockerFixture) -> None:
499 is_constraint = flag in {"-c", "--constraint"}
500 url_open = mocker.patch("tox.tox_env.python.pip.req.file.urlopen", autospec=True)
501 url_open.return_value.__enter__.return_value = BytesIO(b"-i i\na")
502 requirements_txt = tmp_path / "req.txt"
503 requirements_txt.write_text(f"{flag} https://zopefoundation.github.io/Zope/releases/4.5.5/requirements-full.txt")
504 req_file = RequirementsFile(requirements_txt, constraint=is_constraint)
505 assert str(req_file) == f"-{'c' if is_constraint else 'r'} {requirements_txt}"
506 assert vars(req_file.options) == {"index_url": ["i"]}
507 found = [str(i) for i in req_file.requirements]
508 assert found == [f"{'-c ' if is_constraint else ''}a"]
509 # urlopen must be called with a timeout to avoid hanging on slow / unresponsive mirrors
510 assert url_open.call_args.kwargs.get("timeout") is not None
511
512
513 def test_req_over_http_has_req(tmp_path: Path, mocker: MockerFixture) -> None:
514 @contextmanager
515 def enter(url: str, timeout: float | None = None) -> Iterator[IO[bytes]]: # noqa: ARG001
516 if url == "https://root.org/a.txt":
517 yield BytesIO(b"-r b.txt")
518 elif url == "https://root.org/b.txt":
519 yield BytesIO(b"-i i\na")
520 else: # pragma: no cover
521 raise RuntimeError # pragma: no cover
522
523 mocker.patch("tox.tox_env.python.pip.req.file.urlopen", autospec=True, side_effect=enter)
524
525 requirements_txt = tmp_path / "req.txt"
526 requirements_txt.write_text("-r https://root.org/a.txt")
527 req_file = RequirementsFile(requirements_txt, constraint=False)
528
529 assert vars(req_file.options) == {"index_url": ["i"]}
530 found = [str(i) for i in req_file.requirements]
531 assert found == ["a"]
532
533
534 @pytest.mark.parametrize(
535 "loc",
536 ["file://", "file://localhost"],
537 )
538 def test_requirement_via_file_protocol(tmp_path: Path, loc: str) -> None:
539 other_req = tmp_path / "other-requirements.txt"
540 other_req.write_text("-i i\na")
541 requirements_text = tmp_path / "req.txt"
542 requirements_text.write_text(f"-r {loc}{'/' if sys.platform == 'win32' else ''}{other_req}")
543
544 req_file = RequirementsFile(requirements_text, constraint=False)
545
546 assert vars(req_file.options) == {"index_url": ["i"]}
547 found = [str(i) for i in req_file.requirements]
548 assert found == ["a"]
549
550
551 def test_requirement_via_file_protocol_na(tmp_path: Path) -> None:
552 other_req = tmp_path / "other-requirements.txt"
553 other_req.write_text("-i i\na")
554 requirements_text = tmp_path / "req.txt"
555 requirements_text.write_text(f"-r file://magic.com{'/' if sys.platform == 'win32' else ''}{other_req}")
556
557 req_file = RequirementsFile(requirements_text, constraint=False)
558 pattern = r"non-local file URIs are not supported on this platform: 'file://magic\.com\.*"
559 with pytest.raises(ValueError, match=pattern):
560 assert req_file.options
561
562
563 @pytest.mark.parametrize("req", ["pre-commit ~= 4", "pre-commit~=4"])
564 def test_requirement_with_tilde_equals_not_treated_as_path(tmp_path: Path, req: str) -> None:
565 """Deps with ``~=`` version specifier should not be treated as local paths (#3447)."""
566 parsed = ParsedRequirement(req, {}, str(tmp_path / "tox.ini"), 1)
567 assert str(parsed.requirement) == req
568
569
570 def test_requirement_to_path_one_level_up(tmp_path: Path) -> None:
571 other_req = tmp_path / "other.txt"
572 other_req.write_text("-e ..")
573 req_file = RequirementsFile(other_req, constraint=False)
574 result = req_file.requirements
575 assert result[0].requirement == str(tmp_path.parent.resolve())