#15180: Clarify posixpath.join() error message when mixing str & bytes
authorHynek Schlawack <hs@ox.cx>
Sun, 15 Jul 2012 14:21:30 +0000 (16:21 +0200)
committerHynek Schlawack <hs@ox.cx>
Sun, 15 Jul 2012 14:21:30 +0000 (16:21 +0200)
Lib/posixpath.py
Lib/test/test_posixpath.py
Misc/NEWS

index 9570a364a00398361a46aa5dbdcd6ab4fd660c09..84bcc1355f9aaf93e013179077c0300852bfaa29 100644 (file)
@@ -74,13 +74,20 @@ def join(a, *p):
     will be discarded."""
     sep = _get_sep(a)
     path = a
-    for b in p:
-        if b.startswith(sep):
-            path = b
-        elif not path or path.endswith(sep):
-            path +=  b
+    try:
+        for b in p:
+            if b.startswith(sep):
+                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:
-            path += sep + b
+            raise
     return path
 
 
index a7a3e4aa12d0ead217e7f3fdbc23724cdf39c78a..54de0cf51635ba0eb0a7323c9ff36f8a8ebce447 100644 (file)
@@ -56,8 +56,15 @@ class PosixPathTest(unittest.TestCase):
         self.assertEqual(posixpath.join(b"/foo/", b"bar/", b"baz/"),
                          b"/foo/bar/baz/")
 
-        self.assertRaises(TypeError, posixpath.join, b"bytes", "str")
-        self.assertRaises(TypeError, posixpath.join, "str", b"bytes")
+        with self.assertRaises(TypeError) as e:
+            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):
         self.assertEqual(posixpath.split("/foo/bar"), ("/foo", "bar"))
index 81665e39da05f3d2ce85bcc968759a1d7e951511..74e40387a2f93a417f102578bdb5a6ae042a7980 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -87,6 +87,8 @@ Core and Builtins
 Library
 -------
 
+- Issue #15180: Clarify posixpath.join() error message when mixing str & bytes
+
 - Issue #15230: runpy.run_path now correctly sets __package__ as described
   in the documentation