PageRenderTime 46ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/test/test_enumerate.py

https://github.com/rpattabi/ironruby
Python | 262 lines | 224 code | 33 blank | 5 comment | 17 complexity | df92487d094fb9df362794e8b6c6fc6d MD5 | raw file
  1. import unittest
  2. import sys
  3. from test import test_support
  4. class G:
  5. 'Sequence using __getitem__'
  6. def __init__(self, seqn):
  7. self.seqn = seqn
  8. def __getitem__(self, i):
  9. return self.seqn[i]
  10. class I:
  11. 'Sequence using iterator protocol'
  12. def __init__(self, seqn):
  13. self.seqn = seqn
  14. self.i = 0
  15. def __iter__(self):
  16. return self
  17. def next(self):
  18. if self.i >= len(self.seqn): raise StopIteration
  19. v = self.seqn[self.i]
  20. self.i += 1
  21. return v
  22. class Ig:
  23. 'Sequence using iterator protocol defined with a generator'
  24. def __init__(self, seqn):
  25. self.seqn = seqn
  26. self.i = 0
  27. def __iter__(self):
  28. for val in self.seqn:
  29. yield val
  30. class X:
  31. 'Missing __getitem__ and __iter__'
  32. def __init__(self, seqn):
  33. self.seqn = seqn
  34. self.i = 0
  35. def next(self):
  36. if self.i >= len(self.seqn): raise StopIteration
  37. v = self.seqn[self.i]
  38. self.i += 1
  39. return v
  40. class E:
  41. 'Test propagation of exceptions'
  42. def __init__(self, seqn):
  43. self.seqn = seqn
  44. self.i = 0
  45. def __iter__(self):
  46. return self
  47. def next(self):
  48. 3 // 0
  49. class N:
  50. 'Iterator missing next()'
  51. def __init__(self, seqn):
  52. self.seqn = seqn
  53. self.i = 0
  54. def __iter__(self):
  55. return self
  56. class EnumerateTestCase(unittest.TestCase):
  57. enum = enumerate
  58. seq, res = 'abc', [(0,'a'), (1,'b'), (2,'c')]
  59. def test_basicfunction(self):
  60. self.assertEqual(type(self.enum(self.seq)), self.enum)
  61. e = self.enum(self.seq)
  62. self.assertEqual(iter(e), e)
  63. self.assertEqual(list(self.enum(self.seq)), self.res)
  64. self.enum.__doc__
  65. def test_getitemseqn(self):
  66. self.assertEqual(list(self.enum(G(self.seq))), self.res)
  67. e = self.enum(G(''))
  68. self.assertRaises(StopIteration, e.next)
  69. def test_iteratorseqn(self):
  70. self.assertEqual(list(self.enum(I(self.seq))), self.res)
  71. e = self.enum(I(''))
  72. self.assertRaises(StopIteration, e.next)
  73. def test_iteratorgenerator(self):
  74. self.assertEqual(list(self.enum(Ig(self.seq))), self.res)
  75. e = self.enum(Ig(''))
  76. self.assertRaises(StopIteration, e.next)
  77. def test_noniterable(self):
  78. self.assertRaises(TypeError, self.enum, X(self.seq))
  79. def test_illformediterable(self):
  80. self.assertRaises(TypeError, list, self.enum(N(self.seq)))
  81. def test_exception_propagation(self):
  82. self.assertRaises(ZeroDivisionError, list, self.enum(E(self.seq)))
  83. def test_argumentcheck(self):
  84. self.assertRaises(TypeError, self.enum) # no arguments
  85. self.assertRaises(TypeError, self.enum, 1) # wrong type (not iterable)
  86. self.assertRaises(TypeError, self.enum, 'abc', 'a') # wrong type
  87. self.assertRaises(TypeError, self.enum, 'abc', 2, 3) # too many arguments
  88. @test_support.cpython_only
  89. def test_tuple_reuse(self):
  90. if test_support.due_to_ironpython_incompatibility("implementation detail: http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=20279"):
  91. return
  92. # Tests an implementation detail where tuple is reused
  93. # whenever nothing else holds a reference to it
  94. self.assertEqual(len(set(map(id, list(enumerate(self.seq))))), len(self.seq))
  95. self.assertEqual(len(set(map(id, enumerate(self.seq)))), min(1,len(self.seq)))
  96. class MyEnum(enumerate):
  97. pass
  98. class SubclassTestCase(EnumerateTestCase):
  99. enum = MyEnum
  100. class TestEmpty(EnumerateTestCase):
  101. seq, res = '', []
  102. class TestBig(EnumerateTestCase):
  103. seq = range(10,20000,2)
  104. res = zip(range(20000), seq)
  105. class TestReversed(unittest.TestCase):
  106. def test_simple(self):
  107. class A:
  108. def __getitem__(self, i):
  109. if i < 5:
  110. return str(i)
  111. raise StopIteration
  112. def __len__(self):
  113. return 5
  114. for data in 'abc', range(5), tuple(enumerate('abc')), A(), xrange(1,17,5):
  115. self.assertEqual(list(data)[::-1], list(reversed(data)))
  116. self.assertRaises(TypeError, reversed, {})
  117. # don't allow keyword arguments
  118. self.assertRaises(TypeError, reversed, [], a=1)
  119. def test_classic_class(self):
  120. class A:
  121. def __reversed__(self):
  122. return [2, 1]
  123. self.assertEqual(list(reversed(A())), [2, 1])
  124. def test_xrange_optimization(self):
  125. x = xrange(1)
  126. self.assertEqual(type(reversed(x)), type(iter(x)))
  127. @test_support.cpython_only
  128. def test_len(self):
  129. if test_support.due_to_ironpython_incompatibility("implementation detail"):
  130. return
  131. # This is an implementation detail, not an interface requirement
  132. from test.test_iterlen import len
  133. for s in ('hello', tuple('hello'), list('hello'), xrange(5)):
  134. self.assertEqual(len(reversed(s)), len(s))
  135. r = reversed(s)
  136. list(r)
  137. self.assertEqual(len(r), 0)
  138. class SeqWithWeirdLen:
  139. called = False
  140. def __len__(self):
  141. if not self.called:
  142. self.called = True
  143. return 10
  144. raise ZeroDivisionError
  145. def __getitem__(self, index):
  146. return index
  147. r = reversed(SeqWithWeirdLen())
  148. self.assertRaises(ZeroDivisionError, len, r)
  149. def test_gc(self):
  150. class Seq:
  151. def __len__(self):
  152. return 10
  153. def __getitem__(self, index):
  154. return index
  155. s = Seq()
  156. r = reversed(s)
  157. s.r = r
  158. def test_args(self):
  159. self.assertRaises(TypeError, reversed)
  160. self.assertRaises(TypeError, reversed, [], 'extra')
  161. def test_bug1229429(self):
  162. if test_support.due_to_ironpython_incompatibility("implementation detail"):
  163. return
  164. # this bug was never in reversed, it was in
  165. # PyObject_CallMethod, and reversed_new calls that sometimes.
  166. if not hasattr(sys, "getrefcount"):
  167. return
  168. def f():
  169. pass
  170. r = f.__reversed__ = object()
  171. rc = sys.getrefcount(r)
  172. for i in range(10):
  173. try:
  174. reversed(f)
  175. except TypeError:
  176. pass
  177. else:
  178. self.fail("non-callable __reversed__ didn't raise!")
  179. self.assertEqual(rc, sys.getrefcount(r))
  180. def test_objmethods(self):
  181. # Objects must have __len__() and __getitem__() implemented.
  182. class NoLen(object):
  183. def __getitem__(self): return 1
  184. nl = NoLen()
  185. self.assertRaises(TypeError, reversed, nl)
  186. class NoGetItem(object):
  187. def __len__(self): return 2
  188. ngi = NoGetItem()
  189. self.assertRaises(TypeError, reversed, ngi)
  190. class EnumerateStartTestCase(EnumerateTestCase):
  191. def test_basicfunction(self):
  192. e = self.enum(self.seq)
  193. self.assertEqual(iter(e), e)
  194. self.assertEqual(list(self.enum(self.seq)), self.res)
  195. if not test_support.due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/27656"):
  196. class TestStart(EnumerateStartTestCase):
  197. enum = lambda self, i: enumerate(i, start=11)
  198. seq, res = 'abc', [(11, 'a'), (12, 'b'), (13, 'c')]
  199. class TestLongStart(EnumerateStartTestCase):
  200. enum = lambda self, i: enumerate(i, start=sys.maxint+1)
  201. seq, res = 'abc', [(sys.maxint+1,'a'), (sys.maxint+2,'b'),
  202. (sys.maxint+3,'c')]
  203. def test_main(verbose=None):
  204. test_support.run_unittest(__name__)
  205. # verify reference counting
  206. if verbose and hasattr(sys, "gettotalrefcount"):
  207. counts = [None] * 5
  208. for i in xrange(len(counts)):
  209. test_support.run_unittest(__name__)
  210. counts[i] = sys.gettotalrefcount()
  211. print counts
  212. if __name__ == "__main__":
  213. test_main(verbose=True)