Anonymous committed f92616f

On second thought: "Errors should never pass silently", so barf when a
string contains control chars that are illegal for XML

Comments (0)

Files changed (2)


-# Regex to strip all control chars, but for \t \n and \r
-_controlStripper = re.compile(
+# Regex to find any control chars, except for \t \n and \r
+_controlCharPat = re.compile(
 def _escapeAndEncode(text):
+    m =
+    if m is not None:
+        raise ValueError("strings can't contains control characters; "
+                         "use plistlib.Data instead")
     text = text.replace("\r\n", "\n")       # convert DOS line endings
     text = text.replace("\r", "\n")         # convert Mac line endings
     text = text.replace("&", "&")       # escape '&'
     text = text.replace("<", "&lt;")        # escape '<'
     text = text.replace(">", "&gt;")        # escape '>'
-    text = _controlStripper.sub("?", text)  # replace control chars with '?'
     return text.encode("utf-8")             # encode as UTF-8


         self.assertEqual(dict(pl), dict(pl2))
     def test_controlcharacters(self):
-        # chars in the range 0..31 are replaced by '?', except for
-        # \r, \n and \t since they aren't legal XML characters
-        testString = "".join([chr(i) for i in range(32)])
-        expectedResult = '?????????\t\n??\n??????????????????'
-        xml = plistlib.writePlistToString(testString)
-        result = plistlib.readPlistFromString(xml)
-        self.assertEqual(result, expectedResult)
+        for i in range(128):
+            c = chr(i)
+            testString = "string containing %s" % c
+            if i >= 32 or c in "\r\n\t":
+                # \r, \n and \t are the only legal control chars in XML
+                plistlib.writePlistToString(testString)
+            else:
+                self.assertRaises(ValueError,
+                                  plistlib.writePlistToString,
+                                  testString)
     def test_nondictroot(self):
         test1 = "abc"
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.