bpo-31047: Fix ntpath.abspath for invalid paths (GH-8544)

This commit is contained in:
Franz Wöllert 2018-07-29 14:47:09 +02:00 committed by Steve Dower
parent b7fd73896d
commit d2e902e4fb
3 changed files with 26 additions and 22 deletions

View File

@ -496,14 +496,13 @@ def normpath(path):
comps.append(curdir)
return prefix + sep.join(comps)
def _abspath_fallback(path):
"""Return the absolute version of a path as a fallback function in case
`nt._getfullpathname` is not available or raises OSError. See bpo-31047 for
more.
# Return an absolute path.
try:
from nt import _getfullpathname
"""
except ImportError: # not running on Windows - mock up something sensible
def abspath(path):
"""Return the absolute version of a path."""
path = os.fspath(path)
if not isabs(path):
if isinstance(path, bytes):
@ -513,21 +512,20 @@ except ImportError: # not running on Windows - mock up something sensible
path = join(cwd, path)
return normpath(path)
# Return an absolute path.
try:
from nt import _getfullpathname
except ImportError: # not running on Windows - mock up something sensible
abspath = _abspath_fallback
else: # use native Windows method on Windows
def abspath(path):
"""Return the absolute version of a path."""
if path: # Empty path must return current working directory.
path = os.fspath(path)
try:
path = _getfullpathname(path)
return _getfullpathname(path)
except OSError:
pass # Bad path - return unchanged.
elif isinstance(path, bytes):
path = os.getcwdb()
else:
path = os.getcwd()
return normpath(path)
return _abspath_fallback(path)
# realpath is a no-op on systems without islink support
realpath = abspath

View File

@ -280,6 +280,10 @@ class TestNtpath(unittest.TestCase):
@unittest.skipUnless(nt, "abspath requires 'nt' module")
def test_abspath(self):
tester('ntpath.abspath("C:\\")', "C:\\")
with support.temp_cwd(support.TESTFN) as cwd_dir: # bpo-31047
tester('ntpath.abspath("")', cwd_dir)
tester('ntpath.abspath(" ")', cwd_dir + "\\ ")
tester('ntpath.abspath("?")', cwd_dir + "\\?")
def test_relpath(self):
tester('ntpath.relpath("a")', 'a')

View File

@ -0,0 +1,2 @@
Fix ``ntpath.abspath`` for invalid paths on windows. Patch by Franz
Woellert.