Skip to content

Commit

Permalink
Change how we handle defaults.
Browse files Browse the repository at this point in the history
  • Loading branch information
jnb committed Apr 19, 2017
1 parent 5d9c7ef commit f65fd80
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
10 changes: 3 additions & 7 deletions bravado_core/unmarshal.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,18 +126,12 @@ def unmarshal_object(swagger_spec, object_spec, object_value):
type(object_value), object_value))

object_spec = deref(object_spec)
required_fields = object_spec.get('required', [])

result = {}
for k, v in iteritems(object_value):
prop_spec = get_spec_for_prop(
swagger_spec, object_spec, object_value, k)
if v is None and k not in required_fields and prop_spec:
if schema.has_default(swagger_spec, prop_spec):
result[k] = schema.get_default(swagger_spec, prop_spec)
else:
result[k] = None
elif prop_spec:
if prop_spec:
result[k] = unmarshal_schema_object(swagger_spec, prop_spec, v)
else:
# Don't marshal when a spec is not available - just pass through
Expand All @@ -147,6 +141,8 @@ def unmarshal_object(swagger_spec, object_spec, object_value):
for prop_name, prop_spec in iteritems(properties):
if prop_name not in result and swagger_spec.config['include_missing_properties']:
result[prop_name] = None
if schema.has_default(swagger_spec, prop_spec):
result[prop_name] = schema.get_default(swagger_spec, prop_spec)

return result

Expand Down
17 changes: 15 additions & 2 deletions tests/unmarshal/unmarshal_object_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,17 @@ def test_with_properties(empty_swagger_spec, address_spec, address, street_type,
assert expected_address == result


def test_missing_with_default(empty_swagger_spec, address_spec, address):
del address['street_type']
expected_address = {
'number': 1600,
'street_name': u'Ümlaut',
'street_type': 'Street',
}
result = unmarshal_object(empty_swagger_spec, address_spec, address)
assert expected_address == result


def test_with_array(empty_swagger_spec, address_spec):
tags_spec = {
'type': 'array',
Expand Down Expand Up @@ -459,8 +470,10 @@ def test_non_required_none_value(empty_swagger_spec, property_type):
nullable=False,
property_type=property_type)
value = {'x': None}
result = unmarshal_object(empty_swagger_spec, content_spec, value)
assert result == {'x': None}
# This should fail because the field is not nullable
with pytest.raises(SwaggerMappingError) as excinfo:
unmarshal_object(empty_swagger_spec, content_spec, value)
assert 'is a required value' in str(excinfo.value)


def test_unmarshal_object_polymorphic_specs(polymorphic_spec):
Expand Down

0 comments on commit f65fd80

Please sign in to comment.