Improve error handling for unit registry (#12643) (#12645)

(cherry picked from commit af74f1abf6)

Co-authored-by: Oliver <oliver.henry.walters@gmail.com>
This commit is contained in:
github-actions[bot]
2026-08-16 12:41:38 +10:00
committed by GitHub
co-authored by Oliver
parent c977de706a
commit 0acfec3ef0
2 changed files with 15 additions and 2 deletions
+14 -1
View File
@@ -1,5 +1,7 @@
"""Custom field validators for InvenTree.""" """Custom field validators for InvenTree."""
import tokenize
from django.conf import settings from django.conf import settings
from django.core import validators from django.core import validators
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
@@ -9,6 +11,7 @@ import pint.errors
from moneyed import CURRENCIES from moneyed import CURRENCIES
import InvenTree.conversion import InvenTree.conversion
import InvenTree.exceptions
from common.settings import get_global_setting from common.settings import get_global_setting
@@ -24,7 +27,17 @@ def validate_physical_units(unit):
try: try:
ureg(unit) ureg(unit)
except (AssertionError, AttributeError, pint.errors.UndefinedUnitError): except (
AssertionError,
AttributeError,
pint.errors.UndefinedUnitError,
tokenize.TokenError,
):
raise ValidationError(_('Invalid physical unit'))
except Exception:
# Pint parses unit expressions via the python tokenizer, so any
# other unexpected exception type may be raised for malformed input
InvenTree.exceptions.log_error('validate_physical_units', scope='validators')
raise ValidationError(_('Invalid physical unit')) raise ValidationError(_('Invalid physical unit'))
+1 -1
View File
@@ -252,7 +252,7 @@ class ParameterTests(TestCase):
tmp.full_clean() tmp.full_clean()
# Test that invalid units fail # Test that invalid units fail
for unit in ['mmmmm', '-', 'x', int]: for unit in ['mmmmm', '-', 'x', int, "piao's"]:
tmp = ParameterTemplate(name='test', units=unit) tmp = ParameterTemplate(name='test', units=unit)
with self.assertRaises(django_exceptions.ValidationError): with self.assertRaises(django_exceptions.ValidationError):
tmp.full_clean() tmp.full_clean()