Skip to content

Commit

Permalink
Add additional checks and tests (#81)
Browse files Browse the repository at this point in the history
* Add additional checks and tests

* Update src/nomad_measurements/utils.py

Co-authored-by: Hampus Näsström <[email protected]>

* Edit docstring and remove redundant test

---------

Co-authored-by: Hampus Näsström <[email protected]>
  • Loading branch information
ka-sarthak and hampusnasstrom authored Feb 28, 2024
1 parent 73f9a05 commit 994d5eb
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
7 changes: 6 additions & 1 deletion src/nomad_measurements/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ def to_pint_quantity(value: Any=None, unit: str=None) -> Any:
'''
Attempts to generate a pint quantity.
In case the value is a string, it is returned as is.
If the value is a pint quantity, it is converted to the given unit.
Args:
value (Any): Value of the quantity.
Expand All @@ -126,6 +127,10 @@ 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 isinstance(value, ureg.Quantity):
if unit is None:
return value
return value.to(unit)
return value * ureg(unit)
13 changes: 10 additions & 3 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,19 @@ 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 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., '') == 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.])).all()
assert to_pint_quantity('Copper', '') == 'Copper'
== 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 994d5eb

Please sign in to comment.