|
1 | 1 | """Test validation Failure.""" |
2 | 2 |
|
| 3 | +# standard |
| 4 | +from functools import partial |
| 5 | + |
| 6 | +# external |
| 7 | +import pytest |
| 8 | + |
3 | 9 | # local |
4 | | -from validators import between |
| 10 | +from validators import ValidationError, between, validator |
5 | 11 |
|
6 | 12 | failed_obj_repr = "ValidationError(func=between" |
7 | 13 |
|
@@ -31,3 +37,44 @@ def test_arguments_as_properties(self): |
31 | 37 | assert self.is_in_between.__dict__["value"] == 3 |
32 | 38 | assert self.is_in_between.__dict__["min_val"] == 4 |
33 | 39 | assert self.is_in_between.__dict__["max_val"] == 5 |
| 40 | + |
| 41 | + |
| 42 | +def test_partial_validation_error_representation(): |
| 43 | + """Validation errors support partial callables without a name attribute.""" |
| 44 | + |
| 45 | + def above(value: int, minimum: int) -> bool: |
| 46 | + return value > minimum |
| 47 | + |
| 48 | + check = validator(partial(above, minimum=3)) |
| 49 | + error = check(1) |
| 50 | + assert isinstance(error, ValidationError) |
| 51 | + assert repr(error) == "ValidationError(func=partial, args={'value': 1})" |
| 52 | + assert str(error) == repr(error) |
| 53 | + assert check(4) is True |
| 54 | + |
| 55 | + |
| 56 | +def test_callable_instance_validation_error_representation(): |
| 57 | + """Callable instance errors use their type name.""" |
| 58 | + |
| 59 | + class Positive: |
| 60 | + def __call__(self, *, value: int) -> bool: |
| 61 | + return value > 0 |
| 62 | + |
| 63 | + error = validator(Positive())(value=-1) |
| 64 | + assert isinstance(error, ValidationError) |
| 65 | + assert repr(error) == "ValidationError(func=Positive, args={'value': -1})" |
| 66 | + |
| 67 | + |
| 68 | +def test_builtin_validation_error_keeps_raw_arguments(): |
| 69 | + """An unavailable builtin signature must not hide its validation error.""" |
| 70 | + check = validator(int) |
| 71 | + error = check("invalid") |
| 72 | + assert isinstance(error, ValidationError) |
| 73 | + assert "func=int" in repr(error) |
| 74 | + assert error.__dict__["args"] == ("invalid",) |
| 75 | + assert error.__dict__["kwargs"] == {} |
| 76 | + assert "invalid literal" in error.reason |
| 77 | + assert check("42") is True |
| 78 | + |
| 79 | + with pytest.raises(ValidationError, match="func=int"): |
| 80 | + check("invalid", r_ve=True) |
0 commit comments