From 81e9810428f49fcb470255d2a80c7d2a90e206fc Mon Sep 17 00:00:00 2001 From: Raphael Fakhri <153192858+RaphaelFakhri@users.noreply.github.com> Date: Wed, 4 Nov 2026 06:35:01 +0000 Subject: [PATCH] gh-139122: Fix the C UUID error message for badly formed hex strings --- Lib/test/test_uuid.py | 16 ++++++++++++++++ Modules/_uuidmodule.c | 14 ++++++++------ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/Lib/test/test_uuid.py b/Lib/test/test_uuid.py index fb278b6c4044c2..9b066e3e32d333 100755 --- a/Lib/test/test_uuid.py +++ b/Lib/test/test_uuid.py @@ -311,6 +311,22 @@ def __str__(self): self.assertEqual(repr(CustomUUID(int=1)), "CustomUUID('custom uuid')") + def test_bad_hex_error_message(self): + # A hex string that does not hold exactly 32 hex digits raises the + # same error message in the C and Python implementations. + for text in ('', + '1234567812345678123456781234567', + '123456781234567812345678123456789', + '{123456781234567812345678123456789}', + '12345678-1234-5678-1234-567812345678-9', + '12345678-1234-5678-1234-56781234567', + '12345678-1234-5678-1234-5678123456'): + with self.subTest(text=text): + with self.assertRaises(ValueError) as cm: + self.uuid.UUID(text) + self.assertEqual(str(cm.exception), + 'badly formed hexadecimal UUID string') + def test_exceptions(self): badvalue = lambda f: self.assertRaises(ValueError, f) badtype = lambda f: self.assertRaises(TypeError, f) diff --git a/Modules/_uuidmodule.c b/Modules/_uuidmodule.c index e957071a4ecef9..4acfbc59bc3212 100644 --- a/Modules/_uuidmodule.c +++ b/Modules/_uuidmodule.c @@ -738,17 +738,19 @@ from_hex(uuidobject *self, PyObject *hex) } if (j > UUID_SIZE || (j == UUID_SIZE && acc_set)) { - PyErr_Format(PyExc_ValueError, - "invalid UUID '%s': decodes to more than 16 bytes", - hex); + PyErr_SetString( + PyExc_ValueError, + "badly formed hexadecimal UUID string" + ); return -1; } } if (j != UUID_SIZE) { - PyErr_Format(PyExc_ValueError, - "invalid UUID '%s': decodes to less than 16 bytes", - hex); + PyErr_SetString( + PyExc_ValueError, + "badly formed hexadecimal UUID string" + ); return -1; }