Skip to content

Commit

Permalink
pythongh-93575: Correctly calculate NULL bytes in test_raiseMemError
Browse files Browse the repository at this point in the history
  • Loading branch information
tiran committed Jun 7, 2022
1 parent f012df7 commit 8e89228
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
15 changes: 11 additions & 4 deletions Lib/test/test_unicode.py
Original file line number Diff line number Diff line change
Expand Up @@ -2370,9 +2370,10 @@ def test_expandtabs_optimization(self):
self.assertIs(s.expandtabs(), s)

def test_raiseMemError(self):
null_byte = 1
ascii_struct_size = sys.getsizeof("a") - len("a") - null_byte
compact_struct_size = sys.getsizeof("\xff") - len("\xff") - null_byte
# Note: null byte subtracted later once we know char size
# (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self)
ascii_struct_size = sys.getsizeof("a") - len("a")
compact_struct_size = sys.getsizeof("\xff") - len("\xff")

for char in ('a', '\xe9', '\u20ac', '\U0010ffff'):
code = ord(char)
Expand All @@ -2385,12 +2386,18 @@ def test_raiseMemError(self):
else:
char_size = 4 # sizeof(Py_UCS4)
struct_size = compact_struct_size
struct_size -= char_size # space for NULL byte(s)
# Note: sys.maxsize is half of the actual max allocation because of
# the signedness of Py_ssize_t. Strings of maxlen-1 should in principle
# be allocatable, given enough memory.
maxlen = ((sys.maxsize - struct_size) // char_size)
alloc = lambda: char * maxlen
with self.subTest(char=char):
with self.subTest(
char=char,
maxlen=maxlen,
struct_size=struct_size,
char_size=char_size
):
self.assertRaises(MemoryError, alloc)
self.assertRaises(MemoryError, alloc)

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
test_unicode test_raiseMemError now correctly calculates size of NULL byte(s).

0 comments on commit 8e89228

Please sign in to comment.