Skip to content

Commit

Permalink
add sanity check when importing data from a dictionary
Browse files Browse the repository at this point in the history
Signed-off-by: Jose Borreguero <[email protected]>
  • Loading branch information
jmborr committed Feb 16, 2024
1 parent ece500d commit fdc3d1f
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
13 changes: 13 additions & 0 deletions reduction/lr_reduction/reduction_template_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,19 @@ def __init__(self):
self.incident_medium_index_selected = 0

def from_dict(self, data_dict):
r"""Update object's attributes with a dictionary with entries of the type attribute_name: attribute_value.
Raises
------
ValueError
if one entry of the dictionary is not an attribute of this object
"""

# check all keys are data_dict are attributes of object `self`
attribute_names = list(vars(self))
if not all(key in attribute_names for key in data_dict):
raise ValueError("data_dir contains invalid entries")
# update attribute values
for k, v in data_dict.items():
setattr(self, k, v)

Expand Down
29 changes: 29 additions & 0 deletions reduction/test/test_reduction_template_reader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# third-party imports
import pytest

# lr_reduction imports
from lr_reduction.reduction_template_reader import ReductionParameters


class TestReductionParameters:

def test_two_backgrounds(self):
r"""verify the xml dump writes what we want"""
redparms = ReductionParameters()
redparms.two_backgrounds = True
assert "<two_backgrounds_flag>True</two_backgrounds_flag>" in redparms.to_xml()

def test_from_dict(self):
r"""verify method from_dict raises when passed some nonsense"""

redparms = ReductionParameters()
# valid data dictionary
redparms.from_dict(dict(two_backgrounds=True))
assert redparms.two_backgrounds
# invalid data dictionary
with pytest.raises(ValueError) as excinfo:
redparms.from_dict(dict(nonsense=True))
assert "data_dir contains invalid entries" == str(excinfo.value)

if __name__ == "__main__":
pytest.main(__file__)

0 comments on commit fdc3d1f

Please sign in to comment.