Home | History | Annotate | Download | only in test
      1 # Python test set -- built-in functions
      2 
      3 import test.test_support, unittest
      4 import sys
      5 import pickle
      6 import itertools
      7 
      8 import warnings
      9 warnings.filterwarnings("ignore", "integer argument expected",
     10                         DeprecationWarning, "unittest")
     11 
     12 # pure Python implementations (3 args only), for comparison
     13 def pyrange(start, stop, step):
     14     if (start - stop) // step < 0:
     15         # replace stop with next element in the sequence of integers
     16         # that are congruent to start modulo step.
     17         stop += (start - stop) % step
     18         while start != stop:
     19             yield start
     20             start += step
     21 
     22 def pyrange_reversed(start, stop, step):
     23     stop += (start - stop) % step
     24     return pyrange(stop - step, start - step, -step)
     25 
     26 
     27 class XrangeTest(unittest.TestCase):
     28     def assert_iterators_equal(self, xs, ys, test_id, limit=None):
     29         # check that an iterator xs matches the expected results ys,
     30         # up to a given limit.
     31         if limit is not None:
     32             xs = itertools.islice(xs, limit)
     33             ys = itertools.islice(ys, limit)
     34         sentinel = object()
     35         pairs = itertools.izip_longest(xs, ys, fillvalue=sentinel)
     36         for i, (x, y) in enumerate(pairs):
     37             if x == y:
     38                 continue
     39             elif x == sentinel:
     40                 self.fail('{}: iterator ended unexpectedly '
     41                           'at position {}; expected {}'.format(test_id, i, y))
     42             elif y == sentinel:
     43                 self.fail('{}: unexpected excess element {} at '
     44                           'position {}'.format(test_id, x, i))
     45             else:
     46                 self.fail('{}: wrong element at position {};'
     47                           'expected {}, got {}'.format(test_id, i, y, x))
     48 
     49     def assert_xranges_equivalent(self, x, y):
     50         # Check that two xrange objects are equivalent, in the sense of the
     51         # associated sequences being the same.  We want to use this for large
     52         # xrange objects, so instead of converting to lists and comparing
     53         # directly we do a number of indirect checks.
     54         if len(x) != len(y):
     55             self.fail('{} and {} have different '
     56                       'lengths: {} and {} '.format(x, y, len(x), len(y)))
     57         if len(x) >= 1:
     58             if x[0] != y[0]:
     59                 self.fail('{} and {} have different initial '
     60                           'elements: {} and {} '.format(x, y, x[0], y[0]))
     61             if x[-1] != y[-1]:
     62                 self.fail('{} and {} have different final '
     63                           'elements: {} and {} '.format(x, y, x[-1], y[-1]))
     64         if len(x) >= 2:
     65             x_step = x[1] - x[0]
     66             y_step = y[1] - y[0]
     67             if x_step != y_step:
     68                 self.fail('{} and {} have different step: '
     69                           '{} and {} '.format(x, y, x_step, y_step))
     70 
     71     def test_xrange(self):
     72         self.assertEqual(list(xrange(3)), [0, 1, 2])
     73         self.assertEqual(list(xrange(1, 5)), [1, 2, 3, 4])
     74         self.assertEqual(list(xrange(0)), [])
     75         self.assertEqual(list(xrange(-3)), [])
     76         self.assertEqual(list(xrange(1, 10, 3)), [1, 4, 7])
     77         self.assertEqual(list(xrange(5, -5, -3)), [5, 2, -1, -4])
     78 
     79         a = 10
     80         b = 100
     81         c = 50
     82 
     83         self.assertEqual(list(xrange(a, a+2)), [a, a+1])
     84         self.assertEqual(list(xrange(a+2, a, -1L)), [a+2, a+1])
     85         self.assertEqual(list(xrange(a+4, a, -2)), [a+4, a+2])
     86 
     87         seq = list(xrange(a, b, c))
     88         self.assertIn(a, seq)
     89         self.assertNotIn(b, seq)
     90         self.assertEqual(len(seq), 2)
     91 
     92         seq = list(xrange(b, a, -c))
     93         self.assertIn(b, seq)
     94         self.assertNotIn(a, seq)
     95         self.assertEqual(len(seq), 2)
     96 
     97         seq = list(xrange(-a, -b, -c))
     98         self.assertIn(-a, seq)
     99         self.assertNotIn(-b, seq)
    100         self.assertEqual(len(seq), 2)
    101 
    102         self.assertRaises(TypeError, xrange)
    103         self.assertRaises(TypeError, xrange, 1, 2, 3, 4)
    104         self.assertRaises(ValueError, xrange, 1, 2, 0)
    105 
    106         self.assertRaises(OverflowError, xrange, 10**100, 10**101, 10**101)
    107 
    108         self.assertRaises(TypeError, xrange, 0, "spam")
    109         self.assertRaises(TypeError, xrange, 0, 42, "spam")
    110 
    111         self.assertEqual(len(xrange(0, sys.maxint, sys.maxint-1)), 2)
    112 
    113         self.assertRaises(OverflowError, xrange, -sys.maxint, sys.maxint)
    114         self.assertRaises(OverflowError, xrange, 0, 2*sys.maxint)
    115 
    116         r = xrange(-sys.maxint, sys.maxint, 2)
    117         self.assertEqual(len(r), sys.maxint)
    118         self.assertRaises(OverflowError, xrange, -sys.maxint-1, sys.maxint, 2)
    119 
    120     def test_pickling(self):
    121         testcases = [(13,), (0, 11), (-22, 10), (20, 3, -1),
    122                      (13, 21, 3), (-2, 2, 2)]
    123         for proto in range(pickle.HIGHEST_PROTOCOL + 1):
    124             for t in testcases:
    125                 r = xrange(*t)
    126                 self.assertEqual(list(pickle.loads(pickle.dumps(r, proto))),
    127                                  list(r))
    128 
    129         M = min(sys.maxint, sys.maxsize)
    130         large_testcases = testcases + [
    131             (0, M, 1),
    132             (M, 0, -1),
    133             (0, M, M - 1),
    134             (M // 2, M, 1),
    135             (0, -M, -1),
    136             (0, -M, 1 - M),
    137             (-M, M, 2),
    138             (-M, M, 1024),
    139             (-M, M, 10585),
    140             (M, -M, -2),
    141             (M, -M, -1024),
    142             (M, -M, -10585),
    143             ]
    144         for proto in range(pickle.HIGHEST_PROTOCOL + 1):
    145             for t in large_testcases:
    146                 r = xrange(*t)
    147                 r_out = pickle.loads(pickle.dumps(r, proto))
    148                 self.assert_xranges_equivalent(r_out, r)
    149 
    150     def test_repr(self):
    151         # Check that repr of an xrange is a valid representation
    152         # of that xrange.
    153 
    154         # Valid xranges have at most min(sys.maxint, sys.maxsize) elements.
    155         M = min(sys.maxint, sys.maxsize)
    156 
    157         testcases = [
    158             (13,),
    159             (0, 11),
    160             (-22, 10),
    161             (20, 3, -1),
    162             (13, 21, 3),
    163             (-2, 2, 2),
    164             (0, M, 1),
    165             (M, 0, -1),
    166             (0, M, M - 1),
    167             (M // 2, M, 1),
    168             (0, -M, -1),
    169             (0, -M, 1 - M),
    170             (-M, M, 2),
    171             (-M, M, 1024),
    172             (-M, M, 10585),
    173             (M, -M, -2),
    174             (M, -M, -1024),
    175             (M, -M, -10585),
    176             ]
    177         for t in testcases:
    178             r = xrange(*t)
    179             r_out = eval(repr(r))
    180             self.assert_xranges_equivalent(r, r_out)
    181 
    182     def test_range_iterators(self):
    183         # see issue 7298
    184         limits = [base + jiggle
    185                   for M in (2**32, 2**64)
    186                   for base in (-M, -M//2, 0, M//2, M)
    187                   for jiggle in (-2, -1, 0, 1, 2)]
    188         test_ranges = [(start, end, step)
    189                        for start in limits
    190                        for end in limits
    191                        for step in (-2**63, -2**31, -2, -1, 1, 2)]
    192 
    193         for start, end, step in test_ranges:
    194             try:
    195                 iter1 = xrange(start, end, step)
    196             except OverflowError:
    197                 pass
    198             else:
    199                 iter2 = pyrange(start, end, step)
    200                 test_id = "xrange({}, {}, {})".format(start, end, step)
    201                 # check first 100 entries
    202                 self.assert_iterators_equal(iter1, iter2, test_id, limit=100)
    203 
    204             try:
    205                 iter1 = reversed(xrange(start, end, step))
    206             except OverflowError:
    207                 pass
    208             else:
    209                 iter2 = pyrange_reversed(start, end, step)
    210                 test_id = "reversed(xrange({}, {}, {}))".format(start, end, step)
    211                 self.assert_iterators_equal(iter1, iter2, test_id, limit=100)
    212 
    213 
    214 def test_main():
    215     test.test_support.run_unittest(XrangeTest)
    216 
    217 if __name__ == "__main__":
    218     test_main()
    219