Skip to content

Commit 14e5ef7

Browse files
committed
Add a test
1 parent 478df66 commit 14e5ef7

File tree

2 files changed

+34
-5
lines changed

2 files changed

+34
-5
lines changed

src/cattrs/gen/__init__.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -184,14 +184,17 @@ def make_dict_unstructure_fn_from_attrs(
184184
def_str = def_name
185185

186186
c = a.converter
187-
if isinstance(c, Converter):
187+
if c is not None:
188188
conv_name = f"__c_conv_{attr_name}"
189189
globs[conv_name] = c
190190
internal_arg_parts[conv_name] = c
191-
field_name = f"__c_field_{attr_name}"
192-
globs[field_name] = a
193-
internal_arg_parts[field_name] = a
194-
def_str = f"{conv_name}({def_str}, instance, {field_name})"
191+
if isinstance(c, Converter):
192+
field_name = f"__c_field_{attr_name}"
193+
globs[field_name] = a
194+
internal_arg_parts[field_name] = a
195+
def_str = f"{conv_name}({def_str}, instance, {field_name})"
196+
else:
197+
def_str = f"{conv_name}({def_str})"
195198

196199
lines.append(f" if instance.{attr_name} != {def_str}:")
197200
lines.append(f" res['{kn}'] = {invoke}")

tests/test_converter.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
Union,
1717
)
1818

19+
import attrs
1920
import pytest
2021
from attrs import Factory, define, field, fields, has, make_class
2122
from hypothesis import assume, given
@@ -339,6 +340,31 @@ class C:
339340
assert inst == converter.structure(unstructured, C)
340341

341342

343+
@given(simple_typed_classes(defaults="always", allow_nan=False))
344+
def test_omit_default_with_attrs_converter_roundtrip(cl_and_vals):
345+
"""
346+
Omit default with attrs' converter on the converter works.
347+
"""
348+
converter = Converter(omit_if_default=True)
349+
cl, vals, kwargs = cl_and_vals
350+
351+
@define
352+
class C:
353+
a1: int = field(default="1", converter=int)
354+
a2: int = field(default="1", converter=attrs.Converter(int))
355+
c: cl = Factory(lambda: cl(*vals, **kwargs))
356+
357+
inst = C()
358+
unstructured = converter.unstructure(inst)
359+
assert unstructured == {}
360+
assert inst == converter.structure(unstructured, C)
361+
362+
inst = C(0, 0)
363+
unstructured = converter.unstructure(inst)
364+
assert unstructured == {"a1": 0, "a2": 0}
365+
assert inst == converter.structure(unstructured, C)
366+
367+
342368
def test_dict_roundtrip_with_alias():
343369
"""
344370
A class with an aliased attribute can be unstructured and structured.

0 commit comments

Comments
 (0)