Skip to content

Commit 92ea52d

Browse files
authored
Merge pull request #5811 from TaykYoku/72_JEncode
[v7r2] JEncode bytes
2 parents dadfd14 + b13cca1 commit 92ea52d

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

src/DIRAC/Core/Utilities/JEncode.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
from __future__ import division
55
from __future__ import print_function
66

7+
import six
8+
from base64 import b64encode, b64decode
79
import datetime
810
import json
911

@@ -105,7 +107,10 @@ def default(self, obj): # pylint: disable=method-hidden
105107
# if the object inherits from JSJerializable, try to serialize it
106108
elif isinstance(obj, JSerializable):
107109
return obj._toJSON() # pylint: disable=protected-access
108-
110+
# if the object a bytes and we're running with Python 3, encode it
111+
# Python 2's string type is too ambiguous to handle this correctly.
112+
elif six.PY3 and isinstance(obj, bytes):
113+
return {"__dCls": "b64", "obj": b64encode(obj).decode()}
109114
# otherwise, let the parent do
110115
return super(DJSONEncoder, self).default(obj)
111116

@@ -140,6 +145,8 @@ def dict_to_object(dataDict):
140145
return datetime.datetime.strptime(dataDict["obj"], DATETIME_DEFAULT_FORMAT)
141146
elif className == "date":
142147
return datetime.datetime.strptime(dataDict["obj"], DATETIME_DEFAULT_DATE_FORMAT).date()
148+
elif className == "b64":
149+
return b64decode(dataDict["obj"])
143150
elif className:
144151
import importlib
145152

src/DIRAC/Core/Utilities/test/Test_Encode.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
from hypothesis import given, settings, HealthCheck
2323
from hypothesis.strategies import (
24+
binary,
2425
builds,
2526
integers,
2627
lists,
@@ -59,7 +60,7 @@
5960
"jsonTuple",
6061
"mixTuple",
6162
"mixTuple (DIRAC_USE_JSON_DECODE=Yes)",
62-
"mixTuple (DIRAC_USE_JSON_ENCODE=Yes",
63+
"mixTuple (DIRAC_USE_JSON_ENCODE=Yes)",
6364
)
6465

6566
enc_dec_imp_without_json = (disetTuple, (mixTuple, "No", "No"), (mixTuple, "Yes", "No"))
@@ -167,6 +168,14 @@ def enc_dec_without_json(request, monkeypatch):
167168
return base_enc_dec(request, monkeypatch)
168169

169170

171+
@settings(suppress_health_check=function_scoped)
172+
@given(data=binary())
173+
def test_BaseType_Bytes(data):
174+
"""Test for bytes. Test JEncode with python 3 ONLY, since DEncode distorts the result"""
175+
if six.PY3:
176+
agnosticTestFunction(jsonTuple, data)
177+
178+
170179
@settings(suppress_health_check=function_scoped)
171180
@given(data=booleans())
172181
def test_BaseType_Bool(enc_dec, data):

0 commit comments

Comments
 (0)