Skip to content

Commit

Permalink
Add additional checks and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ka-sarthak committed Feb 20, 2024
1 parent 1f1c6e9 commit 790e23d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
8 changes: 7 additions & 1 deletion src/nomad_measurements/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,12 @@ def to_pint_quantity(value: Any=None, unit: str=None) -> Any:
Returns:
Any: Processed quantity with datatype depending on the value.
'''
if isinstance(value, str):
if isinstance(value, str) or value is None:
return value
if unit is None:
if isinstance(value, ureg.Quantity):
return value
return value * ureg.dimensionless
if isinstance(value, ureg.Quantity):
return value.to(unit)
return value * ureg(unit)
18 changes: 13 additions & 5 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,20 @@ def test_merge_sections():
assert system_3.components[0].name == 'Cu'

def test_to_pint_quantity():
assert to_pint_quantity(1, 'mA') == 1 * ureg.mA
assert str(to_pint_quantity(np.asarray([1., 2.]), 'm')) \
== str(np.asarray([1., 2.]) * ureg.m)
assert str(to_pint_quantity(np.asarray([1., 2.]), '')) \
== str(np.asarray([1., 2.]))
assert to_pint_quantity(None, '') is None
assert to_pint_quantity(None, None) is None
assert to_pint_quantity(None, 'mA') is None
assert to_pint_quantity('Copper', '') == 'Copper'
assert to_pint_quantity('Copper', 'mA') == 'Copper'
assert to_pint_quantity(3., None) == 3 * ureg.dimensionless
assert to_pint_quantity(3. * ureg.m, None) == 3 * ureg.m
assert to_pint_quantity(3. * ureg.m, 'cm') == 300 * ureg.cm
assert to_pint_quantity(1, None) == 1
assert (to_pint_quantity(np.asarray([1., 2.]), 'm') \
== np.asarray([1., 2.]) * ureg.m).all()
assert (to_pint_quantity(np.asarray([1., 2.]), '') \
== np.asarray([1., 2.]) * ureg.dimensionless).all()
assert to_pint_quantity(1, 'mA') == 1 * ureg.mA

if __name__ == '__main__':
test_merge_sections()

0 comments on commit 790e23d

Please sign in to comment.