Catch potential exception when performing unit conversion (#5699)

This commit is contained in:
Oliver 2023-10-16 12:00:44 +11:00 committed by GitHub
parent 598f0a5021
commit 4ecd49e3eb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 5 deletions

View File

@ -134,12 +134,15 @@ def convert_physical_value(value: str, unit: str = None, strip_units=True):
# If the value is specified strangely (e.g. as a fraction or a dozen), this can cause issues
# So, we ensure that it is converted to a floating point value
# If we wish to return a "raw" value, some trickery is required
if unit:
magnitude = ureg.Quantity(value.to(ureg.Unit(unit))).magnitude
else:
magnitude = ureg.Quantity(value.to_base_units()).magnitude
try:
if unit:
magnitude = ureg.Quantity(value.to(ureg.Unit(unit))).magnitude
else:
magnitude = ureg.Quantity(value.to_base_units()).magnitude
magnitude = float(ureg.Quantity(magnitude).to_base_units().magnitude)
magnitude = float(ureg.Quantity(magnitude).to_base_units().magnitude)
except Exception as exc:
raise ValidationError(_(f'Invalid quantity supplied ({exc})'))
if strip_units:
return magnitude

View File

@ -104,6 +104,21 @@ class ConversionTest(TestCase):
q = InvenTree.conversion.convert_physical_value(val)
self.assertAlmostEqual(q, expected, 3)
def test_invalid_units(self):
"""Test conversion with bad units"""
tests = {
'3': '10',
'13': '-?-',
'-3': 'xyz',
'-12': '-12',
'1/0': '1/0',
}
for val, unit in tests.items():
with self.assertRaises(ValidationError):
InvenTree.conversion.convert_physical_value(val, unit)
def test_invalid_values(self):
"""Test conversion of invalid inputs"""