Merge "[db] Fix serializer to work with ordered data"
This commit is contained in:
commit
e253c03880
@ -388,7 +388,7 @@ def pretty_float_formatter(field, ndigits=None):
|
||||
:returns: field formatter function
|
||||
"""
|
||||
def _formatter(obj):
|
||||
value = obj[field] if type(obj) == dict else getattr(obj, field)
|
||||
value = obj[field] if isinstance(obj, dict) else getattr(obj, field)
|
||||
if type(value) in (int, float):
|
||||
if ndigits:
|
||||
return round(value, ndigits)
|
||||
|
@ -61,7 +61,8 @@ def serialize_data(data):
|
||||
)):
|
||||
return data
|
||||
if isinstance(data, dict):
|
||||
return {k: serialize_data(v) for k, v in data.items()}
|
||||
return collections.OrderedDict((k, serialize_data(v))
|
||||
for k, v in data.items())
|
||||
if isinstance(data, (list, tuple)):
|
||||
return [serialize_data(i) for i in data]
|
||||
if hasattr(data, "_as_dict"):
|
||||
|
@ -15,6 +15,7 @@
|
||||
# NOTE(andreykurilin): most tests for sqlalchemy api is merged with db_api
|
||||
# tests. Hope, it will be fixed someday.
|
||||
|
||||
import collections
|
||||
import datetime as dt
|
||||
|
||||
import ddt
|
||||
@ -62,6 +63,13 @@ class SerializeTestCase(test.DBTestCase):
|
||||
results = fake_method()
|
||||
self.assertEqual(serialized, results)
|
||||
|
||||
def test_serialize_ordered_dict(self):
|
||||
data = collections.OrderedDict([(1, 2), ("foo", "bar"), (2, 3)])
|
||||
serialized = db_api.serialize_data(data)
|
||||
self.assertIsInstance(serialized, collections.OrderedDict)
|
||||
self.assertEqual([1, "foo", 2], list(serialized.keys()))
|
||||
self.assertEqual([2, "bar", 3], list(serialized.values()))
|
||||
|
||||
def test_serialize_value_error(self):
|
||||
@db_api.serialize
|
||||
def fake_method():
|
||||
|
Loading…
x
Reference in New Issue
Block a user