Skip to content

Commit 1186137

Browse files
committed
Expand to long paths when resolving collection arguments
1 parent 6cacb4b commit 1186137

File tree

3 files changed

+77
-29
lines changed

3 files changed

+77
-29
lines changed

src/_pytest/compat.py

+33-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# mypy: allow-untyped-defs
2-
"""Python version compatibility code."""
2+
"""Python version and platform compatibility code."""
33
from __future__ import annotations
44

55
import dataclasses
@@ -301,6 +301,38 @@ def get_user_id() -> int | None:
301301
return uid if uid != ERROR else None
302302

303303

304+
if sys.platform == "win32":
305+
from ctypes import create_unicode_buffer
306+
from ctypes import windll
307+
308+
def ensure_long_path(p: Path) -> Path:
309+
"""
310+
Ensures the given path contains its long form in Windows.
311+
312+
Short-paths follow the DOS restriction of 8 characters + 3 chars for file extension,
313+
and are still supported by Windows.
314+
"""
315+
if not p.exists():
316+
return p
317+
short_path = os.fspath(p)
318+
# Use a buffer twice the size of the original path size to (reasonably) ensure we will be able
319+
# to hold the long path.
320+
buffer_size = len(short_path) * 2
321+
buffer = create_unicode_buffer(buffer_size)
322+
windll.kernel32.GetLongPathNameW(short_path, buffer, buffer_size)
323+
long_path_str = buffer.value
324+
# If we could not convert it, probably better to hard-crash this now rather
325+
# than later.
326+
assert long_path_str, f"Failed to convert short path to long path form:\n(size: {len(short_path)}):{short_path}"
327+
return Path(buffer.value)
328+
329+
else:
330+
331+
def ensure_long_path(p: Path) -> Path:
332+
"""No-op in other platforms."""
333+
return p
334+
335+
304336
# Perform exhaustiveness checking.
305337
#
306338
# Consider this example:

src/_pytest/main.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828

2929
from _pytest import nodes
3030
import _pytest._code
31+
from _pytest.compat import ensure_long_path
3132
from _pytest.config import Config
3233
from _pytest.config import directory_arg
3334
from _pytest.config import ExitCode
@@ -901,10 +902,6 @@ def collect(self) -> Iterator[Union[nodes.Item, nodes.Collector]]:
901902
# Path part e.g. `/a/b/` in `/a/b/test_file.py::TestIt::test_it`.
902903
if isinstance(matchparts[0], Path):
903904
is_match = node.path == matchparts[0]
904-
if sys.platform == "win32" and not is_match:
905-
# In case the file paths do not match, fallback to samefile() to
906-
# account for short-paths on Windows (#11895).
907-
is_match = os.path.samefile(node.path, matchparts[0])
908905
# Name part e.g. `TestIt` in `/a/b/test_file.py::TestIt::test_it`.
909906
else:
910907
# TODO: Remove parametrized workaround once collection structure contains
@@ -1012,4 +1009,6 @@ def resolve_collection_argument(
10121009
else "directory argument cannot contain :: selection parts: {arg}"
10131010
)
10141011
raise UsageError(msg.format(arg=arg))
1012+
# Ensure we expand short paths to long paths on Windows (#11895).
1013+
fspath = ensure_long_path(fspath)
10151014
return fspath, parts

testing/test_collection.py

+41-24
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from typing import List
1010

1111
from _pytest.assertion.util import running_on_ci
12+
from _pytest.compat import ensure_long_path
1213
from _pytest.config import ExitCode
1314
from _pytest.fixtures import FixtureRequest
1415
from _pytest.main import _in_venv
@@ -1746,27 +1747,43 @@ def test_foo(): assert True
17461747
assert result.parseoutcomes() == {"passed": 1}
17471748

17481749

1749-
@pytest.mark.skipif(not sys.platform.startswith("win"), reason="Windows only")
1750-
def test_collect_short_file_windows(pytester: Pytester) -> None:
1751-
"""Reproducer for #11895: short paths not colleced on Windows."""
1752-
short_path = tempfile.mkdtemp()
1753-
if "~" not in short_path: # pragma: no cover
1754-
if running_on_ci():
1755-
# On CI, we are expecting that under the current GitHub actions configuration,
1756-
# tempfile.mkdtemp() is producing short paths, so we want to fail to prevent
1757-
# this from silently changing without us noticing.
1758-
pytest.fail(
1759-
f"tempfile.mkdtemp() failed to produce a short path on CI: {short_path}"
1760-
)
1761-
else:
1762-
# We want to skip failing this test locally in this situation because
1763-
# depending on the local configuration tempfile.mkdtemp() might not produce a short path:
1764-
# For example, user might have configured %TEMP% exactly to avoid generating short paths.
1765-
pytest.skip(
1766-
f"tempfile.mkdtemp() failed to produce a short path: {short_path}, skipping"
1767-
)
1768-
1769-
test_file = Path(short_path).joinpath("test_collect_short_file_windows.py")
1770-
test_file.write_text("def test(): pass", encoding="UTF-8")
1771-
result = pytester.runpytest(short_path)
1772-
assert result.parseoutcomes() == {"passed": 1}
1750+
class TestCollectionShortPaths:
1751+
@pytest.fixture
1752+
def short_path(self) -> Path:
1753+
short_path = tempfile.mkdtemp()
1754+
if "~" not in short_path: # pragma: no cover
1755+
if running_on_ci():
1756+
# On CI, we are expecting that under the current GitHub actions configuration,
1757+
# tempfile.mkdtemp() is producing short paths, so we want to fail to prevent
1758+
# this from silently changing without us noticing.
1759+
pytest.fail(
1760+
f"tempfile.mkdtemp() failed to produce a short path on CI: {short_path}"
1761+
)
1762+
else:
1763+
# We want to skip failing this test locally in this situation because
1764+
# depending on the local configuration tempfile.mkdtemp() might not produce a short path:
1765+
# For example, user might have configured %TEMP% exactly to avoid generating short paths.
1766+
pytest.skip(
1767+
f"tempfile.mkdtemp() failed to produce a short path: {short_path}, skipping"
1768+
)
1769+
return Path(short_path)
1770+
1771+
@pytest.mark.skipif(not sys.platform.startswith("win"), reason="Windows only")
1772+
def test_ensure_long_path_win(self, short_path: Path) -> None:
1773+
long_path = ensure_long_path(short_path)
1774+
assert len(os.fspath(long_path)) > len(os.fspath(short_path))
1775+
1776+
@pytest.mark.skipif(not sys.platform.startswith("win"), reason="Windows only")
1777+
def test_collect_short_file_windows(
1778+
self, pytester: Pytester, short_path: Path
1779+
) -> None:
1780+
"""Reproducer for #11895: short paths not collected on Windows."""
1781+
test_file = short_path.joinpath("test_collect_short_file_windows.py")
1782+
test_file.write_text("def test(): pass", encoding="UTF-8")
1783+
result = pytester.runpytest(short_path)
1784+
assert result.parseoutcomes() == {"passed": 1}
1785+
1786+
def test_ensure_long_path_general(self, tmp_path: Path) -> None:
1787+
"""Sanity check: a normal path to ensure_long_path works on all platforms."""
1788+
assert ensure_long_path(tmp_path) == tmp_path
1789+
assert ensure_long_path(tmp_path / "non-existent") == tmp_path / "non-existent"

0 commit comments

Comments
 (0)