def testScalarInvalidValue(unit_database_len_time): db = unit_database_len_time db.AddCategory("another-length", "length", min_value=0, max_value=15) scalar = Scalar("another-length", value=15, unit="m") assert scalar.IsValid() scalar = Scalar("another-length", value=-5, unit="m") assert not scalar.IsValid() # By default the validation will be performed. 15 is a valid value. scalar = Scalar("another-length", value=15, unit="m") assert scalar.IsValid() # Even invalid ,the scalar returns the value, unit and a formatted text. another = Scalar("another-length", value=3000, unit="m") assert not another.IsValid() assert another.GetValue("m") == 3000 assert another.GetUnit() == "m" assert another.GetFormatted() == "3000 [m]" # By default the validation will be performed, and in this cases will raise ValueError. another_2 = Scalar("another-length", unit="m", value=5000) assert not another_2.IsValid() # Performing copy between invalid scalars. The validation is not performed on copy. copied = another.CreateCopy(unit="cm") assert not copied.IsValid() assert copied.GetValue("m") == 3000 assert copied.GetUnit() == "cm" assert copied.GetFormatted() == "300000 [cm]"
def testFormatedUnitsOnScalar(unit_database_empty) -> None: """ Allow present units on get formatted Scalar """ unit_database = unit_database_empty unit_database.AddUnitBase("length", "meters", "m") unit_database.AddCategory(category="length", quantity_type="length") class MyScalar(units.Scalar): pass scalar = MyScalar("length", 1.18, "m") assert scalar.GetFormatted() == "1.18 [m]" MyScalar.SetFormattedValueFormat("%0.4f") MyScalar.SetFormattedSuffixFormat(" (%s)") # Tests the GET methods assert MyScalar.GetFormattedValueFormat() == "%0.4f" assert MyScalar.GetFormattedSuffixFormat() == " (%s)" # Tests the Formatted method assert scalar.GetFormatted() == "1.1800 (m)" # Check for invalid format strings with pytest.raises(TypeError): MyScalar.SetFormattedValueFormat("%d [%s]") with pytest.raises(TypeError): MyScalar.SetFormattedSuffixFormat("%s %s") with pytest.raises(TypeError): MyScalar.SetFormattedSuffixFormat("%f") # When invalid format are set, the formats are not changed assert MyScalar.GetFormattedValueFormat() == "%0.4f" assert MyScalar.GetFormattedSuffixFormat() == " (%s)" # Make sure we didn't affect the Scalar class, only the local MyScalar MyScalar.SetFormattedValueFormat("<<< %f") MyScalar.SetFormattedSuffixFormat(" [%s] >>>") scalar2 = Scalar("length", 1.18, "m") assert scalar2.GetFormatted() == "1.18 [m]"