mirror of
https://github.com/inventree/InvenTree
synced 2024-08-30 18:33:04 +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
|
||||
# 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
|
||||
|
@ -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"""
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user