|
2 | 2 |
|
3 | 3 | from enum import Enum |
4 | 4 |
|
| 5 | +import attrs |
5 | 6 | from hypothesis import given |
6 | 7 | from hypothesis.strategies import data, sampled_from |
7 | 8 | from pytest import raises |
@@ -68,3 +69,56 @@ def test_structure_complex_enum() -> None: |
68 | 69 | assert converter.structure(0, SimpleEnum) == SimpleEnum.A |
69 | 70 | assert converter.structure("E", SimpleEnumWithTypeHint) == SimpleEnumWithTypeHint.E |
70 | 71 | assert converter.structure((0, "D"), ComplexEnum) == ComplexEnum.AD |
| 72 | + |
| 73 | + |
| 74 | +def test_unstructure_enum_misuse_raises_clear_error() -> None: |
| 75 | + """Regression test for #601. |
| 76 | +
|
| 77 | + Unstructuring a value that isn't actually an instance of the expected |
| 78 | + enum (e.g. because the enum's raw value was assigned directly to an |
| 79 | + attribute typed as the enum, bypassing any validation) must raise a |
| 80 | + clear, actionable ``TypeError`` instead of an opaque ``AttributeError`` |
| 81 | + like ``'str' object has no attribute 'value'``. |
| 82 | + """ |
| 83 | + converter = BaseConverter() |
| 84 | + |
| 85 | + with raises(TypeError) as exc_info: |
| 86 | + converter.unstructure("A", unstructure_as=SimpleEnum) |
| 87 | + |
| 88 | + msg = str(exc_info.value) |
| 89 | + assert "SimpleEnum" in msg |
| 90 | + assert "'A'" in msg |
| 91 | + |
| 92 | + |
| 93 | +def test_unstructure_typed_enum_misuse_raises_clear_error() -> None: |
| 94 | + """Regression test for #601, typed-enum branch (has `_value_`).""" |
| 95 | + converter = BaseConverter() |
| 96 | + |
| 97 | + with raises(TypeError) as exc_info: |
| 98 | + converter.unstructure("D", unstructure_as=SimpleEnumWithTypeHint) |
| 99 | + |
| 100 | + msg = str(exc_info.value) |
| 101 | + assert "SimpleEnumWithTypeHint" in msg |
| 102 | + assert "'D'" in msg |
| 103 | + |
| 104 | + |
| 105 | +def test_unstructure_attrs_class_with_misused_enum_field() -> None: |
| 106 | + """End-to-end regression test for #601, matching the original report. |
| 107 | +
|
| 108 | + Assigning a plain string default (instead of an actual enum member) to |
| 109 | + an attrs attribute typed as an ``Enum`` used to blow up with an |
| 110 | + unhelpful ``AttributeError`` deep inside generated code. |
| 111 | + """ |
| 112 | + |
| 113 | + @attrs.define |
| 114 | + class Site: |
| 115 | + flavor: SimpleEnumWithTypeHint = "D" # intentionally not an enum member |
| 116 | + |
| 117 | + converter = BaseConverter() |
| 118 | + |
| 119 | + with raises(TypeError) as exc_info: |
| 120 | + converter.unstructure(Site()) |
| 121 | + |
| 122 | + msg = str(exc_info.value) |
| 123 | + assert "SimpleEnumWithTypeHint" in msg |
| 124 | + assert "'D'" in msg |
0 commit comments