Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validate dimension when instantiating datamodel from shape #395

Merged
merged 4 commits into from
Feb 11, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/395.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Validate dimension against schema when instantiating datamodel from array shape
2 changes: 1 addition & 1 deletion src/stdatamodels/jwst/datamodels/tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ class _NonstandardPrimaryArrayModel(JwstDataModel):
def get_primary_array_name(self):
return "wavelength"

m = _NonstandardPrimaryArrayModel((10,))
m = _NonstandardPrimaryArrayModel((10, 10))
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This appeared to be an instance of an array passing validation that we would expect to fail, and indeed it does fail as of the bugfix in this PR. It doesn't look like this change makes much difference for what the test intends to cover, but someone can correct me if that's wrong.

assert "wavelength" in list(m.keys())
assert m.wavelength.sum() == 0

Expand Down
4 changes: 4 additions & 0 deletions src/stdatamodels/properties.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,10 @@ def _make_default_array(attr, schema, ctx):

if attr == primary_array_name:
if ctx.shape is not None:
# Ensure that input shape matches schema ndim
if (ndim is not None) and (len(ctx.shape) != ndim):
msg = f"Array has wrong number of dimensions. Expected {ndim}, got {len(ctx.shape)}"
raise ValueError(msg)
shape = ctx.shape
elif ndim is not None:
shape = tuple([0] * ndim)
Expand Down
5 changes: 5 additions & 0 deletions tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,11 @@ def test_init_with_array2():
dm.data # noqa: B018


def test_init_invalid_shape():
with pytest.raises(ValueError):
BasicModel((50, 50, 50))


def test_set_array():
with pytest.raises(ValueError):
with BasicModel() as dm:
Expand Down
Loading