diff --git a/django/contrib/gis/measure.py b/django/contrib/gis/measure.py index 640f0e0068..590a80293a 100644 --- a/django/contrib/gis/measure.py +++ b/django/contrib/gis/measure.py @@ -232,7 +232,7 @@ class MeasureBase: """ Retrieve the unit attribute name for the given unit string. For example, if the given unit string is 'metre', return 'm'. - Raise an exception if an attribute cannot be found. + Raise an AttributeError if an attribute cannot be found. """ lower = unit_str.lower() if unit_str in cls.UNITS: @@ -242,9 +242,7 @@ class MeasureBase: elif lower in cls.LALIAS: return cls.LALIAS[lower] else: - raise Exception( - 'Could not find a unit keyword associated with "%s"' % unit_str - ) + raise AttributeError(f"Unknown unit type: {unit_str}") class Distance(MeasureBase): diff --git a/tests/gis_tests/test_measure.py b/tests/gis_tests/test_measure.py index 01ad5182e7..2a922abf9b 100644 --- a/tests/gis_tests/test_measure.py +++ b/tests/gis_tests/test_measure.py @@ -6,9 +6,10 @@ and conversions. Here are some tests. import unittest from django.contrib.gis.measure import A, Area, D, Distance +from django.test import SimpleTestCase -class DistanceTest(unittest.TestCase): +class DistanceTest(SimpleTestCase): "Testing the Distance object" def test_init(self): @@ -157,6 +158,13 @@ class DistanceTest(unittest.TestCase): with self.subTest(nm=nm): self.assertEqual(att, D.unit_attname(nm)) + def test_unit_att_name_invalid(self): + msg = "Unknown unit type: invalid-unit-name" + with self.assertRaisesMessage(AttributeError, msg): + D.unit_attname("invalid-unit-name") + with self.assertRaisesMessage(AttributeError, msg): + A.unit_attname("invalid-unit-name") + def test_hash(self): d1 = D(m=99) d2 = D(m=100)