blob: d216c301be02e7ba99f0b873f5efe16ac32dfdde [file] [log] [blame]
Michael W. Hudsonf0d777c2002-07-19 15:47:06 +00001# tests for slice objects; in particular the indices method.
2
Raymond Hettinger5d2e7772003-09-02 01:53:01 +00003import unittest
4from test import test_support
5
Michael W. Hudson173f11d2002-11-05 15:28:51 +00006import sys
Michael W. Hudsonf0d777c2002-07-19 15:47:06 +00007
Raymond Hettinger5d2e7772003-09-02 01:53:01 +00008class SliceTest(unittest.TestCase):
Michael W. Hudson173f11d2002-11-05 15:28:51 +00009
Raymond Hettinger5d2e7772003-09-02 01:53:01 +000010 def test_constructor(self):
11 self.assertRaises(TypeError, slice)
12 self.assertRaises(TypeError, slice, 1, 2, 3, 4)
13
14 def test_repr(self):
15 self.assertEqual(repr(slice(1, 2, 3)), "slice(1, 2, 3)")
16
17 def test_cmp(self):
18 s1 = slice(1, 2, 3)
19 s2 = slice(1, 2, 3)
20 s3 = slice(1, 2, 4)
21 self.assertEqual(s1, s2)
22 self.assertNotEqual(s1, s3)
23
24 class Exc(Exception):
25 pass
26
27 class BadCmp(object):
28 def __eq__(self, other):
29 raise Exc
30
31 s1 = slice(BadCmp())
32 s2 = slice(BadCmp())
33 self.assertRaises(Exc, cmp, s1, s2)
34 self.assertEqual(s1, s1)
35
36 s1 = slice(1, BadCmp())
37 s2 = slice(1, BadCmp())
38 self.assertEqual(s1, s1)
39 self.assertRaises(Exc, cmp, s1, s2)
40
41 s1 = slice(1, 2, BadCmp())
42 s2 = slice(1, 2, BadCmp())
43 self.assertEqual(s1, s1)
44 self.assertRaises(Exc, cmp, s1, s2)
45
46 def test_members(self):
47 s = slice(1)
48 self.assertEqual(s.start, None)
49 self.assertEqual(s.stop, 1)
50 self.assertEqual(s.step, None)
51
52 s = slice(1, 2)
53 self.assertEqual(s.start, 1)
54 self.assertEqual(s.stop, 2)
55 self.assertEqual(s.step, None)
56
57 s = slice(1, 2, 3)
58 self.assertEqual(s.start, 1)
59 self.assertEqual(s.stop, 2)
60 self.assertEqual(s.step, 3)
61
62 class AnyClass:
63 pass
64
65 obj = AnyClass()
66 s = slice(obj)
67 self.assert_(s.stop is obj)
68
69 def test_indices(self):
70 self.assertEqual(slice(None ).indices(10), (0, 10, 1))
71 self.assertEqual(slice(None, None, 2).indices(10), (0, 10, 2))
72 self.assertEqual(slice(1, None, 2).indices(10), (1, 10, 2))
73 self.assertEqual(slice(None, None, -1).indices(10), (9, -1, -1))
74 self.assertEqual(slice(None, None, -2).indices(10), (9, -1, -2))
75 self.assertEqual(slice(3, None, -2).indices(10), (3, -1, -2))
76 self.assertEqual(
77 slice(-100, 100 ).indices(10),
78 slice(None).indices(10)
79 )
80 self.assertEqual(
81 slice(100, -100, -1).indices(10),
82 slice(None, None, -1).indices(10)
83 )
84 self.assertEqual(slice(-100L, 100L, 2L).indices(10), (0, 10, 2))
85
86 self.assertEqual(range(10)[::sys.maxint - 1], [0])
87
88 self.assertRaises(OverflowError, slice(None).indices, 1L<<100)
89
90def test_main():
91 test_support.run_unittest(SliceTest)
92
93if __name__ == "__main__":
94 test_main()