Skip to content

Commit

Permalink
Merge pull request #16 from MridulS/add_scipp_unit_test
Browse files Browse the repository at this point in the history
Validation check for scipp parsable units
  • Loading branch information
MridulS authored May 27, 2024
2 parents d5d15c1 + 8aa12e5 commit 5ec0471
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/chexus/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,25 @@ def validate(self, node: Dataset | Group) -> Violation | None:
return Violation(node.name)


class dataset_units_check(Validator):
def __init__(self) -> None:
super().__init__(
"dataset_units_check",
"Dataset should have units parasable by scipp",
)

def applies_to(self, node: Dataset | Group) -> bool:
return isinstance(node, Dataset) and 'units' in node.attrs

def validate(self, node: Dataset | Group) -> Violation | None:
import scipp as sc

try:
sc.Unit(node.attrs['units'])
except sc.UnitError:
return Violation(node.name)


class non_numeric_dataset_has_units(Validator):
def __init__(self) -> None:
super().__init__(
Expand Down Expand Up @@ -306,5 +325,6 @@ def base_validators(*, has_scipp=True):
if has_scipp:
validators += [
chopper_frequency_units_invalid(),
dataset_units_check(),
]
return validators
37 changes: 37 additions & 0 deletions tests/validators_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,43 @@ def test_units_invalid(units: str):
assert result.name == 'x'


@pytest.mark.parametrize(
"units",
["m", "", "1/year", "Hz/ms"],
)
def test_dataset_units_check_valid(units: str):
dataset = chexus.Dataset(
name="x",
value=1.0,
shape=None,
dtype=np.float64,
parent=None,
attrs={"units": units},
)
assert chexus.validators.dataset_units_check().applies_to(dataset)
result = chexus.validators.dataset_units_check().validate(dataset)
assert result is None


@pytest.mark.parametrize(
"units",
["test", "seco"],
)
def test_dataset_units_check_not_valid(units: str):
dataset = chexus.Dataset(
name="x",
value=1.0,
shape=None,
dtype=np.float64,
parent=None,
attrs={"units": units},
)
assert chexus.validators.dataset_units_check().applies_to(dataset)
result = chexus.validators.dataset_units_check().validate(dataset)
assert isinstance(result, chexus.Violation)
assert result.name == "x"


@pytest.mark.parametrize(
'units, good',
[
Expand Down

0 comments on commit 5ec0471

Please sign in to comment.