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

/Languages/IronPython/Tests/test_list.py

http://github.com/IronLanguages/main
Python | 456 lines | 412 code | 24 blank | 20 comment | 3 complexity | fbb9a35d6866c991dd1356ba60418048 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. def test_extend_self():
  17. l=['a','b','c']
  18. l.extend(l)
  19. Assert(l==['a','b','c','a','b','c'])
  20. # verify repr and print have the same result for a recursive list
  21. @skip('silverlight')
  22. def test_append_self():
  23. a = list('abc')
  24. a.append(a)
  25. AreEqual(str(a), "['a', 'b', 'c', [...]]")
  26. ## file
  27. from iptest.file_util import path_combine
  28. fn = path_combine(testpath.temporary_dir, "testfile.txt")
  29. fo = open(fn, "wb")
  30. a = list('abc')
  31. a.append(a)
  32. print >>fo, a,
  33. fo.close()
  34. fo = open(fn, "rb")
  35. Assert(fo.read() == repr(a))
  36. fo.close()
  37. if is_cli or is_silverlight:
  38. import clr
  39. x = [1,2,3]
  40. y = []
  41. xenum = iter(x)
  42. while xenum.MoveNext():
  43. y.append(xenum.Current)
  44. AreEqual(x, y)
  45. def test_assign_to_empty():
  46. # should all succeed
  47. y = []
  48. [] = y
  49. [], t = y, 0
  50. [[[]]] = [[y]]
  51. del y
  52. def test_unpack():
  53. listOfSize2 = [1, 2]
  54. # Disallow unequal unpacking assignment
  55. def f1(): [a, b, c] = listOfSize2
  56. def f2(): del a
  57. def f3(): [a] = listOfSize2
  58. AssertError(ValueError, f1)
  59. AssertError(NameError, f2)
  60. AssertError(ValueError, f3)
  61. AssertError(NameError, f2)
  62. [a, [b, c]] = [listOfSize2, listOfSize2]
  63. AreEqual(a, listOfSize2)
  64. AreEqual(b, 1)
  65. AreEqual(c, 2)
  66. del a, b, c
  67. [[a, b], c] = (listOfSize2, listOfSize2)
  68. AreEqual(a, 1)
  69. AreEqual(b, 2)
  70. AreEqual(c, listOfSize2)
  71. del a, b, c
  72. def test_sort():
  73. # named params passed to sort
  74. LExpected = ['A', 'b', 'c', 'D']
  75. L = ['D', 'c', 'b', 'A']
  76. L.sort(key=lambda x: x.lower())
  77. Assert(L == LExpected)
  78. l = [1, 2, 3]
  79. l2 = l[:]
  80. l.sort(lambda x, y: x > y)
  81. AreEqual(l, l2)
  82. l.sort(lambda x, y: x > y)
  83. AreEqual(l, l2)
  84. def test_list_in_list():
  85. aList = [['a']]
  86. anItem = ['a']
  87. AreEqual( aList.index(anItem), 0 )
  88. Assert(anItem in aList)
  89. def test_pop():
  90. x = [1,2,3,4,5,6,7,8,9,0]
  91. Assert(x.pop() == 0)
  92. Assert(x.pop(3) == 4)
  93. Assert(x.pop(-5) == 5)
  94. Assert(x.pop(0) == 1)
  95. Assert(x.pop() == 9)
  96. Assert(x.pop(2) == 6)
  97. Assert(x.pop(3) == 8)
  98. Assert(x.pop(-1) == 7)
  99. Assert(x.pop(-2) == 2)
  100. Assert(x.pop() == 3)
  101. def test_add_mul():
  102. x = [1,2,3]
  103. x += [4,5,6]
  104. Assert(x == [1,2,3,4,5,6])
  105. x = [1,2,3]
  106. AreEqual(x * 2, [1,2,3,1,2,3])
  107. AreEqual(2 * x, [1,2,3,1,2,3])
  108. class mylong(long): pass
  109. AreEqual([1, 2] * mylong(2L), [1, 2, 1, 2])
  110. AreEqual([3, 4].__mul__(mylong(2L)), [3, 4, 3, 4])
  111. AreEqual([5, 6].__rmul__(mylong(2L)), [5, 6, 5, 6])
  112. AreEqual(mylong(2L) * [7,8] , [7, 8, 7, 8])
  113. AssertError(TypeError, lambda: [1,2] * [3,4])
  114. AssertError(OverflowError, lambda: [1,2] * mylong(203958720984752098475023957209L))
  115. def test_reverse():
  116. x = ["begin",1,2,3,4,5,6,7,8,9,0,"end"]
  117. del x[6:]
  118. x.reverse()
  119. Assert(x == [5, 4, 3, 2, 1, "begin"])
  120. x = list("iron python")
  121. x.reverse()
  122. Assert(x == ['n','o','h','t','y','p',' ','n','o','r','i'])
  123. # should return listreverseenumerator, not reversed
  124. Assert(type(reversed([2,3,4])) != reversed)
  125. def test_equal():
  126. AreEqual([2,3] == '', False)
  127. AreEqual(list.__eq__([], None), NotImplemented)
  128. class MyEquality(object):
  129. def __eq__(self, other):
  130. return 'abc'
  131. class MyOldEquality(object):
  132. def __eq__(self, other):
  133. return 'def'
  134. AreEqual([] == MyEquality(), 'abc')
  135. AreEqual([] == MyOldEquality(), 'def')
  136. AreEqual([2,3] == (2,3), False)
  137. class MyIterable(object):
  138. def __iter__(self): return MyIterable()
  139. def next(self):
  140. yield 'a'
  141. yield 'b'
  142. AreEqual(['a', 'b'] == MyIterable(), False)
  143. def test_self_init():
  144. a = [1, 2, 3]
  145. list.__init__(a, a)
  146. AreEqual(a, [])
  147. ######################################################################
  148. # Verify behavior of index when the list changes...
  149. class clears(object):
  150. def __eq__(self, other):
  151. global hitCount
  152. hitCount = hitCount + 1
  153. del a[:]
  154. return False
  155. class appends(object):
  156. def __eq__(self, other):
  157. global hitCount
  158. hitCount = hitCount + 1
  159. a.append(self)
  160. return False
  161. a = [clears(), clears(),clears(),clears(),clears()]
  162. hitCount = 0
  163. AssertError(ValueError, a.index, 23)
  164. AreEqual(hitCount, 1) # should stop after the first equality check
  165. a = [appends(), appends(), appends()]
  166. hitCount = 0
  167. AssertError(ValueError, a.index, 2)
  168. AreEqual(hitCount, 3) # should have only checked existing items
  169. @runonly('cli')
  170. def test_pass_pythonlist_to_clr():
  171. ##
  172. ## test passing pythonlist to clr where IList or ArrayList is requested
  173. ## also borrow this place to test passing python dict to clr where
  174. ## IDictionary or Hashtable is requested
  175. ##
  176. def contains_all_1s(x):
  177. '''check the return value are 11111 or similar'''
  178. if type(x) == tuple:
  179. x = x[0]
  180. s = str(x)
  181. AreEqual(s.count("1"), len(s))
  182. def do_something(thetype, pl, cl, check_func):
  183. pt = thetype(pl)
  184. pt.AddRemove()
  185. ct = thetype(cl)
  186. ct.AddRemove()
  187. check_func()
  188. x = pt.Inspect()
  189. y = ct.Inspect()
  190. contains_all_1s(x)
  191. contains_all_1s(y)
  192. AreEqual(x, y)
  193. AreEqual(pt.Loop(), ct.Loop())
  194. check_func()
  195. load_iron_python_test()
  196. import System
  197. import IronPythonTest
  198. # test ListWrapperForIList
  199. pl = range(40)
  200. cl = System.Collections.Generic.List[int]()
  201. for x in pl: cl.Add(x)
  202. def check_content():
  203. for x, y in zip(cl, pl): AreEqual(x, y)
  204. do_something(IronPythonTest.UsePythonListAsList, pl, cl, check_content)
  205. # test DictWrapperForIDict
  206. pl = {"redmond" : 10, "seattle" : 20}
  207. cl = System.Collections.Generic.Dictionary[str, int]()
  208. for x, y in pl.iteritems(): cl.Add(x, y)
  209. pll = list(pl.iteritems())
  210. cll = list(cl)
  211. pll.sort(lambda x, y: cmp(x[0], y[0]))
  212. cll.sort(lambda x, y: cmp(x.Key, y.Key))
  213. def check_content():
  214. for x, y in zip(cll, pll):
  215. AreEqual(x.Key, y[0])
  216. AreEqual(x.Value, y[1])
  217. do_something(IronPythonTest.UsePythonDictAsDictionary, pl, cl, check_content)
  218. def test_inplace_addition():
  219. x = [2,3,4]
  220. x += x
  221. AreEqual(x, [2,3,4,2,3,4])
  222. test_cases = [ ([], [], []),
  223. ([1], [], [1]),
  224. ([], [1], [1]),
  225. ([1], [1], [1, 1]),
  226. ([1], [2], [1, 2]),
  227. ([2], [1], [2, 1]),
  228. ([1, 2], [], [1, 2]),
  229. ([], [1, 2], [1, 2]),
  230. ([1, 2], [3], [1, 2, 3]),
  231. ([3], [1, 2], [3, 1, 2]),
  232. ([1, 2], [3, 4], [1, 2, 3, 4]),
  233. ([3, 4], [1, 2], [3, 4, 1, 2]),
  234. ([None], [], [None]),
  235. ([None], [2], [None, 2]),
  236. ([""], [], [""]),
  237. ]
  238. for left_operand, right_operand, result in test_cases:
  239. #(No access to copy.deepcopy in IP)
  240. # Create new list to verify no side effects to the RHS list
  241. orig_right = [x for x in right_operand]
  242. left_operand += right_operand
  243. AreEqual(left_operand, result)
  244. #Side effects...
  245. AreEqual(orig_right, right_operand)
  246. #interesting cases
  247. x = [None]
  248. x += xrange(3)
  249. AreEqual(x, [None, 0, 1, 2])
  250. x = [None]
  251. x += (0, 1, 2)
  252. AreEqual(x, [None, 0, 1, 2])
  253. x = [None]
  254. x += "012"
  255. AreEqual(x, [None, "0", "1", "2"])
  256. x = [None]
  257. x += Exception()
  258. AreEqual(x, [None])
  259. #negative cases
  260. neg_cases = [ ([], None),
  261. ([], 1),
  262. ([], 1L),
  263. ([], 3.14),
  264. ([], object),
  265. ([], object()),
  266. ]
  267. for left_operand, right_operand in neg_cases:
  268. try:
  269. left_operand += right_operand
  270. AssertUnreachable()
  271. except TypeError, e:
  272. pass
  273. def test_indexing():
  274. l = [2,3,4]
  275. def set(x, i, v): x[i] = v
  276. AssertError(TypeError, lambda : l[2.0])
  277. AssertError(TypeError, lambda : set(l, 2.0, 1))
  278. class mylist(list):
  279. def __getitem__(self, index):
  280. return list.__getitem__(self, int(index))
  281. def __setitem__(self, index, value):
  282. return list.__setitem__(self, int(index), value)
  283. l = mylist(l)
  284. AreEqual(l[2.0], 4)
  285. l[2.0] = 1
  286. AreEqual(l[2], 1)
  287. def test_getslice():
  288. """overriding __len__ doesn't get called when doing __getslice__"""
  289. class l(list):
  290. def __len__(self):
  291. raise Exception()
  292. x = l()
  293. AreEqual(x.__getslice__(-1, -200), [])
  294. class mylist(list):
  295. def __getslice__(self, i, j):
  296. return i, j
  297. class mylong(long): pass
  298. class myint(int): pass
  299. # all indexes to __getslice__ should be ints
  300. for listType in list, mylist:
  301. for input in [0, 1, False, True, myint(0), myint(1), mylong(0), mylong(1), -1, myint(-1), mylong(-1)]:
  302. for x in listType(range(5))[input:input]:
  303. AreEqual(type(x), int)
  304. def test_repr():
  305. class mylist(list):
  306. def __repr__(self): return 'abc'
  307. AreEqual(repr(mylist()), 'abc')
  308. def test_index_multiply():
  309. for data in ([1,2], (1,2), 'ab'):
  310. class M:
  311. def __rmul__(self, other):
  312. return 1
  313. class Index(object):
  314. def __index__(self): return 2
  315. class OldIndex:
  316. def __index__(self): return 2
  317. AreEqual(data * M(), 1)
  318. AssertError(TypeError, lambda : data.__mul__(M()))
  319. AreEqual(data * Index(), data * 2)
  320. AreEqual(data * OldIndex(), data * 2)
  321. AreEqual(data.__mul__(Index()), data * 2)
  322. AreEqual(data.__mul__(OldIndex()), data * 2)
  323. AssertErrorWithMessage(TypeError, "'NoneType' object cannot be interpreted as an index", lambda : data.__mul__(None))
  324. AssertError(TypeError, lambda : data * None)
  325. AssertError(TypeError, lambda : None * data)
  326. def test_sequence_assign():
  327. tokens = [(chr(ord('a') + val), val) for val in range(0,10)]
  328. (first,pos),tokens = tokens[0], tokens[1:]
  329. AreEqual(first, 'a')
  330. AreEqual(pos, 0)
  331. AreEqual(tokens, [('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5), ('g', 6), ('h', 7), ('i', 8), ('j', 9)])
  332. def test_inheritance():
  333. listIter = type(iter([2,3,4]))
  334. reverseListIter = type(reversed([2,3,4]))
  335. for base in (listIter, reverseListIter):
  336. def subclass():
  337. class x(base): pass
  338. AssertError(TypeError, subclass)
  339. def test_backwards_slicing_no_step():
  340. class mylist(object):
  341. def __getitem__(self, index):
  342. return 'stuff'[index]
  343. a = list('stuff')
  344. for val in (a, 'stuff', tuple('stuff'), mylist()):
  345. a[1:0] = val
  346. AreEqual(a, list("stuff"[:1] + "stuff" + "stuff"[1:]))
  347. a = list('stuff')
  348. for val in (a, 'stuff', tuple('stuff'), mylist()):
  349. a[1:0:1] = a
  350. AreEqual(a, list("stuff"[:1] + "stuff" + "stuff"[1:]))
  351. a = list('stuff')
  352. def test_cp20125():
  353. class Temp(list):
  354. def __init__(self, value):
  355. self.value = value
  356. def __mul__(self, other):
  357. return self.value * other
  358. t1 = Temp(3.0)
  359. AreEqual(t1 * 3.0, 9.0)
  360. #--MAIN------------------------------------------------------------------------
  361. run_test(__name__)