diff --git a/Lib/test/test_range.py b/Lib/test/test_range.py index 106c732dd97..c022f070bf5 100644 --- a/Lib/test/test_range.py +++ b/Lib/test/test_range.py @@ -493,6 +493,35 @@ class RangeTest(unittest.TestCase): test_id = "reversed(range({}, {}, {}))".format(start, end, step) self.assert_iterators_equal(iter1, iter2, test_id, limit=100) + @test.support.cpython_only + def test_range_iterator_invocation(self): + import _testcapi + rangeiter_type = type(iter(range(0))) + + # rangeiter_new doesn't take keyword arguments + with self.assertRaises(TypeError): + rangeiter_type(a=1) + + # rangeiter_new takes exactly 3 arguments + self.assertRaises(TypeError, rangeiter_type) + self.assertRaises(TypeError, rangeiter_type, 1) + self.assertRaises(TypeError, rangeiter_type, 1, 1) + self.assertRaises(TypeError, rangeiter_type, 1, 1, 1, 1) + + # start, stop and stop must fit in C long + for good_val in [_testcapi.LONG_MAX, _testcapi.LONG_MIN]: + rangeiter_type(good_val, good_val, good_val) + for bad_val in [_testcapi.LONG_MAX + 1, _testcapi.LONG_MIN - 1]: + self.assertRaises(OverflowError, + rangeiter_type, bad_val, 1, 1) + self.assertRaises(OverflowError, + rangeiter_type, 1, bad_val, 1) + self.assertRaises(OverflowError, + rangeiter_type, 1, 1, bad_val) + + # step mustn't be zero + self.assertRaises(ValueError, rangeiter_type, 1, 1, 0) + def test_slice(self): def check(start, stop, step=None): i = slice(start, stop, step) diff --git a/Misc/NEWS b/Misc/NEWS index 91681976c84..aed3a2990d0 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -10,6 +10,9 @@ Release date: TBA Core and Builtins ----------------- +- Issue #28376: The constructor of range_iterator now checks that step is not 0. + Patch by Oren Milman. + - Issue #26906: Resolving special methods of uninitialized type now causes implicit initialization of the type instead of a fail. diff --git a/Objects/rangeobject.c b/Objects/rangeobject.c index 288be4fb693..899697aa3a1 100644 --- a/Objects/rangeobject.c +++ b/Objects/rangeobject.c @@ -937,12 +937,20 @@ rangeiter_new(PyTypeObject *type, PyObject *args, PyObject *kw) { long start, stop, step; - if (!_PyArg_NoKeywords("rangeiter()", kw)) + if (!_PyArg_NoKeywords("range_iterator()", kw)) { return NULL; + } - if (!PyArg_ParseTuple(args, "lll;rangeiter() requires 3 int arguments", - &start, &stop, &step)) + if (!PyArg_ParseTuple(args, + "lll;range_iterator() requires 3 int arguments", + &start, &stop, &step)) { return NULL; + } + if (step == 0) { + PyErr_SetString(PyExc_ValueError, + "range_iterator() arg 3 must not be zero"); + return NULL; + } return fast_range_iter(start, stop, step); }