diff --git a/InvenTree/InvenTree/conversion.py b/InvenTree/InvenTree/conversion.py index c69bd73c0c..dc7c4a3224 100644 --- a/InvenTree/InvenTree/conversion.py +++ b/InvenTree/InvenTree/conversion.py @@ -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 diff --git a/InvenTree/InvenTree/tests.py b/InvenTree/InvenTree/tests.py index cbb8bf58d1..02d8b9c408 100644 --- a/InvenTree/InvenTree/tests.py +++ b/InvenTree/InvenTree/tests.py @@ -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"""