|
| 1 | +import pytest |
| 2 | +from pydantic import BaseModel |
| 3 | + |
| 4 | +from common.types import Percent, PercentLimited |
| 5 | + |
| 6 | + |
| 7 | +class Model(BaseModel): |
| 8 | + p: Percent |
| 9 | + |
| 10 | + |
| 11 | +def test_non_negative_percent(): |
| 12 | + with pytest.raises(ValueError): |
| 13 | + Percent(-1.0) |
| 14 | + |
| 15 | + |
| 16 | +def test_incorrect_type(): |
| 17 | + with pytest.raises(ValueError): |
| 18 | + Percent("stuff") |
| 19 | + |
| 20 | + |
| 21 | +@pytest.mark.parametrize("input_value", [0.0, 1.0, 99.9, 100.0, 120.5, 50.123, 25]) |
| 22 | +def test_valid_percent(input_value: float): |
| 23 | + assert Percent(input_value) == input_value # type: ignore [arg-type] |
| 24 | + |
| 25 | + |
| 26 | +@pytest.mark.parametrize( |
| 27 | + "input_value,expected_decimal_fraction", |
| 28 | + [(0.0, 0.0), (99, 0.99), (51.234, 0.51234), (121.2, 1.212)], |
| 29 | +) |
| 30 | +def test_as_decimal_fraction(input_value: float, expected_decimal_fraction: float): |
| 31 | + assert Model(p=input_value).p.as_decimal_fraction() == expected_decimal_fraction # type: ignore [arg-type] # noqa: E501 |
| 32 | + |
| 33 | + |
| 34 | +class ModelLimited(BaseModel): |
| 35 | + p: PercentLimited |
| 36 | + |
| 37 | + |
| 38 | +@pytest.mark.parametrize("input_value", (-1, -0.01, 100.01)) |
| 39 | +def test_percent_limited_out_of_range(input_value: float): |
| 40 | + with pytest.raises(ValueError): |
| 41 | + PercentLimited(input_value) |
| 42 | + |
| 43 | + |
| 44 | +@pytest.mark.parametrize("input_value", [0.0, 1.0, 99.9, 100.0, 50.123, 25]) |
| 45 | +def test_valid_percent_limited(input_value: float): |
| 46 | + assert PercentLimited(input_value) == input_value # type: ignore [arg-type] |
| 47 | + |
| 48 | + |
| 49 | +@pytest.mark.parametrize( |
| 50 | + "input_value,expected_decimal_fraction", [(0.0, 0.0), (99, 0.99), (51.234, 0.51234)] |
| 51 | +) |
| 52 | +def test_as_decimal_fraction_limited(input_value: float, expected_decimal_fraction: float): |
| 53 | + assert ModelLimited(p=input_value).p.as_decimal_fraction() == expected_decimal_fraction # type: ignore [arg-type] # noqa: E501 |
0 commit comments