mirror of
https://github.com/micropython/micropython.git
synced 2026-01-05 03:30:14 +01:00
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:
committed by
Damien George
parent
b44c4de4fd
commit
7be82f8b7c
38
tests/basics/builtin_range_maxsize.py
Normal file
38
tests/basics/builtin_range_maxsize.py
Normal 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
|
||||
26
tests/cpydiff/types_range_limits.py
Normal file
26
tests/cpydiff/types_range_limits.py
Normal 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")
|
||||
Reference in New Issue
Block a user