Merge pull request #19072 from shadinaif/fix_lazy_text_with_json_dumps

Fix exceptions raised when a lazy text is used in json dump
This commit is contained in:
Ned Batchelder
2018-11-05 06:20:05 -05:00
committed by GitHub
21 changed files with 107 additions and 48 deletions

View File

@@ -5,7 +5,6 @@ that are stored in a database an accessible using their Location as an identifie
import logging
import re
import json
import datetime
from pytz import UTC
@@ -22,11 +21,15 @@ from xblock.plugin import default_select
from .exceptions import InvalidLocationError, InsufficientSpecificationError
from xmodule.errortracker import make_error_tracker
from xmodule.assetstore import AssetMetadata
from opaque_keys.edx.keys import CourseKey, UsageKey, AssetKey
from opaque_keys.edx.keys import CourseKey, AssetKey
from opaque_keys.edx.locations import Location # For import backwards compatibility
from xblock.runtime import Mixologist
from xblock.core import XBlock
# The below import is not used within this module, but ir is still needed becuase
# other modules are imorting EdxJSONEncoder from here
from openedx.core.lib.json_utils import EdxJSONEncoder # pylint: disable=unused-import
log = logging.getLogger('edx.modulestore')
new_contract('CourseKey', CourseKey)
@@ -1430,25 +1433,3 @@ def prefer_xmodules(identifier, entry_points):
return default_select(identifier, from_xmodule)
else:
return default_select(identifier, entry_points)
class EdxJSONEncoder(json.JSONEncoder):
"""
Custom JSONEncoder that handles `Location` and `datetime.datetime` objects.
`Location`s are encoded as their url string form, and `datetime`s as
ISO date strings
"""
def default(self, obj):
if isinstance(obj, (CourseKey, UsageKey)):
return unicode(obj)
elif isinstance(obj, datetime.datetime):
if obj.tzinfo is not None:
if obj.utcoffset() is None:
return obj.isoformat() + 'Z'
else:
return obj.isoformat()
else:
return obj.isoformat()
else:
return super(EdxJSONEncoder, self).default(obj)

View File

@@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
"""
Tests of XML export
"""
@@ -10,6 +11,7 @@ import shutil
import unittest
from datetime import datetime, timedelta, tzinfo
from django.utils.translation import ugettext_lazy
from fs.osfs import OSFS
from path import Path as path
from six import text_type
@@ -212,3 +214,17 @@ class TestEdxJsonEncoder(unittest.TestCase):
with self.assertRaises(TypeError):
self.encoder.default({})
def test_encode_unicode_lazy_text(self):
"""
Verify that the encoding is functioning fine with lazy text
"""
# Initializing a lazy text object with Unicode
unicode_text = u"Your 𝓟𝓵𝓪𝓽𝓯𝓸𝓻𝓶 Name Here"
lazy_text = ugettext_lazy(unicode_text)
self.assertEquals(
unicode_text,
self.encoder.default(lazy_text)
)