Skip to content

Commit

Permalink
Merge pull request #1258 from delocalizer/fix/base64Binary
Browse files Browse the repository at this point in the history
handle encoding of base64Binary Literals
  • Loading branch information
nicholascar authored May 15, 2021
2 parents 8d592a2 + 31a3d16 commit cb30688
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
7 changes: 5 additions & 2 deletions rdflib/term.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
import warnings
import math

import base64
import xml.dom.minidom

from datetime import date, time, datetime, timedelta
Expand All @@ -53,6 +52,7 @@
parse_duration,
duration_isoformat,
)
from base64 import b64decode, b64encode
from binascii import hexlify, unhexlify

import rdflib
Expand Down Expand Up @@ -1435,6 +1435,7 @@ def _parseBoolean(value):
_XSD_YEARMONTHDURATION = URIRef(_XSD_PFX + "yearMonthDuration")

_OWL_RATIONAL = URIRef("http://www.w3.org/2002/07/owl#rational")
_XSD_B64BINARY = URIRef(_XSD_PFX + "base64Binary")
_XSD_HEXBINARY = URIRef(_XSD_PFX + "hexBinary")
# TODO: gYearMonth, gYear, gMonthDay, gDay, gMonth

Expand Down Expand Up @@ -1559,6 +1560,8 @@ def _castPythonToLiteral(obj, datatype):
_SpecificPythonToXSDRules = [
((str, _XSD_HEXBINARY), hexlify),
((bytes, _XSD_HEXBINARY), hexlify),
((str, _XSD_B64BINARY), b64encode),
((bytes, _XSD_B64BINARY), b64encode),
]

XSDToPython = {
Expand Down Expand Up @@ -1593,7 +1596,7 @@ def _castPythonToLiteral(obj, datatype):
URIRef(_XSD_PFX + "unsignedByte"): int,
URIRef(_XSD_PFX + "float"): float,
URIRef(_XSD_PFX + "double"): float,
URIRef(_XSD_PFX + "base64Binary"): lambda s: base64.b64decode(s),
URIRef(_XSD_PFX + "base64Binary"): b64decode,
URIRef(_XSD_PFX + "anyURI"): None,
_RDF_XMLLITERAL: _parseXML,
_RDF_HTMLLITERAL: _parseHTML,
Expand Down
29 changes: 29 additions & 0 deletions test/test_b64_binary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# -*- coding: utf-8 -*-

import unittest
import base64
from rdflib import Literal, XSD


class B64BinaryTestCase(unittest.TestCase):

def test_unicode(self):
str1 = "Test utf-8 string éàë"
# u b64string
b64_str1 = base64.b64encode(str1.encode("utf-8")).decode()
l1 = Literal(b64_str1, datatype=XSD.base64Binary)
b_str1 = l1.toPython()
self.assertEqual(b_str1.decode("utf-8"), str1)
self.assertEqual(str(l1), b64_str1)

# b b64string
b64_str1b = base64.b64encode(str1.encode("utf-8"))
l1b = Literal(b64_str1b, datatype=XSD.base64Binary)
b_str1b = l1b.toPython()
self.assertEqual(b_str1, b_str1b)
self.assertEqual(b_str1b.decode("utf-8"), str1)
self.assertEqual(str(l1b), b64_str1)


if __name__ == "__main__":
unittest.main()

0 comments on commit cb30688

Please sign in to comment.