|
| 1 | +"""Annotation validation consumes the field owner's public value semantics.""" |
| 2 | +from dataclasses import dataclass |
| 3 | + |
| 4 | +import pytest |
| 5 | + |
| 6 | +from python_introspect import AnnotatedDataclassValidationMixin, validate_annotated_dataclass |
| 7 | + |
| 8 | + |
| 9 | +DEFERRED = object() |
| 10 | + |
| 11 | + |
| 12 | +@dataclass |
| 13 | +class EffectiveValue(AnnotatedDataclassValidationMixin): |
| 14 | + value: int |
| 15 | + |
| 16 | + def __getattribute__(self, name): |
| 17 | + value = object.__getattribute__(self, name) |
| 18 | + return 7 if name == "value" and value is DEFERRED else value |
| 19 | + |
| 20 | + |
| 21 | +def test_validation_reads_effective_values_without_rewriting_storage(): |
| 22 | + instance = EffectiveValue(DEFERRED) |
| 23 | + assert instance.value == 7 |
| 24 | + assert object.__getattribute__(instance, "value") is DEFERRED |
| 25 | + validate_annotated_dataclass(instance) |
| 26 | + |
| 27 | + |
| 28 | +@pytest.mark.parametrize("value", [None, "invalid", False]) |
| 29 | +def test_literal_null_and_invalid_concrete_values_are_not_masked(value): |
| 30 | + with pytest.raises(TypeError, match="must be int"): |
| 31 | + EffectiveValue(value) |
| 32 | + |
| 33 | + |
| 34 | +def test_field_descriptor_failure_propagates_its_original_identity(): |
| 35 | + failure = RuntimeError("field accessor failed") |
| 36 | + |
| 37 | + @dataclass |
| 38 | + class FailedRead(AnnotatedDataclassValidationMixin): |
| 39 | + value: int |
| 40 | + |
| 41 | + def __getattribute__(self, name): |
| 42 | + if name == "value": |
| 43 | + raise failure |
| 44 | + return object.__getattribute__(self, name) |
| 45 | + |
| 46 | + with pytest.raises(RuntimeError) as raised: |
| 47 | + FailedRead(3) |
| 48 | + assert raised.value is failure |
0 commit comments