diff options
author | Daniel Pope <lordmauve@users.noreply.github.com> | 2025-03-12 10:40:11 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2025-03-12 10:40:11 (GMT) |
commit | e0637cebe5bf863897f2e89dfcb76be0015c1877 (patch) | |
tree | 54f308a209c3f9ff3210df7a55450ed5e84df7cf /Lib/test/test_bytes.py | |
parent | 405a2d74cbdef5a899c900b6897ec85fe465abd2 (diff) | |
download | cpython-e0637cebe5bf863897f2e89dfcb76be0015c1877.zip cpython-e0637cebe5bf863897f2e89dfcb76be0015c1877.tar.gz cpython-e0637cebe5bf863897f2e89dfcb76be0015c1877.tar.bz2 |
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>
Diffstat (limited to 'Lib/test/test_bytes.py')
-rw-r--r-- | Lib/test/test_bytes.py | 23 |
1 files changed, 22 insertions, 1 deletions
diff --git a/Lib/test/test_bytes.py b/Lib/test/test_bytes.py index f6ffe83..d5490a2 100644 --- a/Lib/test/test_bytes.py +++ b/Lib/test/test_bytes.py @@ -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') |