tests: Test extremes of range() and document differences to CPython.

This avoids remaining buggy cases where C signed overflow occurs.

Signed-off-by: Jeff Epler <jepler@gmail.com>
This commit is contained in:
Jeff Epler
2025-07-15 16:05:42 +01:00
committed by Damien George
parent b44c4de4fd
commit 7be82f8b7c
2 changed files with 64 additions and 0 deletions

View File

@@ -0,0 +1,38 @@
try:
from sys import maxsize
except ImportError:
print("SKIP")
raise SystemExit
# Test the range builtin at extreme values. (https://github.com/micropython/micropython/issues/17684)
#
# This is written using asserts instead of prints because the value of `maxsize` differs.
#
# Numbers & counts right up against the max of mp_int_t also cause overflows, such as
# objrange.c:115:14: runtime error: signed integer overflow: 9223372036854775807 + 1 cannot be represented in type 'long int'
# so just avoid them for the purposes of this test.
r = range(-maxsize + 1, -1)
assert r.start == -maxsize + 1
assert r.stop == -1
assert r[0] == -maxsize + 1
assert r[1] == -maxsize + 2
assert r[-1] == -2
assert r[-2] == -3
ir = iter(r)
assert next(ir) == -maxsize + 1
assert next(ir) == -maxsize + 2
r = range(0, maxsize - 1)
assert len(r) == maxsize - 1
assert r.stop == maxsize - 1
r = range(maxsize, 0, -1)
assert len(r) == maxsize
assert r.start == maxsize
assert r[0] == maxsize
assert r[1] == maxsize - 1
ir = iter(r)
assert next(ir) == maxsize
assert next(ir) == maxsize - 1

View File

@@ -0,0 +1,26 @@
"""
categories: Types,range
description: Range objects with large start or stop arguments misbehave.
cause: Intermediate calculations overflow the C mp_int_t type
workaround: Avoid using such ranges
"""
from sys import maxsize
# A range including `maxsize-1` cannot be created
try:
print(range(-maxsize - 1, 0))
except OverflowError:
print("OverflowError")
# A range with `stop-start` exceeding sys.maxsize has incorrect len(), while CPython cannot calculate len().
try:
print(len(range(-maxsize, maxsize)))
except OverflowError:
print("OverflowError")
# A range with `stop-start` exceeding sys.maxsize has incorrect len()
try:
print(len(range(-maxsize, maxsize, maxsize)))
except OverflowError:
print("OverflowError")