Issue #22034: Improve handling of wrong argument types in posixpath.join().

This commit is contained in:
Serhiy Storchaka 2014-08-24 12:23:36 +03:00
commit 1fa36268cf
2 changed files with 20 additions and 21 deletions

View File

@ -82,14 +82,13 @@ def join(a, *p):
path += b path += b
else: else:
path += sep + b path += sep + b
except TypeError: except (TypeError, AttributeError):
valid_types = all(isinstance(s, (str, bytes, bytearray)) for s in (a,) + p:
for s in (a, ) + p) if not isinstance(s, (str, bytes)):
if valid_types: raise TypeError('join() argument must be str or bytes, not %r' %
# Must have a mixture of text and binary data s.__class__.__name__) from None
raise TypeError("Can't mix strings and bytes in path " # Must have a mixture of text and binary data
"components.") from None raise TypeError("Can't mix strings and bytes in path components") from None
raise
return path return path

View File

@ -57,21 +57,21 @@ 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/")
def check_error_msg(list_of_args, msg): def test_join_errors(self):
"""Check posixpath.join raises friendly TypeErrors.""" # Check posixpath.join raises friendly TypeErrors.
for args in (item for perm in list_of_args errmsg = "Can't mix strings and bytes in path components"
for item in itertools.permutations(perm)): with self.assertRaisesRegex(TypeError, errmsg):
with self.assertRaises(TypeError) as cm: posixpath.join(b'bytes', 'str')
posixpath.join(*args) with self.assertRaisesRegex(TypeError, errmsg):
self.assertEqual(msg, cm.exception.args[0]) posixpath.join('str', b'bytes')
check_error_msg([[b'bytes', 'str'], [bytearray(b'bytes'), 'str']],
"Can't mix strings and bytes in path components.")
# regression, see #15377 # regression, see #15377
with self.assertRaises(TypeError) as cm: errmsg = r'join\(\) argument must be str or bytes, not %r'
with self.assertRaisesRegex(TypeError, errmsg % 'NoneType'):
posixpath.join(None, 'str') posixpath.join(None, 'str')
self.assertNotEqual("Can't mix strings and bytes in path components.", with self.assertRaisesRegex(TypeError, errmsg % 'NoneType'):
cm.exception.args[0]) posixpath.join('str', None)
with self.assertRaisesRegex(TypeError, errmsg % 'bytearray'):
posixpath.join(bytearray(b'foo'), bytearray(b'bar'))
def test_split(self): def test_split(self):
self.assertEqual(posixpath.split("/foo/bar"), ("/foo", "bar")) self.assertEqual(posixpath.split("/foo/bar"), ("/foo", "bar"))