| 1 |
import pytest |
| 2 |
import numpy as np |
| 3 |
import xarray as xr |
| 4 |
|
| 5 |
from polsarpro.auxil import validate_dataset, POLTYPES |
| 6 |
|
| 7 |
|
| 8 |
def make_dataset(poltype: str, wrong_dtype: bool = False, desc: str | None = None): |
| 9 |
"""Utility to build a dataset for a given poltype, with optional mistakes.""" |
| 10 |
if poltype not in POLTYPES: |
| 11 |
# use S variables by default if poltype is not correct |
| 12 |
specs = POLTYPES["S"] |
| 13 |
else: |
| 14 |
specs = POLTYPES[poltype] |
| 15 |
shape = (5, 5) |
| 16 |
|
| 17 |
data_vars = {} |
| 18 |
for v, props in specs["vars"].items(): |
| 19 |
dtype = props["dtype"] |
| 20 |
if wrong_dtype: |
| 21 |
# flip float32 -> complex64, complex64 -> float32 |
| 22 |
dtype = "complex64" if dtype == "float32" else "float32" |
| 23 |
arr = np.zeros(shape, dtype=dtype) |
| 24 |
data_vars[v] = (("y", "x"), arr) |
| 25 |
|
| 26 |
ds = xr.Dataset(data_vars) |
| 27 |
ds.attrs["poltype"] = poltype |
| 28 |
ds.attrs["description"] = desc if desc is not None else specs["description"] |
| 29 |
return ds |
| 30 |
|
| 31 |
|
| 32 |
@pytest.mark.parametrize("poltype", list(POLTYPES.keys())) |
| 33 |
def test_valid_datasets_pass(poltype): |
| 34 |
ds = make_dataset(poltype) |
| 35 |
# Should not raise |
| 36 |
_ = validate_dataset(ds, allowed_poltypes=poltype) |
| 37 |
|
| 38 |
|
| 39 |
def test_invalid_poltype_raises(): |
| 40 |
ds = make_dataset("INVALID") |
| 41 |
with pytest.raises(ValueError, match=f"Unsupported poltype"): |
| 42 |
_ = validate_dataset(ds, allowed_poltypes=("S", "T3", "C4")) |
| 43 |
|
| 44 |
|
| 45 |
def test_missing_variable_raises(): |
| 46 |
ds = make_dataset("S") |
| 47 |
ds = ds.drop_vars("hh") |
| 48 |
with pytest.raises(ValueError, match=f"Dataset is missing required variable: 'hh'"): |
| 49 |
_ = validate_dataset(ds, allowed_poltypes="S") |
| 50 |
|
| 51 |
|
| 52 |
def test_wrong_dtype_detected(): |
| 53 |
ds = make_dataset("T3", wrong_dtype=True) |
| 54 |
with pytest.raises(ValueError, match="dtype"): |
| 55 |
_ = validate_dataset(ds, allowed_poltypes="T3", check_dtypes=True) |
| 56 |
|
| 57 |
|
| 58 |
def test_skip_checks_allows_pass(): |
| 59 |
# Wrong dtype, but skip dtype check |
| 60 |
ds = make_dataset("T3", wrong_dtype=True) |
| 61 |
# Should not raise |
| 62 |
_ = validate_dataset(ds, allowed_poltypes="T3", check_dtypes=False) |