Skip to content

Commit

Permalink
fix: make Wildcard fields support Nested and List fields (fix #728) (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
ziirish authored and SteadBytes committed Oct 27, 2019
1 parent f21c261 commit 823f61e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
6 changes: 5 additions & 1 deletion flask_restplus/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,9 +281,11 @@ def format(self, value):
def is_attr(val):
return self.container.attribute and hasattr(val, self.container.attribute)

if value is None:
return []
return [
self.container.output(idx,
val if (isinstance(val, dict) or is_attr(val)) and not is_nested else value)
val if (isinstance(val, dict) or is_attr(val)) and not is_nested else value)
for idx, val in enumerate(value)
]

Expand Down Expand Up @@ -793,6 +795,8 @@ def output(self, key, obj, ordered=False):
return self.container.format(self.default)
return None

if isinstance(self.container, Nested):
return marshal(value, self.container.nested, skip_none=self.container.skip_none, ordered=ordered)
return self.container.format(value)

def schema(self):
Expand Down
31 changes: 31 additions & 0 deletions tests/test_marshalling.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,37 @@ def test_marshal(self):
assert not isinstance(output, OrderedDict)
assert output == {'foo': 'bar'}

def test_marshal_wildcard_nested(self):
nest = fields.Nested(OrderedDict([('thumbnail', fields.String), ('video', fields.String)]))
wild = fields.Wildcard(nest)
wildcard_fields = OrderedDict([('*', wild)])
model = OrderedDict([('preview', fields.Nested(wildcard_fields))])
sub_dict = OrderedDict([
('9:16', {'thumbnail': 24, 'video': 12}),
('16:9', {'thumbnail': 25, 'video': 11}),
('1:1', {'thumbnail': 26, 'video': 10})
])
marshal_dict = OrderedDict([('preview', sub_dict)])
output = marshal(marshal_dict, model)
assert output == {'preview': {'1:1': {'thumbnail': '26', 'video': '10'},
'16:9': {'thumbnail': '25', 'video': '11'},
'9:16': {'thumbnail': '24', 'video': '12'}}}

def test_marshal_wildcard_list(self):
wild = fields.Wildcard(fields.List(fields.String))
wildcard_fields = OrderedDict([('*', wild)])
model = OrderedDict([('preview', fields.Nested(wildcard_fields))])
sub_dict = OrderedDict([
('1:1', [1, 2, 3]),
('16:9', [4, 5, 6]),
('9:16', [7, 8, 9])
])
marshal_dict = OrderedDict([('preview', sub_dict)])
output = marshal(marshal_dict, model)
assert output == {'preview': {'9:16': ['7', '8', '9'],
'16:9': ['4', '5', '6'],
'1:1': ['1', '2', '3']}}

def test_marshal_with_envelope(self):
model = OrderedDict([('foo', fields.Raw)])
marshal_dict = OrderedDict([('foo', 'bar'), ('bat', 'baz')])
Expand Down

0 comments on commit 823f61e

Please sign in to comment.