diff --git a/src/doc/cfood.rst b/src/doc/cfood.rst index 1ffd26c6bfada5e778b56ccb308ade2c39d4e922..6dc226b29c286a0c7cc13539485c5c494a923339 100644 --- a/src/doc/cfood.rst +++ b/src/doc/cfood.rst @@ -167,9 +167,9 @@ following. ValueWithUnitElt: type: TextElement match_name: ^my_prop$ - match_value: "^(?P<number>\d+\.?\d*)\s+(?P<unit>.+)" # Extract value and unit from a string which - # has a number followed by at least one whitespace - # character followed by a unit. + match_value: "^(?P<number>\\d+\\.?\\d*)\s+(?P<unit>.+)" # Extract value and unit from a string which + # has a number followed by at least one whitespace + # character followed by a unit. records: MyRecord: MyProp: diff --git a/unittests/test_scanner.py b/unittests/test_scanner.py index 226b5040547f0e003729dba63622edf836552f18..da26af0b9436b622aa9e479dc24f000283cfdc32 100644 --- a/unittests/test_scanner.py +++ b/unittests/test_scanner.py @@ -316,3 +316,57 @@ def test_record_parents(): assert rec.parents[0].name == 'Stuff' # default parent stays if no parent is given on # lower levels assert len(rec.parents) == 1 + + +def test_units(): + """Test the correct setting of units.""" + crawler_definition = load_definition(UNITTESTDIR / "test_unit_cfood.yml") + converter_registry = create_converter_registry(crawler_definition) + + data = { + "value_with_unit": "1.1 m", + "array_with_units": [ + "1.1 cm", + "2.2 cm" + ] + } + records = scan_structure_elements(DictElement(name="", value=data), crawler_definition, + converter_registry) + assert len(records) == 1 + rec = records[0] + # This is hard-coded in cfood: + assert rec.get_property("may_be_overwritten") is not None + assert rec.get_property("may_be_overwritten").value == "12" + assert rec.get_property("may_be_overwritten").unit == "K" + # Those are set from data + assert rec.get_property("value_with_unit") is not None + assert rec.get_property("value_with_unit").value == "1.1" + assert rec.get_property("value_with_unit").unit == "m" + assert rec.get_property("list_with_unit") is not None + assert rec.get_property("list_with_unit").value == ["1.1", "2.2"] + assert rec.get_property("list_with_unit").unit == "cm" + + # Contradictory units + data = { + "array_with_units": [ + "1.1 K", + "45 W" + ] + } + with raises(RuntimeError) as rte: + records = scan_structure_elements(DictElement(name="", value=data), crawler_definition, + converter_registry) + assert "Property 'list_with_unit' has contradictory units" in str(rte.value) + + # Overwrite value and unit + data = { + "may_be_overwritten": "400 °C" + } + records = scan_structure_elements(DictElement(name="", value=data), crawler_definition, + converter_registry) + assert len(records) == 1 + rec = records[0] + # Now set from data + assert rec.get_property("may_be_overwritten") is not None + assert rec.get_property("may_be_overwritten").value == "400" + assert rec.get_property("may_be_overwritten").unit == "°C"