#15180: Clarify posixpath.join() error message when mixing str & bytes

This commit is contained in:
Hynek Schlawack 2012-07-15 16:21:30 +02:00
parent a3d1cac4b2
commit 4774946c3b
3 changed files with 24 additions and 8 deletions

View File

@ -74,13 +74,20 @@ def join(a, *p):
will be discarded.""" will be discarded."""
sep = _get_sep(a) sep = _get_sep(a)
path = a path = a
for b in p: try:
if b.startswith(sep): for b in p:
path = b if b.startswith(sep):
elif not path or path.endswith(sep): path = b
path += b elif not path or path.endswith(sep):
path += b
else:
path += sep + b
except TypeError:
strs = [isinstance(s, str) for s in (a, ) + p]
if any(strs) and not all(strs):
raise TypeError("Can't mix strings and bytes in path components.")
else: else:
path += sep + b raise
return path return path

View File

@ -56,8 +56,15 @@ class PosixPathTest(unittest.TestCase):
self.assertEqual(posixpath.join(b"/foo/", b"bar/", b"baz/"), self.assertEqual(posixpath.join(b"/foo/", b"bar/", b"baz/"),
b"/foo/bar/baz/") b"/foo/bar/baz/")
self.assertRaises(TypeError, posixpath.join, b"bytes", "str") with self.assertRaises(TypeError) as e:
self.assertRaises(TypeError, posixpath.join, "str", b"bytes") posixpath.join(b'bytes', 'str')
self.assertIn("Can't mix strings and bytes", e.args[0])
with self.assertRaises(TypeError) as e:
posixpath.join('str', b'bytes')
self.assertIn("Can't mix strings and bytes", e.args[0])
with self.assertRaises(TypeError) as e:
posixpath.join('str', bytearray(b'bytes'))
self.assertIn("Can't mix strings and bytes", e.args[0])
def test_split(self): def test_split(self):
self.assertEqual(posixpath.split("/foo/bar"), ("/foo", "bar")) self.assertEqual(posixpath.split("/foo/bar"), ("/foo", "bar"))

View File

@ -87,6 +87,8 @@ Core and Builtins
Library Library
------- -------
- Issue #15180: Clarify posixpath.join() error message when mixing str & bytes
- Issue #15230: runpy.run_path now correctly sets __package__ as described - Issue #15230: runpy.run_path now correctly sets __package__ as described
in the documentation in the documentation