|
| 1 | +import pytest |
| 2 | +from pydantic import ValidationError |
| 3 | + |
| 4 | +from app.schemas.simulation_input import RVConfig |
| 5 | + |
| 6 | +# --------------------------------------------------------------------------- # |
| 7 | +# Positive cases # |
| 8 | +# --------------------------------------------------------------------------- # |
| 9 | + |
| 10 | +def test_normal_sets_variance_to_mean() -> None: |
| 11 | + """When distribution='normal' and variance is omitted, variance == mean.""" |
| 12 | + cfg = RVConfig(mean=10, distribution="normal") |
| 13 | + assert cfg.variance == 10.0 |
| 14 | + |
| 15 | + |
| 16 | +def test_poisson_keeps_variance_none() -> None: |
| 17 | + """When distribution='poisson' and variance is omitted, variance stays None.""" |
| 18 | + cfg = RVConfig(mean=5, distribution="poisson") |
| 19 | + assert cfg.variance is None |
| 20 | + |
| 21 | + |
| 22 | +def test_explicit_variance_is_preserved() -> None: |
| 23 | + """If the user supplies variance explicitly, it is preserved unchanged.""" |
| 24 | + cfg = RVConfig(mean=8, distribution="normal", variance=4) |
| 25 | + assert cfg.variance == 4.0 |
| 26 | + |
| 27 | + |
| 28 | +# --------------------------------------------------------------------------- # |
| 29 | +# Validation errors # |
| 30 | +# --------------------------------------------------------------------------- # |
| 31 | + |
| 32 | +def test_mean_must_be_numeric() -> None: |
| 33 | + """A non-numeric mean raises a ValidationError with our custom message.""" |
| 34 | + with pytest.raises(ValidationError) as excinfo: |
| 35 | + RVConfig(mean="not a number", distribution="poisson") |
| 36 | + |
| 37 | + # Check that at least one error refers to the 'mean' field |
| 38 | + assert any(err["loc"] == ("mean",) for err in excinfo.value.errors()) |
| 39 | + assert "mean must be a number" in excinfo.value.errors()[0]["msg"] |
| 40 | + |
| 41 | + |
| 42 | +def test_missing_mean_field() -> None: |
| 43 | + """Omitting the mean field raises a 'field required' ValidationError.""" |
| 44 | + with pytest.raises(ValidationError) as excinfo: |
| 45 | + # Using model_validate avoids the constructor signature check |
| 46 | + RVConfig.model_validate({"distribution": "normal"}) |
| 47 | + |
| 48 | + assert any( |
| 49 | + err["loc"] == ("mean",) and err["type"] == "missing" |
| 50 | + for err in excinfo.value.errors() |
| 51 | + ) |
0 commit comments