From 15d920ef0c86a2d612ba6e74f8824026fc1d4ed6 Mon Sep 17 00:00:00 2001 From: VincentTran Date: Fri, 5 Jun 2020 12:12:30 +0800 Subject: [PATCH] add support for variant of dict and list set tuple --- nameko_django/VERSION | 2 +- nameko_django/serializer.py | 4 +++- tests/test_serializer.py | 26 +++++++++++++++++++++++++- 3 files changed, 29 insertions(+), 3 deletions(-) diff --git a/nameko_django/VERSION b/nameko_django/VERSION index 45a1b3f..781dcb0 100644 --- a/nameko_django/VERSION +++ b/nameko_django/VERSION @@ -1 +1 @@ -1.1.2 +1.1.3 diff --git a/nameko_django/serializer.py b/nameko_django/serializer.py index 311dd42..4ec0e13 100644 --- a/nameko_django/serializer.py +++ b/nameko_django/serializer.py @@ -65,7 +65,9 @@ def encode_nondefault_object(obj): return dict(obj.to_dict()) elif hasattr(obj, 'to_list') and callable(obj.to_list): return list(obj.to_list()) - elif isinstance(obj, tuple): # tuple will be treated as list + elif isinstance(obj, dict): # handle Box, defaultdict and all variant of dictionary + return dict(obj) + elif isinstance(obj, (tuple, set, list)): # tuple,set,list will be treated as list return list(obj) elif isinstance(obj, Enum) and hasattr(obj, 'value'): return obj.value diff --git a/tests/test_serializer.py b/tests/test_serializer.py index dfbccf2..e849c51 100644 --- a/tests/test_serializer.py +++ b/tests/test_serializer.py @@ -20,7 +20,7 @@ from datetime import datetime, date, time, timedelta from decimal import Decimal from aenum import Enum, IntEnum, Constant -from collections import namedtuple +from collections import namedtuple, defaultdict, OrderedDict from django.utils.timezone import FixedOffset from django.utils import timezone from nose import tools @@ -97,6 +97,30 @@ def test_simple_dictionary(): assert test_data == dec_data +def test_default_dictionary(): + test_data = defaultdict( + type='Mount', + modes=1, + rw=True, + level=1.5 + ) + enc_data = dumps(test_data) + dec_data = loads(enc_data) + assert dict(test_data) == dec_data + + +def test_orderred_dictionary(): + test_data = OrderedDict( + type='Mount', + rw=True, + level=1.5 + ) + test_data['modes'] = 1 + enc_data = dumps(test_data) + dec_data = loads(enc_data) + assert dict(test_data) == dec_data + + def test_simple_boxdict(): test_data = {'a': 1, 'b': 2, 'c': 3, 'd': '', 'e': {'e0': 0, 'e1': -1, 'ee': ['e', 'e']}} enc_data = dumps(Box(test_data))