1
0
mirror of https://github.com/openSUSE/osc.git synced 2024-09-20 01:06:17 +02:00

_private.api: Add xml_escape() function

This commit is contained in:
Daniel Mach 2023-03-03 13:12:21 +01:00
parent 13979f79d3
commit bacaa29a78
2 changed files with 48 additions and 0 deletions

View File

@ -4,6 +4,7 @@ and work with related XML data.
"""
import xml.sax.saxutils
from xml.etree import ElementTree as ET
@ -120,6 +121,19 @@ def write_xml_node_to_file(node, path, indent=True):
ET.ElementTree(node).write(path)
def xml_escape(string):
"""
Escape the string so it's safe to use in XML and xpath.
"""
entities = {
"\"": """,
"'": "'",
}
if isinstance(string, bytes):
return xml.sax.saxutils.escape(string.decode("utf-8"), entities=entities).encode("utf-8")
return xml.sax.saxutils.escape(string, entities=entities)
def xml_indent(root):
"""
Indent XML so it looks pretty after printing or saving to file.

View File

@ -0,0 +1,34 @@
import unittest
from osc._private.api import xml_escape
class TestXmlEscape(unittest.TestCase):
def test_lt(self):
actual = xml_escape("<")
expected = "&lt;"
self.assertEqual(actual, expected)
def test_gt(self):
actual = xml_escape(">")
expected = "&gt;"
self.assertEqual(actual, expected)
def test_apos(self):
actual = xml_escape("'")
expected = "&apos;"
self.assertEqual(actual, expected)
def test_quot(self):
actual = xml_escape("\"")
expected = "&quot;"
self.assertEqual(actual, expected)
def test_amp(self):
actual = xml_escape("&")
expected = "&amp;"
self.assertEqual(actual, expected)
if __name__ == "__main__":
unittest.main()