gh-101410: support custom messages for domain errors in the math module (#124299)

This adds basic support to override default messages for domain errors
in the math_1() helper.  The sqrt(), atanh(), log2(), log10() and log()
functions were modified as examples.  New macro supports gradual
changing of error messages in other 1-arg functions.

Co-authored-by: CharlieZhao <zhaoyu_hit@qq.com>
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
This commit is contained in:
Sergey B Kirpichev 2025-01-23 16:55:25 +03:00 committed by GitHub
parent 25a614a502
commit 75f59bb629
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 109 additions and 29 deletions

View file

@ -2503,6 +2503,46 @@ class MathTests(unittest.TestCase):
self.assertRaises(TypeError, math.atan2, 1.0)
self.assertRaises(TypeError, math.atan2, 1.0, 2.0, 3.0)
def test_exception_messages(self):
x = -1.1
with self.assertRaisesRegex(ValueError,
f"expected a nonnegative input, got {x}"):
math.sqrt(x)
with self.assertRaisesRegex(ValueError,
f"expected a positive input, got {x}"):
math.log(x)
with self.assertRaisesRegex(ValueError,
f"expected a positive input, got {x}"):
math.log(123, x)
with self.assertRaisesRegex(ValueError,
f"expected a positive input, got {x}"):
math.log(x, 123)
with self.assertRaisesRegex(ValueError,
f"expected a positive input, got {x}"):
math.log2(x)
with self.assertRaisesRegex(ValueError,
f"expected a positive input, got {x}"):
math.log10(x)
x = decimal.Decimal('-1.1')
with self.assertRaisesRegex(ValueError,
f"expected a positive input, got {x}"):
math.log(x)
x = fractions.Fraction(1, 10**400)
with self.assertRaisesRegex(ValueError,
f"expected a positive input, got {float(x)}"):
math.log(x)
x = -123
with self.assertRaisesRegex(ValueError,
f"expected a positive input, got {x}"):
math.log(x)
with self.assertRaisesRegex(ValueError,
f"expected a float or nonnegative integer, got {x}"):
math.gamma(x)
x = 1.0
with self.assertRaisesRegex(ValueError,
f"expected a number between -1 and 1, got {x}"):
math.atanh(x)
# Custom assertions.
def assertIsNaN(self, value):