diff --git a/src/parcels/_typing.py b/src/parcels/_typing.py index 7c2e12b8fd..3d44281209 100644 --- a/src/parcels/_typing.py +++ b/src/parcels/_typing.py @@ -39,24 +39,27 @@ KernelFunction = Callable[..., None] +def _is_xarray_object(obj): # with no imports + try: + return "xarray.core" in obj.__module__ + except AttributeError: + return False + + def _validate_against_pure_literal(value, typing_literal): """Uses a Literal type alias to validate. Can't be used with ``Literal[...] | None`` etc. as its not a pure literal. """ + # TODO remove once https://github.com/pydata/xarray/issues/11209 is resolved - Xarray objects don't work normally in `in` statements + if _is_xarray_object(value): + raise ValueError(f"Invalid input type {type(value)}") + if value not in get_args(typing_literal): msg = f"Invalid value {value!r}. Valid options are {get_args(typing_literal)!r}" raise ValueError(msg) # Assertion functions to clean user input -def assert_valid_interp_method(value: Any): - _validate_against_pure_literal(value, InterpMethodOption) - - def assert_valid_mesh(value: Any): _validate_against_pure_literal(value, Mesh) - - -def assert_valid_gridindexingtype(value: Any): - _validate_against_pure_literal(value, GridIndexingType) diff --git a/tests-v3/test_typing.py b/tests-v3/test_typing.py deleted file mode 100644 index f4efba3efd..0000000000 --- a/tests-v3/test_typing.py +++ /dev/null @@ -1,31 +0,0 @@ -import pytest - -from parcels._typing import ( - assert_valid_gridindexingtype, - assert_valid_interp_method, - assert_valid_mesh, -) - -validators = ( - assert_valid_interp_method, - assert_valid_mesh, - assert_valid_gridindexingtype, -) - - -@pytest.mark.parametrize("validator", validators) -def test_invalid_option(validator): - with pytest.raises(ValueError): - validator("invalid option") - - -validation_mapping = [ - (assert_valid_interp_method, "nearest"), - (assert_valid_mesh, "spherical"), - (assert_valid_gridindexingtype, "pop"), -] - - -@pytest.mark.parametrize("validator, value", validation_mapping) -def test_valid_option(validator, value): - validator(value) diff --git a/tests/test_typing.py b/tests/test_typing.py new file mode 100644 index 0000000000..4f1d3e0c56 --- /dev/null +++ b/tests/test_typing.py @@ -0,0 +1,20 @@ +import numpy as np +import pytest +import xarray as xr + +from parcels._typing import ( + assert_valid_mesh, +) + + +def test_invalid_assert_valid_mesh(): + with pytest.raises(ValueError, match="Invalid value"): + assert_valid_mesh("invalid option") + + ds = xr.Dataset({"A": (("a", "b"), np.arange(20).reshape(4, 5))}) + with pytest.raises(ValueError, match="Invalid input type"): + assert_valid_mesh(ds) + + +def test_assert_valid_mesh(): + assert_valid_mesh("spherical")