Skip to content

Commit

Permalink
Enable initialization with "empty" datamodel
Browse files Browse the repository at this point in the history
  • Loading branch information
WilliamJamieson committed Aug 22, 2023
1 parent bcd7d9f commit 4ae89cf
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
19 changes: 15 additions & 4 deletions src/roman_datamodels/datamodels/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,18 +90,22 @@ def __init__(self, init=None, **kwargs):
return

if init is None:
self._asdf = self.open_asdf(init=None, **kwargs)
self._instance = self._node_type()

elif isinstance(init, (str, bytes, PurePath)):
if isinstance(init, PurePath):
init = str(init)
if isinstance(init, bytes):
init = init.decode(sys.getfilesystemencoding())

self._asdf = self.open_asdf(init, **kwargs)
if not self.check_type(self._asdf):
raise ValueError(f"ASDF file is not of the type expected. Expected {self.__class__.__name__}")

self._instance = self._asdf.tree["roman"]
elif isinstance(init, asdf.AsdfFile):
self._asdf = init

self._instance = self._asdf.tree["roman"]
else:
raise OSError("Argument does not appear to be an ASDF file or TaggedObjectNode.")
Expand Down Expand Up @@ -303,11 +307,18 @@ def validate(self):
"""
validate.value_change(self._instance, pass_invalid_values=False, strict_validation=True)

@property
def asdf(self):
if self._asdf is None:
self._asdf = asdf.AsdfFile({"roman": self._instance})

return self._asdf

def info(self, *args, **kwargs):
return self._asdf.info(*args, **kwargs)
return self.asdf.info(*args, **kwargs)

def search(self, *args, **kwargs):
return self._asdf.search(*args, **kwargs)
return self.asdf.search(*args, **kwargs)

def schema_info(self, *args, **kwargs):
return self._asdf.schema_info(*args, **kwargs)
return self.asdf.schema_info(*args, **kwargs)
23 changes: 23 additions & 0 deletions tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,29 @@ def test_model_schemas(node, model):
asdf.schema.load_schema(instance.schema_uri)


@pytest.mark.parametrize("node, model", datamodels.MODEL_REGISTRY.items())
def test_empty_model(node, model):
mdl = model()
assert isinstance(mdl._instance, node)
assert mdl._asdf is None


@pytest.mark.parametrize("node, model", datamodels.MODEL_REGISTRY.items())
def test_empty_model_asdf(node, model):
mdl = model()

# Check there is a validation issue
with pytest.raises(asdf.ValidationError):
mdl.asdf

assert mdl._asdf is None

# Fill in instance properly and check that asdf can be created
mdl._instance = utils.mk_node(node)
assert mdl.asdf.tree["roman"] is mdl._instance
assert mdl._asdf is not None


# Testing core schema
def test_core_schema(tmp_path):
# Set temporary asdf file
Expand Down

0 comments on commit 4ae89cf

Please sign in to comment.