2024-05-09 04:29:13 +00:00
|
|
|
import numpy as np
|
|
|
|
import pytest
|
2024-08-13 03:50:33 +00:00
|
|
|
from pydantic import ValidationError, BaseModel
|
2024-05-09 04:29:13 +00:00
|
|
|
from numpydantic.exceptions import DtypeError, ShapeError
|
|
|
|
|
|
|
|
from tests.conftest import ValidationCase
|
|
|
|
|
2024-09-23 20:28:38 +00:00
|
|
|
pytestmark = pytest.mark.numpy
|
|
|
|
|
2024-05-09 04:29:13 +00:00
|
|
|
|
|
|
|
def numpy_array(case: ValidationCase) -> np.ndarray:
|
2024-08-13 03:50:33 +00:00
|
|
|
if issubclass(case.dtype, BaseModel):
|
|
|
|
return np.full(shape=case.shape, fill_value=case.dtype(x=1))
|
|
|
|
else:
|
|
|
|
return np.zeros(shape=case.shape, dtype=case.dtype)
|
2024-05-09 04:29:13 +00:00
|
|
|
|
|
|
|
|
|
|
|
def _test_np_case(case: ValidationCase):
|
|
|
|
array = numpy_array(case)
|
|
|
|
if case.passes:
|
|
|
|
case.model(array=array)
|
|
|
|
else:
|
|
|
|
with pytest.raises((ValidationError, DtypeError, ShapeError)):
|
|
|
|
case.model(array=array)
|
|
|
|
|
|
|
|
|
2024-09-23 20:28:38 +00:00
|
|
|
@pytest.mark.shape
|
2024-05-09 04:29:13 +00:00
|
|
|
def test_numpy_shape(shape_cases):
|
|
|
|
_test_np_case(shape_cases)
|
|
|
|
|
|
|
|
|
2024-09-23 20:28:38 +00:00
|
|
|
@pytest.mark.dtype
|
2024-05-09 04:29:13 +00:00
|
|
|
def test_numpy_dtype(dtype_cases):
|
|
|
|
_test_np_case(dtype_cases)
|
2024-05-15 03:18:04 +00:00
|
|
|
|
|
|
|
|
|
|
|
def test_numpy_coercion(model_blank):
|
|
|
|
"""If no other interface matches, we try and coerce to a numpy array"""
|
|
|
|
instance = model_blank(array=[1, 2, 3])
|
|
|
|
assert isinstance(instance.array, np.ndarray)
|