From 1e6a800959cb5a3ba5c528ec7fbbcfa3e6843d8f Mon Sep 17 00:00:00 2001 From: Per von Zweigbergk Date: Sat, 9 Sep 2023 12:13:58 +0200 Subject: [PATCH] Move translation of ValueError to ValidationError into to_python where it belongs --- netbox/utilities/forms/fields/expandable.py | 5 ++++- netbox/utilities/forms/utils.py | 7 +------ netbox/utilities/tests/test_forms.py | 8 ++++---- 3 files changed, 9 insertions(+), 11 deletions(-) diff --git a/netbox/utilities/forms/fields/expandable.py b/netbox/utilities/forms/fields/expandable.py index 959271a85..d0f82765a 100644 --- a/netbox/utilities/forms/fields/expandable.py +++ b/netbox/utilities/forms/fields/expandable.py @@ -30,7 +30,10 @@ class ExpandableNameField(forms.CharField): if not value: return '' if re.search(ALPHANUMERIC_EXPANSION_PATTERN, value): - return list(expand_alphanumeric_pattern(value)) + try: + return list(expand_alphanumeric_pattern(value)) + except ValueError as e: + raise forms.ValidationError(*e.args) return [value] diff --git a/netbox/utilities/forms/utils.py b/netbox/utilities/forms/utils.py index a7446f79f..41b92932c 100644 --- a/netbox/utilities/forms/utils.py +++ b/netbox/utilities/forms/utils.py @@ -96,12 +96,7 @@ def expand_alphanumeric_pattern(pattern): if not re.search(ALPHANUMERIC_EXPANSION_PATTERN, pattern): raise ValueError(f"String {repr(pattern)} contains no valid alphanumeric patterns") - try: - yield from expand_alphanumeric_pattern_impl(pattern) - except ValueError as e: - # Unit tests expect forms.ValidationError to be thrown if patterns were "valid" at a first glance, - # but then turned out to be invalid when looking closer. So we preserve this behaviour here. - raise forms.ValidationError(*e.args) + yield from expand_alphanumeric_pattern_impl(pattern) def expand_ipaddress_pattern(string, family): diff --git a/netbox/utilities/tests/test_forms.py b/netbox/utilities/tests/test_forms.py index 999e7290d..af0639d36 100644 --- a/netbox/utilities/tests/test_forms.py +++ b/netbox/utilities/tests/test_forms.py @@ -269,19 +269,19 @@ class ExpandAlphanumeric(TestCase): sorted(expand_alphanumeric_pattern('r[8--9]a')) def test_invalid_range_alphanumeric(self): - with self.assertRaises(forms.ValidationError): + with self.assertRaises(ValueError): sorted(expand_alphanumeric_pattern('r[9-a]a')) - with self.assertRaises(forms.ValidationError): + with self.assertRaises(ValueError): sorted(expand_alphanumeric_pattern('r[a-9]a')) def test_invalid_range_bounds(self): - with self.assertRaises(forms.ValidationError): + with self.assertRaises(ValueError): sorted(expand_alphanumeric_pattern('r[9-8]a')) sorted(expand_alphanumeric_pattern('r[b-a]a')) def test_invalid_range_len(self): - with self.assertRaises(forms.ValidationError): + with self.assertRaises(ValueError): sorted(expand_alphanumeric_pattern('r[a-bb]a')) def test_invalid_set(self):