From aeeab62e2078eb7f096c8ff2b36d2d56f5406e2a Mon Sep 17 00:00:00 2001 From: Jan Range Date: Thu, 7 Mar 2024 15:53:34 -0600 Subject: [PATCH] add tests for `Unit` --- tests/unit/datatypes/test_unit.py | 118 ++++++++++++++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 tests/unit/datatypes/test_unit.py diff --git a/tests/unit/datatypes/test_unit.py b/tests/unit/datatypes/test_unit.py new file mode 100644 index 0000000..43dfb28 --- /dev/null +++ b/tests/unit/datatypes/test_unit.py @@ -0,0 +1,118 @@ +import json +import re +import pytest + +from sdRDM.base.datatypes.unit import BaseUnit, Unit +from astropy.units import UnitBase, Unit as AstroUnit + + +class TestUnit: + @pytest.mark.unit + def test_simple_unit_from_string(self): + # Arrange + unit_string = "m" + + # Act + unit = Unit.from_string(unit_string) + + # Assert + assert unit.name == "m" + assert unit.bases == [ + BaseUnit( + kind="m", + exponent=1, + scale=1, + ) + ] + + @pytest.mark.unit + def test_composite_unit_from_string(self): + # Arrange + unit_string = "m/s" + + # Act + unit = Unit.from_string(unit_string) + + # Assert + assert unit.name == "m / s" + assert unit.bases == [ + BaseUnit( + kind="m", + exponent=1, + scale=1, + ), + BaseUnit( + kind="s", + exponent=-1, + scale=1, + ), + ] + + @pytest.mark.unit + def test_dimensionless_unit_from_string(self): + # Arrange + unit_string = "dimensionless" + + # Act + unit = Unit.from_string(unit_string) + + # Assert + assert unit.name == "dimensionless" + assert unit.bases == [] + + @pytest.mark.unit + def test_json_serialization(self): + # Arrange + unit_string = "m/s" + + # Act + unit = Unit.from_string(unit_string) + unit_json = unit.json(exclude={"id"}) + + # Assert + expected_json = { + "name": "m / s", + "bases": [ + { + "kind": "m", + "exponent": 1, + "scale": 1, + }, + { + "kind": "s", + "exponent": -1, + "scale": 1, + }, + ], + } + + assert json.loads(unit_json) == expected_json + + @pytest.mark.unit + def test_to_unit_string(self): + # Arrange + unit_string = "m/s" + unit = Unit.from_string(unit_string) + + # Act + string = unit.to_unit_string() + + # Assert + assert string == "m / s" + + @pytest.mark.unit + def test_xml_serialization(self): + # Arrange + unit_string = "m/s" + + # Act + unit = Unit.from_string(unit_string) + unit_xml = unit.xml() + + # Assert + expected_xml = ' ' + + unit_xml = unit_xml.replace("\n", "").replace("'", '"') + unit_xml = re.sub(r'id="[\w-]+"', "", unit_xml) + + assert unit_xml == expected_xml