From 38cde27a89d6341722f4a7b434a1535a6fa9abb7 Mon Sep 17 00:00:00 2001 From: Andrew Northall Date: Sat, 24 Jun 2023 11:36:38 +0100 Subject: [PATCH] Fixed #34676 -- Normalized Distance()/Area() exceptions for nonexistent units. --- django/contrib/gis/measure.py | 6 ++---- tests/gis_tests/test_measure.py | 10 +++++++++- 2 files changed, 11 insertions(+), 5 deletions(-) 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)