Skip to content

Commit

Permalink
Merge pull request #1 from shwetas1205/master
Browse files Browse the repository at this point in the history
Respecting defaults from attr class
  • Loading branch information
toumorokoshi authored Oct 31, 2017
2 parents beafd77 + e6136a6 commit 0ccfc7e
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
4 changes: 2 additions & 2 deletions cattr/converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,10 +283,10 @@ def _structure_attr_from_dict(self, a, name, mapping):
type_ = a.metadata.get(TYPE_METADATA_KEY)
if type_ is None:
# No type.
return mapping[name]
return mapping.get(name, a.default)
if _is_union_type(type_):
# This is a union.
val = mapping.get(name, NOTHING)
val = mapping.get(name, a.default)
if NoneType in type_.__args__ and val is NOTHING:
return None
return self._structure_union(val, type_)
Expand Down
14 changes: 12 additions & 2 deletions tests/test_structure_attrs.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
"""Loading of attrs classes."""
from attr import asdict, astuple, fields
from attr import asdict, astuple, fields, make_class
from hypothesis import assume, given

from typing import Union

from . import simple_classes
from . import simple_classes, simple_attrs


@given(simple_classes())
Expand All @@ -20,6 +20,16 @@ def test_structure_simple_from_dict(converter, cl_and_vals):
assert obj == loaded


@given(simple_attrs(defaults=True))
def test_structure_simple_from_dict_default(converter, cl_and_vals):
"""Test structuring non-nested attrs classes with default value."""
a, _ = cl_and_vals
cl = make_class("HypClass", {"a": a})
obj = cl()
loaded = converter.structure({}, cl)
assert obj == loaded


@given(simple_classes())
def test_roundtrip(converter, cl_and_vals):
# type: (Converter, Any) -> None
Expand Down

0 comments on commit 0ccfc7e

Please sign in to comment.