Specify namedtuple_as_object=False when using simplejson

This makes namedtuple serialization consistent with non simplejson case.

Closes-Bug: #1356173
Change-Id: I9dd879914c7cb226c71e856914536318b416e488
This commit is contained in:
YAMAMOTO Takashi 2014-08-14 02:18:19 +09:00
parent af8fafcf34
commit c5b869462f
2 changed files with 23 additions and 2 deletions

View File

@ -38,11 +38,13 @@ import inspect
import itertools
import sys
is_simplejson = False
if sys.version_info < (2, 7):
# On Python <= 2.6, json module is not C boosted, so try to use
# simplejson module if available
try:
import simplejson as json
is_simplejson = True
except ImportError:
import json
else:
@ -165,10 +167,14 @@ def to_primitive(value, convert_instances=False, convert_datetime=True,
def dumps(value, default=to_primitive, **kwargs):
if is_simplejson:
kwargs['namedtuple_as_object'] = False
return json.dumps(value, default=default, **kwargs)
def dump(obj, fp, *args, **kwargs):
if is_simplejson:
kwargs['namedtuple_as_object'] = False
return json.dump(obj, fp, *args, **kwargs)

View File

@ -13,6 +13,7 @@
# License for the specific language governing permissions and limitations
# under the License.
import collections
import datetime
import json
@ -33,8 +34,9 @@ class JSONUtilsTestMixin(object):
def setUp(self):
super(JSONUtilsTestMixin, self).setUp()
self.json_patcher = mock.patch.object(
jsonutils, 'json', self.json_impl)
self.json_patcher = mock.patch.multiple(
jsonutils, json=self.json_impl,
is_simplejson=self.json_impl is simplejson)
self.json_impl_mock = self.json_patcher.start()
def tearDown(self):
@ -44,6 +46,10 @@ class JSONUtilsTestMixin(object):
def test_dumps(self):
self.assertEqual('{"a": "b"}', jsonutils.dumps({'a': 'b'}))
def test_dumps_namedtuple(self):
n = collections.namedtuple("foo", "bar baz")(1, 2)
self.assertEqual('[1, 2]', jsonutils.dumps(n))
def test_dump(self):
expected = '{"a": "b"}'
json_dict = {'a': 'b'}
@ -53,6 +59,15 @@ class JSONUtilsTestMixin(object):
self.assertEqual(expected, fp.getvalue())
def test_dump_namedtuple(self):
expected = '[1, 2]'
json_dict = collections.namedtuple("foo", "bar baz")(1, 2)
fp = six.StringIO()
jsonutils.dump(json_dict, fp)
self.assertEqual(expected, fp.getvalue())
def test_loads(self):
self.assertEqual({'a': 'b'}, jsonutils.loads('{"a": "b"}'))