mirror of
https://github.com/inventree/InvenTree.git
synced 2025-04-30 12:36:45 +00:00
Catch potential exception when performing unit conversion (#5699)
This commit is contained in:
parent
598f0a5021
commit
4ecd49e3eb
@ -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
|
# 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
|
# 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 we wish to return a "raw" value, some trickery is required
|
||||||
if unit:
|
try:
|
||||||
magnitude = ureg.Quantity(value.to(ureg.Unit(unit))).magnitude
|
if unit:
|
||||||
else:
|
magnitude = ureg.Quantity(value.to(ureg.Unit(unit))).magnitude
|
||||||
magnitude = ureg.Quantity(value.to_base_units()).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:
|
if strip_units:
|
||||||
return magnitude
|
return magnitude
|
||||||
|
@ -104,6 +104,21 @@ class ConversionTest(TestCase):
|
|||||||
q = InvenTree.conversion.convert_physical_value(val)
|
q = InvenTree.conversion.convert_physical_value(val)
|
||||||
self.assertAlmostEqual(q, expected, 3)
|
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):
|
def test_invalid_values(self):
|
||||||
"""Test conversion of invalid inputs"""
|
"""Test conversion of invalid inputs"""
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user