PageRenderTime 49ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/Languages/IronPython/Tests/test_iterator.py

http://github.com/IronLanguages/main
Python | 273 lines | 235 code | 23 blank | 15 comment | 8 complexity | a2fb0f2e087dfdc5e40b0627a2e9c41b MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception
  1. #####################################################################################
  2. #
  3. # Copyright (c) Microsoft Corporation. All rights reserved.
  4. #
  5. # This source code is subject to terms and conditions of the Apache License, Version 2.0. A
  6. # copy of the license can be found in the License.html file at the root of this distribution. If
  7. # you cannot locate the Apache License, Version 2.0, please send an email to
  8. # ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
  9. # by the terms of the Apache License, Version 2.0.
  10. #
  11. # You must not remove this notice, or any other, from this software.
  12. #
  13. #
  14. #####################################################################################
  15. from iptest.assert_util import *
  16. class It:
  17. x = 0
  18. a = ()
  19. def __init__(self, a):
  20. self.x = 0
  21. self.a = a
  22. def next(self):
  23. if self.x <= 9:
  24. self.x = self.x+1
  25. return self.a[self.x-1]
  26. else:
  27. raise StopIteration
  28. def __iter__(self):
  29. return self
  30. class Iterator:
  31. x = 0
  32. a = (1,2,3,4,5,6,7,8,9,0)
  33. def __iter__(self):
  34. return It(self.a)
  35. class Indexer:
  36. a = (1,2,3,4,5,6,7,8,9,0)
  37. def __getitem__(self, i):
  38. if i < len(self.a):
  39. return self.a[i]
  40. else:
  41. raise IndexError
  42. i = Iterator()
  43. for j in i:
  44. Assert(j in i)
  45. Assert(1 in i)
  46. Assert(2 in i)
  47. Assert(not (10 in i))
  48. i = Indexer()
  49. for j in i:
  50. Assert(j in i)
  51. Assert(1 in i)
  52. Assert(2 in i)
  53. Assert(not (10 in i))
  54. # Testing the iter(o,s) function
  55. class Iter:
  56. x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
  57. index = -1
  58. it = Iter()
  59. def f():
  60. it.index += 1
  61. return it.x[it.index]
  62. y = []
  63. for i in iter(f, 14):
  64. y.append(i)
  65. Assert(y == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])
  66. y = ['1']
  67. y += Iterator()
  68. Assert(y == ['1', 1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
  69. y = ['1']
  70. y += Indexer()
  71. Assert(y == ['1', 1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
  72. AssertErrorWithMessages(TypeError, "iter() takes at least 1 argument (0 given)",
  73. "iter expected at least 1 arguments, got 0", iter)
  74. def test_itertools_same_value():
  75. from itertools import izip
  76. x = iter(range(4))
  77. AreEqual([(i,j) for i,j in izip(x,x)], [(0, 1), (2, 3)])
  78. def test_itertools_islice_end():
  79. """islice shouldn't consume values after the limit specified by step"""
  80. from itertools import izip, islice
  81. # create a zipped iterator w/ odd number of values...
  82. it = izip([2,3,4], [4,5,6])
  83. # slice in 2, turn that into a list...
  84. list(islice(it, 2))
  85. # we should still have the last value still present
  86. for x in it:
  87. AreEqual(x, (4,6))
  88. @skip("silverlight")
  89. def test_iterator_for():
  90. """test various iterable objects with multiple incomplete iterations"""
  91. def generator():
  92. yield 0
  93. yield 1
  94. from cStringIO import StringIO
  95. strO = StringIO()
  96. strO.write('abc\n')
  97. strO.write('def')
  98. strI = StringIO('abc\ndef')
  99. import sys
  100. fi = sys.float_info
  101. d = {2:3, 3:4}
  102. l = [2, 3]
  103. s = set([2, 3, 4])
  104. if not is_silverlight:
  105. f = file('test_file.txt', 'w+')
  106. f.write('abc\n')
  107. f.write('def')
  108. f.close()
  109. f = file('test_file.txt')
  110. import os
  111. stat = os.stat(__file__)
  112. class x(object):
  113. abc = 2
  114. bcd = 3
  115. dictproxy = x.__dict__
  116. dictlist = list(x.__dict__)
  117. ba = bytearray(b'abc')
  118. try:
  119. # iterator, first Value, second Value
  120. iterators = [
  121. # objects which when enumerated multiple times continue
  122. (generator(), 0, 1),
  123. (strI, 'abc\n', 'def'),
  124. (strO, 'abc\n', 'def'),
  125. # objects which when enumerated multiple times reset
  126. (xrange(10), 0, 0),
  127. ([0, 1], 0, 0),
  128. ((0, 1), 0, 0),
  129. (fi, fi[0], fi[0]),
  130. (b'abc', b'a', b'a'),
  131. (ba, ord(b'a'), ord(b'a')),
  132. (u'abc', u'a', u'a'),
  133. (d, list(d)[0], list(d)[0]),
  134. (l, l[0], l[0]),
  135. (s, list(s)[0], list(s)[0]),
  136. (dictproxy, dictlist[0], dictlist[0]),
  137. ]
  138. if not is_silverlight:
  139. iterators.append((f, 'abc\n', 'def'))
  140. iterators.append((stat, stat[0], stat[0]))
  141. for iterator, res0, res1 in iterators:
  142. for x in iterator:
  143. AreEqual(x, res0)
  144. break
  145. for x in iterator:
  146. AreEqual(x, res1)
  147. break
  148. finally:
  149. f.close()
  150. os.unlink('test_file.txt')
  151. def test_iterator_closed_file():
  152. cf = file(__file__)
  153. cf.close()
  154. def f():
  155. for x in cf: pass
  156. AssertError(ValueError, f)
  157. def test_no_return_self_in_iter():
  158. class A(object):
  159. def __iter__(cls):
  160. return 1
  161. def next(cls):
  162. return 2
  163. a = A()
  164. AreEqual(next(a), 2)
  165. def test_no_iter():
  166. class A(object):
  167. def next(cls):
  168. return 2
  169. a = A()
  170. AreEqual(next(a), 2)
  171. def test_with_iter():
  172. class A(object):
  173. def __iter__(cls):
  174. return cls
  175. def next(self):
  176. return 2
  177. a = A()
  178. AreEqual(next(a), 2)
  179. def test_with_iter_next_in_init():
  180. class A(object):
  181. def __init__(cls):
  182. AreEqual(next(cls), 2)
  183. AreEqual(cls.next(), 2)
  184. def __iter__(cls):
  185. return cls
  186. def next(cls):
  187. return 2
  188. a = A()
  189. AreEqual(next(a), 2)
  190. def test_interacting_iterators():
  191. """This test is similar to how Jinga2 fails."""
  192. class A(object):
  193. def __iter__(cls):
  194. return cls
  195. def next(self):
  196. return 3
  197. class B(object):
  198. def __iter__(cls):
  199. return A()
  200. def next(self):
  201. return 2
  202. b = B()
  203. AreEqual(next(b), 2)
  204. def test_call_to_iter_or_next():
  205. class A(object):
  206. def __iter__(cls):
  207. Assert(False, "__iter__ should not be called.")
  208. return cls
  209. def next(self):
  210. return 2
  211. a = A()
  212. AreEqual(next(a), 2)
  213. run_test(__name__)