|
| 1 | +from typing import Any, Dict |
| 2 | + |
| 3 | +from guardrails.guard import Guard |
| 4 | +from guardrails.validator_base import ( |
| 5 | + FailResult, |
| 6 | + ValidationResult, |
| 7 | + Validator, |
| 8 | + register_validator, |
| 9 | +) |
| 10 | + |
| 11 | + |
| 12 | +@register_validator("failure", "string") |
| 13 | +class FailureValidator(Validator): |
| 14 | + def validate(self, value: Any, metadata: Dict[str, Any]) -> ValidationResult: |
| 15 | + return FailResult( |
| 16 | + error_message=("Failed cuz this is the failure validator"), |
| 17 | + fix_value="FIXED", |
| 18 | + ) |
| 19 | + |
| 20 | + |
| 21 | +# TODO: Add reask tests. Reask is fairly well covered through notebooks |
| 22 | +# but it's good to have it here too. |
| 23 | +def test_fix(): |
| 24 | + guard = Guard().use(FailureValidator, on_fail="fix") |
| 25 | + res = guard.parse("hi") |
| 26 | + assert res.validated_output == "FIXED" |
| 27 | + assert res.validation_passed # Should this even be true though? |
| 28 | + |
| 29 | + |
| 30 | +def test_default_noop(): |
| 31 | + guard = Guard().use(FailureValidator, on_fail="noop") |
| 32 | + res = guard.parse("hi") |
| 33 | + assert res.validated_output == "hi" |
| 34 | + assert not res.validation_passed |
| 35 | + |
| 36 | + |
| 37 | +def test_filter(): |
| 38 | + guard = Guard().use(FailureValidator, on_fail="filter") |
| 39 | + res = guard.parse("hi") |
| 40 | + assert res.validated_output is None |
| 41 | + assert not res.validation_passed |
| 42 | + |
| 43 | + |
| 44 | +def test_refrain(): |
| 45 | + guard = Guard().use(FailureValidator, on_fail="refrain") |
| 46 | + res = guard.parse("hi") |
| 47 | + assert res.validated_output is None |
| 48 | + assert not res.validation_passed |
| 49 | + |
| 50 | + |
| 51 | +def test_exception(): |
| 52 | + guard = Guard().use(FailureValidator, on_fail="exception") |
| 53 | + try: |
| 54 | + guard.parse("hi") |
| 55 | + except Exception as e: |
| 56 | + assert "Failed cuz this is the failure validator" in str(e) |
| 57 | + else: |
| 58 | + assert False, "Expected an exception" |
0 commit comments