|
9 | 9 | import pytest |
10 | 10 | from attrs import define |
11 | 11 |
|
12 | | -from cattrs import BaseConverter |
| 12 | +from cattrs import BaseConverter, ClassValidationError, Converter |
13 | 13 | from cattrs.strategies import configure_union_passthrough |
14 | 14 |
|
15 | 15 |
|
@@ -109,3 +109,35 @@ class B: |
109 | 109 |
|
110 | 110 | with pytest.raises(TypeError): |
111 | 111 | converter.structure((), union) |
| 112 | + |
| 113 | + |
| 114 | +def test_int_is_float(converter: BaseConverter) -> None: |
| 115 | + """By default, ints can also be accepted when floats are. |
| 116 | +
|
| 117 | + When the strategy gets initialized with both ints and floats, |
| 118 | + unions that only contain floats also accept ints by default. |
| 119 | + """ |
| 120 | + |
| 121 | + configure_union_passthrough(Union[int, float, str, None], converter) |
| 122 | + |
| 123 | + assert converter.structure(1, Union[float, str, None]) == 1 |
| 124 | + assert isinstance(converter.structure(1, Union[float, str, None]), int) |
| 125 | + |
| 126 | + |
| 127 | +def test_int_is_not_float(converter: BaseConverter) -> None: |
| 128 | + """Ints can be configured to be separate.""" |
| 129 | + |
| 130 | + @define |
| 131 | + class A: |
| 132 | + a: int |
| 133 | + |
| 134 | + configure_union_passthrough( |
| 135 | + Union[int, float], converter, accept_ints_as_floats=False |
| 136 | + ) |
| 137 | + |
| 138 | + with pytest.raises( |
| 139 | + ClassValidationError |
| 140 | + if isinstance(converter, Converter) and converter.detailed_validation |
| 141 | + else TypeError |
| 142 | + ): |
| 143 | + converter.structure(1, Union[float, A]) |
0 commit comments