gh-129349: Accept bytes in bytes.fromhex()/bytearray.fromhex() (#129844)

Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
Co-authored-by: Victor Stinner <vstinner@python.org>
This commit is contained in:
Daniel Pope 2025-03-12 10:40:11 +00:00 committed by GitHub
parent 405a2d74cb
commit e0637cebe5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 90 additions and 69 deletions

View file

@ -450,13 +450,34 @@ class BaseBytesTest:
# check that ASCII whitespace is ignored
self.assertEqual(self.type2test.fromhex(' 1A\n2B\t30\v'), b)
self.assertEqual(self.type2test.fromhex(b' 1A\n2B\t30\v'), b)
for c in "\x09\x0A\x0B\x0C\x0D\x20":
self.assertEqual(self.type2test.fromhex(c), self.type2test())
for c in "\x1C\x1D\x1E\x1F\x85\xa0\u2000\u2002\u2028":
self.assertRaises(ValueError, self.type2test.fromhex, c)
# Check that we can parse bytes and bytearray
tests = [
("bytes", bytes),
("bytearray", bytearray),
("memoryview", memoryview),
("array.array", lambda bs: array.array('B', bs)),
]
for name, factory in tests:
with self.subTest(name=name):
self.assertEqual(self.type2test.fromhex(factory(b' 1A 2B 30 ')), b)
# Invalid bytes are rejected
for u8 in b"\0\x1C\x1D\x1E\x1F\x85\xa0":
b = bytes([30, 31, u8])
self.assertRaises(ValueError, self.type2test.fromhex, b)
self.assertEqual(self.type2test.fromhex('0000'), b'\0\0')
self.assertRaises(TypeError, self.type2test.fromhex, b'1B')
with self.assertRaisesRegex(
TypeError,
r'fromhex\(\) argument must be str or bytes-like, not tuple',
):
self.type2test.fromhex(())
self.assertRaises(ValueError, self.type2test.fromhex, 'a')
self.assertRaises(ValueError, self.type2test.fromhex, 'rt')
self.assertRaises(ValueError, self.type2test.fromhex, '1a b cd')