Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix structure for union of attr classes with default values #108

Merged
merged 6 commits into from
Nov 18, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@
History
=======

1.1.2 (unrelased)
-----------------
* Disambigualation do not pick non required field.
(`#108 <https://github.com/Tinche/cattrs/pull/108>`_)

1.1.1 (2020-10-30)
------------------
* Add metadata for supported Python versions.
Expand Down
11 changes: 9 additions & 2 deletions src/cattr/disambiguators.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
Type,
)

from attr import fields
from attr import fields, NOTHING

from cattr._compat import get_origin

Expand Down Expand Up @@ -42,7 +42,14 @@ def create_uniq_field_dis_func(*classes: Type) -> Callable:
if not uniq:
m = "{} has no usable unique attributes.".format(cl)
raise ValueError(m)
uniq_attrs_dict[next(iter(uniq))] = cl
# We need a unique attribute with no default.
cl_fields = fields(get_origin(cl) or cl)
for attr_name in uniq:
if getattr(cl_fields, attr_name).default is NOTHING:
break
else:
raise ValueError(f"{cl} has no usable non-default attributes.")
uniq_attrs_dict[attr_name] = cl
else:
fallback = cl

Expand Down
26 changes: 24 additions & 2 deletions tests/test_disambigutors.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
"""Tests for auto-disambiguators."""
from typing import Any

import attr
import pytest

from hypothesis import assume, given
from attr import NOTHING
from hypothesis import HealthCheck, assume, given, settings

from cattr.disambiguators import create_uniq_field_dis_func

Expand Down Expand Up @@ -40,6 +43,18 @@ class D(object):
# No unique fields on either class.
create_uniq_field_dis_func(C, D)

@attr.s
class E:
pass

@attr.s
class F:
b = attr.ib(default=Any)

with pytest.raises(ValueError):
# no usable non-default attributes
create_uniq_field_dis_func(E, F)


@given(simple_classes(defaults=False))
def test_fallback(cl_and_vals):
Expand All @@ -63,9 +78,12 @@ class A(object):
fn({"xyz": 1}) is A # Uses the fallback.


@settings(
suppress_health_check=[HealthCheck.filter_too_much, HealthCheck.too_slow]
)
@given(simple_classes(), simple_classes())
def test_disambiguation(cl_and_vals_a, cl_and_vals_b):
"""Disambiguation should work when there are unique fields."""
"""Disambiguation should work when there are unique required fields."""
cl_a, vals_a = cl_and_vals_a
cl_b, vals_b = cl_and_vals_b

Expand All @@ -76,6 +94,10 @@ def test_disambiguation(cl_and_vals_a, cl_and_vals_b):
assume(len(req_b))

assume((req_a - req_b) or (req_b - req_a))
for attr_name in req_a - req_b:
assume(getattr(attr.fields(cl_a), attr_name).default is NOTHING)
for attr_name in req_b - req_a:
assume(getattr(attr.fields(cl_b), attr_name).default is NOTHING)

fn = create_uniq_field_dis_func(cl_a, cl_b)

Expand Down
19 changes: 19 additions & 0 deletions tests/test_structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
)
from pytest import raises

import attr
from cattr import Converter
from cattr._compat import is_bare, is_union_type
from cattr.converters import NoneType
Expand Down Expand Up @@ -351,3 +352,21 @@ class Bar(Foo):
converter.register_structure_hook(Bar, lambda obj, cls: cls("bar"))
assert converter.structure(None, Foo).value == "foo"
assert converter.structure(None, Bar).value == "bar"


def test_structure_union_edge_case():
converter = Converter()

@attr.s(auto_attribs=True)
class A:
a1: Any
a2: Optional[Any] = None

@attr.s(auto_attribs=True)
class B:
b1: Any
b2: Optional[Any] = None

assert converter.structure(
[{"a1": "foo"}, {"b1": "bar"}], List[Union[A, B]]
) == [A("foo"), B("bar")]