4 from test
import test_support
7 'Sequence using __getitem__'
8 def __init__(self
, seqn
):
10 def __getitem__(self
, i
):
14 'Sequence using iterator protocol'
15 def __init__(self
, seqn
):
21 if self
.i
>= len(self
.seqn
): raise StopIteration
27 'Sequence using iterator protocol defined with a generator'
28 def __init__(self
, seqn
):
36 'Missing __getitem__ and __iter__'
37 def __init__(self
, seqn
):
41 if self
.i
>= len(self
.seqn
): raise StopIteration
47 'Test propagation of exceptions'
48 def __init__(self
, seqn
):
57 'Iterator missing next()'
58 def __init__(self
, seqn
):
64 class EnumerateTestCase(unittest
.TestCase
):
67 seq
, res
= 'abc', [(0,'a'), (1,'b'), (2,'c')]
69 def test_basicfunction(self
):
70 self
.assertEqual(type(self
.enum(self
.seq
)), self
.enum
)
71 e
= self
.enum(self
.seq
)
72 self
.assertEqual(iter(e
), e
)
73 self
.assertEqual(list(self
.enum(self
.seq
)), self
.res
)
76 def test_getitemseqn(self
):
77 self
.assertEqual(list(self
.enum(G(self
.seq
))), self
.res
)
79 self
.assertRaises(StopIteration, e
.next
)
81 def test_iteratorseqn(self
):
82 self
.assertEqual(list(self
.enum(I(self
.seq
))), self
.res
)
84 self
.assertRaises(StopIteration, e
.next
)
86 def test_iteratorgenerator(self
):
87 self
.assertEqual(list(self
.enum(Ig(self
.seq
))), self
.res
)
89 self
.assertRaises(StopIteration, e
.next
)
91 def test_noniterable(self
):
92 self
.assertRaises(TypeError, self
.enum
, X(self
.seq
))
94 def test_illformediterable(self
):
95 self
.assertRaises(TypeError, list, self
.enum(N(self
.seq
)))
97 def test_exception_propagation(self
):
98 self
.assertRaises(ZeroDivisionError, list, self
.enum(E(self
.seq
)))
100 def test_argumentcheck(self
):
101 self
.assertRaises(TypeError, self
.enum
) # no arguments
102 self
.assertRaises(TypeError, self
.enum
, 1) # wrong type (not iterable)
103 self
.assertRaises(TypeError, self
.enum
, 'abc', 2) # too many arguments
105 def test_tuple_reuse(self
):
106 # Tests an implementation detail where tuple is reused
107 # whenever nothing else holds a reference to it
108 self
.assertEqual(len(Set(map(id, list(enumerate(self
.seq
))))), len(self
.seq
))
109 self
.assertEqual(len(Set(map(id, enumerate(self
.seq
)))), min(1,len(self
.seq
)))
111 class MyEnum(enumerate):
114 class SubclassTestCase(EnumerateTestCase
):
118 class TestEmpty(EnumerateTestCase
):
122 class TestBig(EnumerateTestCase
):
124 seq
= range(10,20000,2)
125 res
= zip(range(20000), seq
)
128 def test_main(verbose
=None):
129 testclasses
= (EnumerateTestCase
, SubclassTestCase
, TestEmpty
, TestBig
)
130 test_support
.run_unittest(*testclasses
)
132 # verify reference counting
134 if verbose
and hasattr(sys
, "gettotalrefcount"):
136 for i
in xrange(len(counts
)):
137 test_support
.run_unittest(*testclasses
)
138 counts
[i
] = sys
.gettotalrefcount()
141 if __name__
== "__main__":
142 test_main(verbose
=True)