Debian Codegraph @

testing/test_link_resolve.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 from contextlib import contextmanager
5 import os.path
6 from pathlib import Path
7 from string import ascii_lowercase
8 import subprocess
9 import sys
10 import textwrap
11
12 from _pytest.pytester import Pytester
13
14
15 @contextmanager
16 def subst_path_windows(filepath: Path):
17 for c in ascii_lowercase[7:]: # Create a subst drive from H-Z.
18 c += ":"
19 if not os.path.exists(c):
20 drive = c
21 break
22 else:
23 raise AssertionError("Unable to find suitable drive letter for subst.")
24
25 directory = filepath.parent
26 basename = filepath.name
27
28 args = ["subst", drive, str(directory)]
29 subprocess.check_call(args)
30 assert os.path.exists(drive)
31 try:
32 filename = Path(drive, os.sep, basename)
33 yield filename
34 finally:
35 args = ["subst", "/D", drive]
36 subprocess.check_call(args)
37
38
39 @contextmanager
40 def subst_path_linux(filepath: Path):
41 directory = filepath.parent
42 basename = filepath.name
43
44 target = directory / ".." / "sub2"
45 os.symlink(str(directory), str(target), target_is_directory=True)
46 try:
47 filename = target / basename
48 yield filename
49 finally:
50 # We don't need to unlink (it's all in the tempdir).
51 pass
52
53
54 def test_link_resolve(pytester: Pytester) -> None:
55 """See: https://github.com/pytest-dev/pytest/issues/5965."""
56 sub1 = pytester.mkpydir("sub1")
57 p = sub1.joinpath("test_foo.py")
58 p.write_text(
59 textwrap.dedent(
60 """
61 import pytest
62 def test_foo():
63 raise AssertionError()
64 """
65 ),
66 encoding="utf-8",
67 )
68
69 subst = subst_path_linux
70 if sys.platform == "win32":
71 subst = subst_path_windows
72
73 with subst(p) as subst_p:
74 result = pytester.runpytest(str(subst_p), "-v")
75 # i.e.: Make sure that the error is reported as a relative path, not as a
76 # resolved path.
77 # See: https://github.com/pytest-dev/pytest/issues/5965
78 stdout = result.stdout.str()
79 assert "sub1/test_foo.py" not in stdout
80
81 # i.e.: Expect drive on windows because we just have drive:filename, whereas
82 # we expect a relative path on Linux.
83 expect = f"*{subst_p}*" if sys.platform == "win32" else "*sub2/test_foo.py*"
84 result.stdout.fnmatch_lines([expect])