PageRenderTime 54ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/Languages/IronPython/Tests/test_dict.py

http://github.com/IronLanguages/main
Python | 1243 lines | 982 code | 180 blank | 81 comment | 89 complexity | 27a35f3f5b33b26da3b81d0230590de2 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. #Regression: CodePlex 15715
  16. #Do not move or remove these two lines
  17. x = dir(dict)
  18. x = dir(dict.fromkeys)
  19. from iptest.assert_util import *
  20. import operator
  21. def test_sanity():
  22. items = 0
  23. d = {'key1': 'value1', 'key2': 'value2'}
  24. for key, value in d.iteritems():
  25. items += 1
  26. Assert((key, value) == ('key1', 'value1') or (key,value) == ('key2', 'value2'))
  27. Assert(items == 2)
  28. Assert(d["key1"] == "value1")
  29. Assert(d["key2"] == "value2")
  30. def getitem(d,k):
  31. d[k]
  32. AssertError(KeyError, getitem, d, "key3")
  33. x = d.get("key3")
  34. Assert(x == None)
  35. Assert(d["key1"] == d.get("key1"))
  36. Assert(d["key2"] == d.get("key2"))
  37. Assert(d.get("key3", "value3") == "value3")
  38. AssertError(KeyError, getitem, d, "key3")
  39. Assert(d.setdefault("key3") == None)
  40. Assert(d.setdefault("key4", "value4") == "value4")
  41. Assert(d["key3"] == None)
  42. Assert(d["key4"] == "value4")
  43. d2= dict(key1 = 'value1', key2 = 'value2')
  44. Assert(d2['key1'] == 'value1')
  45. #--inherit from a dictionary---------------------------------------------------
  46. def test_dict_inherit():
  47. class MyDict(dict):
  48. def __setitem__(self, *args):
  49. super(MyDict, self).__setitem__(*args)
  50. a = MyDict()
  51. a[0] = 'abc'
  52. AreEqual(a[0], 'abc')
  53. a[None] = 3
  54. AreEqual(a[None], 3)
  55. class MyDict(dict):
  56. def __setitem__(self, *args):
  57. dict.__setitem__(self, *args)
  58. a = MyDict()
  59. a[0] = 'abc'
  60. AreEqual(a[0], 'abc')
  61. a[None] = 3
  62. AreEqual(a[None], 3)
  63. #------------------------------------------------------------------------------
  64. # verify function environments, FieldIdDict,
  65. # custom old class dict, and module environments
  66. # all local identical to normal dictionaries
  67. def test_function_environments():
  68. x = {}
  69. class C: pass
  70. AreEqual(dir(x), dir(C.__dict__))
  71. class C:
  72. xx = 'abc'
  73. yy = 'def'
  74. pass
  75. AreEqual(dir(x), dir(C.__dict__))
  76. class C:
  77. x0 = 'abc'
  78. x1 = 'def'
  79. x2 = 'aaa'
  80. x3 = 'aaa'
  81. pass
  82. AreEqual(dir(x), dir(C.__dict__))
  83. class C:
  84. x0 = 'abc'
  85. x1 = 'def'
  86. x2 = 'aaa'
  87. x3 = 'aaa'
  88. x4 = 'abc'
  89. x5 = 'def'
  90. x6 = 'aaa'
  91. x7 = 'aaa'
  92. x0 = 'abc'
  93. pass
  94. AreEqual(dir(x), dir(C.__dict__))
  95. class C:
  96. x0 = 'abc'
  97. x1 = 'def'
  98. x2 = 'aaa'
  99. x3 = 'aaa'
  100. x4 = 'abc'
  101. x5 = 'def'
  102. x6 = 'aaa'
  103. x7 = 'aaa'
  104. x0 = 'abc'
  105. x10 = 'abc'
  106. x11 = 'def'
  107. x12 = 'aaa'
  108. x13 = 'aaa'
  109. x14 = 'abc'
  110. x15 = 'def'
  111. x16 = 'aaa'
  112. x17 = 'aaa'
  113. x10 = 'abc'
  114. pass
  115. AreEqual(dir(x), dir(C.__dict__))
  116. class C:
  117. x0 = 'abc'
  118. x1 = 'def'
  119. x2 = 'aaa'
  120. x3 = 'aaa'
  121. x4 = 'abc'
  122. x5 = 'def'
  123. x6 = 'aaa'
  124. x7 = 'aaa'
  125. x0 = 'abc'
  126. x10 = 'abc'
  127. x11 = 'def'
  128. x12 = 'aaa'
  129. x13 = 'aaa'
  130. x14 = 'abc'
  131. x15 = 'def'
  132. x16 = 'aaa'
  133. x17 = 'aaa'
  134. x10 = 'abc'
  135. x20 = 'abc'
  136. x21 = 'def'
  137. x22 = 'aaa'
  138. x23 = 'aaa'
  139. x24 = 'abc'
  140. x25 = 'def'
  141. x26 = 'aaa'
  142. x27 = 'aaa'
  143. x20 = 'abc'
  144. x110 = 'abc'
  145. x111 = 'def'
  146. x112 = 'aaa'
  147. x113 = 'aaa'
  148. x114 = 'abc'
  149. x115 = 'def'
  150. x116 = 'aaa'
  151. x117 = 'aaa'
  152. x110 = 'abc'
  153. pass
  154. AreEqual(dir(x), dir(C.__dict__))
  155. a = C()
  156. AreEqual(dir(x), dir(a.__dict__))
  157. a = C()
  158. a.abc = 'def'
  159. a.ghi = 'def'
  160. AreEqual(dir(x), dir(a.__dict__))
  161. if is_cli:
  162. # cpython does not have __dict__ at the module level?
  163. #AreEqual(dir(x), dir(__dict__))
  164. pass
  165. #####################################################################
  166. ## coverage for CustomFieldIdDict
  167. def contains(d, *attrs):
  168. for attr in attrs:
  169. Assert(attr in d, "didn't find " + str(attr) + " in " + repr(d))
  170. Assert(d.__contains__(attr), "didn't find " + str(attr) + " in " + repr(d))
  171. def repeat_on_class(C):
  172. newStyle = "__class__" in dir(C)
  173. c = C()
  174. d = C.__dict__
  175. contains(d, '__doc__', 'x1', 'f1')
  176. ## recursive entries & repr
  177. C.abc = d
  178. if not newStyle:
  179. x = repr(d) # shouldn't stack overflow
  180. else:
  181. x = str(d)
  182. Assert(x.find("'abc'") != -1)
  183. if not newStyle:
  184. Assert(x.find("{...}") != -1)
  185. else:
  186. Assert(x.find("'abc': <dictproxy object at") != -1)
  187. del C.abc
  188. keys, values = d.keys(), d.values()
  189. AreEqual(len(keys), len(values))
  190. contains(keys, '__doc__', 'x1', 'f1')
  191. ## initial length
  192. l = len(d)
  193. Assert(l > 3)
  194. # add more attributes
  195. def f2(self): return 22
  196. def f3(self): return 33
  197. if not newStyle:
  198. d['f2'] = f2
  199. d['x2'] = 20
  200. AreEqual(len(d), l + 2)
  201. AreEqual(d.__len__(), l + 2)
  202. if not newStyle:
  203. contains(d, '__doc__', 'x1', 'x2', 'f1', 'f2')
  204. contains(d.keys(), '__doc__', 'x1', 'x2', 'f1', 'f2')
  205. else:
  206. contains(d, '__doc__', 'x1', 'f1')
  207. contains(d.keys(), '__doc__', 'x1', 'f1')
  208. AreEqual(d['x1'], 10)
  209. if not newStyle:
  210. AreEqual(d['x2'], 20)
  211. AreEqual(d['f1'](c), 11)
  212. if not newStyle:
  213. AreEqual(d['f2'](c), 22)
  214. AssertError(KeyError, lambda : d['x3'])
  215. AssertError(KeyError, lambda : d['f3'])
  216. ## get
  217. AreEqual(d.get('x1'), 10)
  218. if not newStyle:
  219. AreEqual(d.get('x2'), 20)
  220. AreEqual(d.get('f1')(c), 11)
  221. if not newStyle:
  222. AreEqual(d.get('f2')(c), 22)
  223. AreEqual(d.get('x3'), None)
  224. AreEqual(d.get('x3', 30), 30)
  225. AreEqual(d.get('f3'), None)
  226. AreEqual(d.get('f3', f3)(c), 33)
  227. if not newStyle:
  228. ## setdefault
  229. AreEqual(d.setdefault('x1'), 10)
  230. AreEqual(d.setdefault('x1', 30), 10)
  231. AreEqual(d.setdefault('f1')(c), 11)
  232. AreEqual(d.setdefault('f1', f3)(c), 11)
  233. AreEqual(d.setdefault('x2'), 20)
  234. AreEqual(d.setdefault('x2', 30), 20)
  235. AreEqual(d.setdefault('f2')(c), 22)
  236. AreEqual(d.setdefault('f2', f3)(c), 22)
  237. AreEqual(d.setdefault('x3', 30), 30)
  238. AreEqual(d.setdefault('f3', f3)(c), 33)
  239. if not newStyle:
  240. ## pop
  241. l1 = len(d)
  242. AreEqual(d.pop('x1', 30), 10)
  243. AreEqual(len(d), l1-1)
  244. l1 = len(d)
  245. AreEqual(d.pop('x2', 30), 20)
  246. AreEqual(len(d), l1-1)
  247. l1 = len(d)
  248. AreEqual(d.pop("xx", 70), 70)
  249. AreEqual(len(d), l1)
  250. ## has_key
  251. Assert(d.has_key('f1'))
  252. if not newStyle:
  253. Assert(d.has_key('f2'))
  254. Assert(d.has_key('f3'))
  255. Assert(d.has_key('fx') == False)
  256. # subclassing, overriding __getitem__, and passing to
  257. # eval
  258. dictType = type(d)
  259. try:
  260. class newDict(dictType):
  261. def __getitem__(self, key):
  262. if key == 'abc':
  263. return 'def'
  264. return super(self, dictType).__getitem__(key)
  265. except TypeError, ex:
  266. if not newStyle:
  267. Assert(ex.message.find('cannot derive from sealed or value types') != -1, ex.message)
  268. else:
  269. Assert(ex.message.find('Error when calling the metaclass bases') != -1, ex.message)
  270. else:
  271. try:
  272. nd = newDict()
  273. except TypeError, e:
  274. if sys.platform == 'cli':
  275. import clr
  276. if clr.GetClrType(dictType).ToString() == 'IronPython.Runtime.Types.NamespaceDictionary':
  277. Fail("Error! Threw TypeError when creating newDict deriving from NamespaceDictionary")
  278. else:
  279. AreEqual(eval('abc', {}, nd), 'def')
  280. ############### IN THIS POINT, d LOOKS LIKE ###############
  281. ## {'f1': f1, 'f2': f2, 'f3': f3, 'x3': 30, '__doc__': 'This is comment', '__module__': '??'}
  282. ## iteritems
  283. lk = []
  284. for (k, v) in d.iteritems():
  285. lk.append(k)
  286. exp = None
  287. if k == 'f1': exp = 11
  288. elif k == 'f2': exp == 22
  289. elif k == 'f3': exp == 33
  290. if exp <> None:
  291. AreEqual(v(c), exp)
  292. if not newStyle:
  293. contains(lk, 'f1', 'f2', 'f3', 'x3', '__doc__')
  294. else:
  295. contains(lk, 'f1', '__module__', '__dict__', 'x1', '__weakref__', '__doc__')
  296. # iterkeys
  297. lk = []
  298. for k in d.iterkeys():
  299. lk.append(k)
  300. if not newStyle:
  301. contains(lk, 'f1', 'f2', 'f3', 'x3', '__doc__')
  302. else:
  303. contains(lk, 'f1', '__module__', '__dict__', 'x1', '__weakref__', '__doc__')
  304. # itervalues
  305. for v in d.itervalues():
  306. if callable(v):
  307. exp = v(c)
  308. Assert(exp in [11, 22, 33])
  309. elif v is str:
  310. Assert(v == 'This is comment')
  311. elif v is int:
  312. Assert(v == 30)
  313. if not newStyle:
  314. ## something fun before destorying it
  315. l1 = len(d)
  316. d[dict] = 3 # object as key
  317. AreEqual(len(d), l1+1)
  318. l1 = len(d)
  319. d[int] = 4 # object as key
  320. if is_cli or is_silverlight:
  321. print "CodePlex 16811"
  322. return
  323. AreEqual(len(d), l1+1)
  324. l1 = len(d)
  325. del d[int]
  326. AreEqual(len(d), l1-1)
  327. l1 = len(d)
  328. del d[dict]
  329. AreEqual(len(d), l1-1)
  330. l1 = len(d)
  331. del d['x3']
  332. AreEqual(len(d), l1-1)
  333. l1 = len(d)
  334. d.popitem()
  335. AreEqual(len(d), l1-1)
  336. ## object as key
  337. d[int] = int
  338. d[str] = "str"
  339. AreEqual(d[int], int)
  340. AreEqual(d[str], "str")
  341. d.clear()
  342. AreEqual(len(d), 0)
  343. AreEqual(d.__len__(), 0)
  344. #------------------------------------------------------------------------------
  345. def test_customfieldiddict_old():
  346. class C:
  347. '''This is comment'''
  348. x1 = 10
  349. def f1(self): return 11
  350. repeat_on_class(C)
  351. def test_customfieldiddict_new():
  352. class C(object):
  353. '''This is comment'''
  354. x1 = 10
  355. def f1(self): return 11
  356. repeat_on_class(C)
  357. #------------------------------------------------------------------------------
  358. def test_customfieldiddict_fromkeys():
  359. def new_repeat_on_class(C):
  360. d1 = C.__dict__
  361. l1 = len(d1)
  362. d2 = dict.fromkeys(d1)
  363. l2 = len(d2)
  364. AreEqual(l1, l2)
  365. AreEqual(d2['x'], None)
  366. AreEqual(d2['f'], None)
  367. d2 = dict.fromkeys(d1, 10)
  368. l2 = len(d2)
  369. AreEqual(l1, l2)
  370. AreEqual(d2['x'], 10)
  371. AreEqual(d2['f'], 10)
  372. class C:
  373. x = 10
  374. def f(self): pass
  375. new_repeat_on_class(C)
  376. class C(object):
  377. x = 10
  378. def f(self): pass
  379. new_repeat_on_class(C)
  380. #------------------------------------------------------------------------------
  381. def test_customfieldiddict_compare():
  382. def new_repeat_on_class(C1, C2):
  383. d1 = C1.__dict__
  384. d2 = C2.__dict__
  385. # object as key
  386. d1[int] = int
  387. d2[int] = int
  388. Assert(d1 <> d2)
  389. d2['f'] = d1['f']
  390. Assert([x for x in d1] == [x for x in d2])
  391. Assert(d1.fromkeys([x for x in d1]) >= d2.fromkeys([x for x in d2]))
  392. Assert(d1.fromkeys([x for x in d1]) <= d2.fromkeys([x for x in d2]))
  393. d1['y'] = 20
  394. d1[int] = int
  395. Assert(d1.fromkeys([x for x in d1]) > d2.fromkeys([x for x in d2]))
  396. Assert(d1.fromkeys([x for x in d1]) >= d2.fromkeys([x for x in d2]))
  397. Assert(d2.fromkeys([x for x in d2]) < d1.fromkeys([x for x in d1]))
  398. Assert(d2.fromkeys([x for x in d2]) <= d1.fromkeys([x for x in d1]))
  399. class C1:
  400. x = 10
  401. def f(self): pass
  402. class C2:
  403. x = 10
  404. def f(self): pass
  405. new_repeat_on_class(C1, C2)
  406. def t_func():
  407. class C1(object):
  408. x = 10
  409. def f(self): pass
  410. C1.__dict__[1] = 2
  411. AssertError(TypeError, t_func)
  412. @skip("win32")
  413. def test_dict_to_idict():
  414. """verify dicts can be converted to IDictionaries"""
  415. load_iron_python_test()
  416. from IronPythonTest import DictConversion
  417. class MyDict(dict): pass
  418. class KOld: pass
  419. class KNew(object): pass
  420. class KOldDerived(KOld): pass
  421. class KNewDerived(KNew): pass
  422. test_dicts = [
  423. {},
  424. {1:100},
  425. {None:None},
  426. {object:object},
  427. {1:100, 2:200},
  428. {1:100, 2:200, 3:300, 4:400},
  429. MyDict.__dict__,
  430. KOld.__dict__,
  431. KNew.__dict__,
  432. KOldDerived.__dict__,
  433. KNewDerived.__dict__,
  434. ]
  435. for temp_dict in test_dicts:
  436. expected = temp_dict.keys() + temp_dict.values()
  437. expected.sort()
  438. to_idict = list(DictConversion.ToIDictionary(temp_dict))
  439. to_idict.sort()
  440. AreEqual(to_idict, expected)
  441. to_idict = list(DictConversion.ToIDictionary(MyDict(temp_dict)))
  442. to_idict.sort()
  443. AreEqual(to_idict, expected)
  444. #####################################################################
  445. ## coverage for FieldIdDict
  446. def test_fieldiddict():
  447. def func(): pass
  448. d = func.__dict__
  449. d['x1'] = 10
  450. d['f1'] = lambda : 11
  451. d[int] = "int"
  452. d[dict] = {2:20}
  453. keys, values = d.keys(), d.values()
  454. AreEqual(len(keys), len(values))
  455. contains(keys, 'x1', 'f1', int, dict)
  456. ## initial length
  457. l = len(d)
  458. Assert(l == 4)
  459. # add more attributes
  460. d['x2'] = 20
  461. d['f2'] = lambda x: 22
  462. AreEqual(len(d), l + 2)
  463. AreEqual(d.__len__(), l + 2)
  464. contains(d, 'x1', 'x2', 'f1', 'f2', int, dict)
  465. contains(d.keys(), 'x1', 'x2', 'f1', 'f2', int, dict)
  466. AreEqual(d['x1'], 10)
  467. AreEqual(d['x2'], 20)
  468. AreEqual(d['f1'](), 11)
  469. AreEqual(d['f2'](9), 22)
  470. AssertError(KeyError, lambda : d['x3'])
  471. AssertError(KeyError, lambda : d['f3'])
  472. ## get
  473. AreEqual(d.get('x1'), 10)
  474. AreEqual(d.get('x2'), 20)
  475. AreEqual(d.get('f1')(), 11)
  476. AreEqual(d.get('f2')(1), 22)
  477. def f3(): return 33
  478. AreEqual(d.get('x3'), None)
  479. AreEqual(d.get('x3', 30), 30)
  480. AreEqual(d.get('f3'), None)
  481. AreEqual(d.get('f3', f3)(), 33)
  482. ## setdefault
  483. AreEqual(d.setdefault('x1'), 10)
  484. AreEqual(d.setdefault('x1', 30), 10)
  485. AreEqual(d.setdefault('f1')(), 11)
  486. AreEqual(d.setdefault('f1', f3)(), 11)
  487. AreEqual(d.setdefault('x2'), 20)
  488. AreEqual(d.setdefault('x2', 30), 20)
  489. AreEqual(d.setdefault('f2')(1), 22)
  490. AreEqual(d.setdefault('f2', f3)(1), 22)
  491. AreEqual(d.setdefault('x3', 30), 30)
  492. AreEqual(d.setdefault('f3', f3)(), 33)
  493. ## pop
  494. l1 = len(d); AreEqual(d.pop('x1', 30), 10)
  495. AreEqual(len(d), l1-1)
  496. l1 = len(d); AreEqual(d.pop('x2', 30), 20)
  497. AreEqual(len(d), l1-1)
  498. l1 = len(d); AreEqual(d.pop(int, 70), "int")
  499. AreEqual(len(d), l1-1)
  500. l1 = len(d); AreEqual(d.pop("xx", 70), 70)
  501. AreEqual(len(d), l1)
  502. ## has_key
  503. Assert(d.has_key('f1'))
  504. Assert(d.has_key('f2'))
  505. Assert(d.has_key('f3'))
  506. Assert(d.has_key(dict))
  507. Assert(d.has_key('fx') == False)
  508. ############### IN THIS POINT, d LOOKS LIKE ###############
  509. # f1, f2, f3, x3, dict as keys
  510. ## iteritems
  511. lk = []
  512. for (k, v) in d.iteritems():
  513. lk.append(k)
  514. if k == 'f1': AreEqual(v(), 11)
  515. elif k == 'f2': AreEqual(v(1), 22)
  516. elif k == 'f3': AreEqual(v(), 33)
  517. elif k == 'x3': AreEqual(v, 30)
  518. elif k == dict: AreEqual(v, {2:20})
  519. contains(lk, 'f1', 'f2', 'f3', 'x3', dict)
  520. # iterkeys
  521. lk = []
  522. for k in d.iterkeys():
  523. lk.append(k)
  524. contains(lk, 'f1', 'f2', 'f3', 'x3', dict)
  525. # itervalues
  526. for v in d.itervalues():
  527. if callable(v):
  528. try: exp = v(1)
  529. except: pass
  530. try: exp = v()
  531. except: pass
  532. Assert(exp in [11, 22, 33])
  533. elif v is dict:
  534. Assert(v == {2:20})
  535. elif v is int:
  536. Assert(v == 30)
  537. ## something fun before destorying it
  538. l1 = len(d); d[int] = 4 # object as key
  539. AreEqual(len(d), l1+1)
  540. l1 = len(d); del d[int]
  541. AreEqual(len(d), l1-1)
  542. l1 = len(d); del d[dict]
  543. AreEqual(len(d), l1-1)
  544. l1 = len(d); del d['x3']
  545. AreEqual(len(d), l1-1)
  546. l1 = len(d); popped_item = d.popitem()
  547. AreEqual(len(d), l1-1)
  548. ## object as key
  549. d[int] = int
  550. d[str] = "str"
  551. AreEqual(d[int], int)
  552. AreEqual(d[str], "str")
  553. d.clear()
  554. AreEqual(len(d), 0)
  555. AreEqual(d.__len__(), 0)
  556. d[int] = int
  557. AreEqual(len(d), 1)
  558. ## comparison
  559. def func1(): pass
  560. def func2(): pass
  561. d1 = func1.__dict__
  562. d2 = func2.__dict__
  563. d1['x'] = 10
  564. d2['x'] = 30
  565. d1[int] = int
  566. d2[int] = int
  567. # object as key
  568. Assert(d1 <> d2)
  569. d2['x'] = 10
  570. Assert(d1 == d2)
  571. Assert(d1 >= d2)
  572. Assert(d1 <= d2)
  573. d1['y'] = 20
  574. d1[dict] = "int"
  575. Assert(d1 > d2)
  576. Assert(d1 >= d2)
  577. Assert(d2 < d1)
  578. Assert(d2 <= d1)
  579. #####################################################################
  580. # subclassing dict, overriding __init__
  581. def test_subclass_dict_override__init__():
  582. class foo(dict):
  583. def __init__(self, abc):
  584. self.abc = abc
  585. a = foo('abc')
  586. AreEqual(a.abc, 'abc')
  587. # make sure dict.__init__ works
  588. a = {}
  589. a.__init__({'abc':'def'})
  590. AreEqual(a, {'abc':'def'})
  591. a.__init__({'abcd':'defg'})
  592. AreEqual(a, {'abc':'def', 'abcd':'defg'})
  593. # keyword arg contruction
  594. # single kw-arg, should go into dict
  595. a = dict(b=2)
  596. AreEqual(a, {'b':2})
  597. # dict value to init, Plus kw-arg
  598. a = dict({'a':3}, b=2)
  599. AreEqual(a, {'a':3, 'b':2})
  600. # more than one
  601. a = dict({'a':3}, b=2, c=5)
  602. AreEqual(a, {'a':3, 'b':2, 'c':5})
  603. try:
  604. dict({'a':3}, {'b':2}, c=5)
  605. AssertUnreachable()
  606. except TypeError: pass
  607. #####################################################################
  608. if is_netstandard: # TODO: revert this once System.SystemException is added to netstandard (https://github.com/IronLanguages/main/issues/1399)
  609. SystemError = System.InvalidOperationException
  610. def test_DictionaryUnionEnumerator():
  611. if is_cli == False:
  612. return
  613. class C(object): pass
  614. c = C()
  615. d = c.__dict__
  616. import System
  617. # Check empty enumerator
  618. e = System.Collections.IDictionary.GetEnumerator(d)
  619. AssertError(SystemError, getattr, e, "Key")
  620. AreEqual(e.MoveNext(), False)
  621. AssertError(SystemError, getattr, e, "Key")
  622. # Add non-string attribute
  623. d[1] = 100
  624. e = System.Collections.IDictionary.GetEnumerator(d)
  625. AssertError(SystemError, getattr, e, "Key")
  626. AreEqual(e.MoveNext(), True)
  627. AreEqual(e.Key, 1)
  628. AreEqual(e.MoveNext(), False)
  629. AssertError(SystemError, getattr, e, "Key")
  630. # Add string attribute
  631. c.attr = 100
  632. e = System.Collections.IDictionary.GetEnumerator(d)
  633. AssertError(SystemError, getattr, e, "Key")
  634. AreEqual(e.MoveNext(), True)
  635. key1 = e.Key
  636. AreEqual(e.MoveNext(), True)
  637. key2 = e.Key
  638. AreEqual((key1, key2) == (1, "attr") or (key1, key2) == ("attr", 1), True)
  639. AreEqual(e.MoveNext(), False)
  640. AssertError(SystemError, getattr, e, "Key")
  641. # Remove non-string attribute
  642. del d[1]
  643. e = System.Collections.IDictionary.GetEnumerator(d)
  644. AssertError(SystemError, getattr, e, "Key")
  645. AreEqual(e.MoveNext(), True)
  646. AreEqual(e.Key, "attr")
  647. AreEqual(e.MoveNext(), False)
  648. AssertError(SystemError, getattr, e, "Key")
  649. # Remove string attribute and check empty enumerator
  650. del c.attr
  651. e = System.Collections.IDictionary.GetEnumerator(d)
  652. AssertError(SystemError, getattr, e, "Key")
  653. AreEqual(e.MoveNext(), False)
  654. AssertError(SystemError, getattr, e, "Key")
  655. def test_same_but_different():
  656. """Test case checks that when two values who are logically different but share hash code & equality
  657. result in only a single entry"""
  658. AreEqual({-10:0, -10L:1}, {-10:1})
  659. #####################################################################
  660. def test_module_dict():
  661. me = sys.modules[__name__]
  662. moduleDict = me.__dict__
  663. AreEqual(operator.isMappingType(moduleDict), True)
  664. AreEqual(moduleDict.__contains__("test_module_dict"), True)
  665. AreEqual(moduleDict["test_module_dict"], test_module_dict)
  666. AreEqual(moduleDict.keys().__contains__("test_module_dict"), True)
  667. def test_eval_locals_simple():
  668. class Locals(dict):
  669. def __getitem__(self, key):
  670. try:
  671. return dict.__getitem__(self, key)
  672. except KeyError, e:
  673. return 'abc'
  674. locs = Locals()
  675. AreEqual(eval("unknownvariable", globals(), locs), 'abc')
  676. def test_key_error():
  677. class c: pass
  678. class d(object): pass
  679. for key in ['abc', 1, c(), d(), 1.0, 1L]:
  680. try:
  681. {}[key]
  682. except KeyError, e:
  683. AreEqual(e.args[0], key)
  684. try:
  685. del {}[key]
  686. except KeyError, e:
  687. AreEqual(e.args[0], key)
  688. try:
  689. set([]).remove(key)
  690. except KeyError, e:
  691. AreEqual(e.args[0], key)
  692. def test_contains():
  693. class ContainsDict(dict):
  694. was_called = False
  695. def __contains__(self, key):
  696. ContainsDict.was_called = True
  697. return dict.__contains__(self, key)
  698. md = ContainsDict()
  699. md["stuff"] = 1
  700. AreEqual(ContainsDict.was_called, False)
  701. AreEqual("nothing" in md, False)
  702. AreEqual("stuff" in md, True)
  703. AreEqual(ContainsDict.was_called, True)
  704. def test_stdtypes_dict():
  705. temp_types = [ int,
  706. long,
  707. float,
  708. complex,
  709. bool,
  710. str,
  711. unicode,
  712. basestring,
  713. list,
  714. tuple,
  715. xrange,
  716. dict,
  717. set,
  718. frozenset,
  719. type,
  720. object,
  721. ] #+ [eval("types." + x) for x in dir(types) if x.endswith("Type")]
  722. if not is_silverlight:
  723. temp_types.append(file)
  724. temp_keys = [ None, -1, 0, 1, 2.34, "", "None", int, object, test_stdtypes_dict, [], (None,)]
  725. for temp_type in temp_types:
  726. for temp_key in temp_keys:
  727. def tFunc(): temp_type.__dict__[temp_key] = 0
  728. AssertError(TypeError, tFunc)
  729. @skip("silverlight")
  730. def test_main_dict():
  731. import __main__
  732. #just make sure this doesn't throw...
  733. t_list = []
  734. for w in __main__.__dict__: t_list.append(w)
  735. t_list.sort()
  736. g_list = globals().keys()
  737. g_list.sort()
  738. AreEqual(t_list, g_list)
  739. def test_update():
  740. test_cases = (
  741. #N changes with an empty dict
  742. ({}, (), {}, {}),
  743. ({}, ({'k':'v'},), {}, {'k':'v'}),
  744. ({}, (), {'k':'v'}, {'k':'v'}),
  745. ({}, ({'k':'v', 'x':'y'},), {}, {'k':'v', 'x':'y'}),
  746. ({}, (), {'k':'v', 'x':'y'}, {'k':'v', 'x':'y'}),
  747. ({}, ({'k':'v'},), {'x':'y'}, {'k':'v', 'x':'y'}),
  748. #N changes with one pre-existing dict element
  749. ({'a':'b'}, (), {}, {'a':'b'}),
  750. ({'a':'b'}, ({'k':'v'},), {}, {'a':'b', 'k':'v'}),
  751. ({'a':'b'}, (), {'k':'v'}, {'a':'b', 'k':'v'}),
  752. ({'a':'b'}, ({'k':'v', 'x':'y'},), {}, {'a':'b', 'k':'v', 'x':'y'}),
  753. ({'a':'b'}, (), {'k':'v', 'x':'y'}, {'a':'b', 'k':'v', 'x':'y'}),
  754. ({'a':'b'}, ({'k':'v'},), {'x':'y'}, {'a':'b', 'k':'v', 'x':'y'}),
  755. #N changes with one pre-existing dict element
  756. ({'a':'b', 'c':'d'}, (), {}, {'a':'b', 'c':'d'}),
  757. ({'a':'b', 'c':'d'}, ({'k':'v'},), {}, {'a':'b', 'c':'d', 'k':'v'}),
  758. ({'a':'b', 'c':'d'}, (), {'k':'v'}, {'a':'b', 'c':'d', 'k':'v'}),
  759. ({'a':'b', 'c':'d'}, ({'k':'v', 'x':'y'},), {}, {'a':'b', 'c':'d', 'k':'v', 'x':'y'}),
  760. ({'a':'b', 'c':'d'}, (), {'k':'v', 'x':'y'}, {'a':'b', 'c':'d', 'k':'v', 'x':'y'}),
  761. ({'a':'b', 'c':'d'}, ({'k':'v'},), {'x':'y'}, {'a':'b', 'c':'d', 'k':'v', 'x':'y'}),
  762. )
  763. for start_dict, dict_param, kw_params, expected in test_cases:
  764. try:
  765. start_dict.update(*dict_param, **kw_params)
  766. except Exception, e:
  767. print "ERROR:", start_dict, ".update(*", dict_param, ", **", kw_params, ") failed!"
  768. raise e
  769. AreEqual(start_dict, expected)
  770. def test_update_argnames():
  771. expected = {"b": 1}
  772. result = {}
  773. result.update(b=1)
  774. AreEqual(result, expected)
  775. expected = {"other": 1}
  776. result = {}
  777. result.update(other=1)
  778. AreEqual(result, expected)
  779. expected = {"other": 1, "otherArgs": 2}
  780. result = {}
  781. result.update({"other": 1}, otherArgs=2)
  782. AreEqual(result, expected)
  783. def test_update_no_setitem():
  784. # update doesn't call __setitem__
  785. class mydict(dict):
  786. def __init__(self, *args, **kwargs):
  787. dict.__init__(self, *args, **kwargs)
  788. self.setcalled = False
  789. def __setitem__(self, index, value):
  790. self.setcalled = True
  791. raise Exception()
  792. d = mydict()
  793. d.update(mydict(abc=2))
  794. AreEqual(d.setcalled, False)
  795. d.update({'foo': 2})
  796. AreEqual(d.setcalled, False)
  797. def test_keys_not_as_property():
  798. def f():
  799. mapping = { 10: 10}
  800. for k in mapping.keys: pass
  801. AssertErrorWithMessages(TypeError,
  802. "iteration over non-sequence of type builtin_function_or_method",
  803. "'builtin_function_or_method' object is not iterable",
  804. f)
  805. def test_dict_class_dictionary():
  806. class KOld:
  807. KLASS_MEMBER = 3.14
  808. def aFunc(): pass
  809. def aMethod(self): pass
  810. class KNew(object):
  811. KLASS_MEMBER = 3.14
  812. def aFunc(): pass
  813. def aMethod(self): pass
  814. for K in [KOld, KNew]:
  815. temp_dict = dict(K.__dict__)
  816. #class member has the correct value?
  817. AreEqual(K.__dict__["KLASS_MEMBER"], 3.14)
  818. AreEqual(temp_dict["KLASS_MEMBER"], 3.14)
  819. #methods show up?
  820. for func_name in ["aFunc", "aMethod"]:
  821. Assert(func_name in K.__dict__.keys())
  822. Assert(func_name in temp_dict.keys())
  823. expected_keys = [ '__module__', 'KLASS_MEMBER', 'aFunc', 'aMethod',
  824. '__dict__',
  825. '__weakref__', '__doc__']
  826. for expected_key in expected_keys:
  827. Assert(KNew.__dict__.has_key(expected_key), expected_key)
  828. Assert(temp_dict.has_key(expected_key), expected_key)
  829. def test_cp15882():
  830. x = {}
  831. #negative cases
  832. for bad_stuff in [
  833. [1],
  834. {}, {1:1}, {(1,2): 1},
  835. set()]:
  836. try:
  837. x[bad_stuff] = 1
  838. Fail(str(bad_stuff) + " is unhashable")
  839. except TypeError:
  840. AreEqual(x, {})
  841. #positive cases
  842. for stuff in [
  843. (), (None),
  844. (-1), (0), (1), (2),
  845. (1, 2), (1, 2, 3),
  846. xrange(3), 1j, object, test_cp15882,
  847. (xrange(3)), (1j), (object), (test_cp15882),
  848. (()), ((())),
  849. ]:
  850. for i in xrange(2):
  851. x[stuff] = 1
  852. AreEqual(x[stuff], 1)
  853. del x[stuff]
  854. AreEqual(x, {})
  855. AssertError(KeyError, x.__delitem__, stuff)
  856. for i in xrange(2):
  857. x[stuff] = 1
  858. AreEqual(x[stuff], 1)
  859. x.__delitem__(stuff)
  860. AreEqual(x, {})
  861. AssertError(KeyError, x.__delitem__, stuff)
  862. def test_cp35348():
  863. empty = {} # underlying type: EmptyDictionaryStorage
  864. emptied = {1:1} # underlying type: CommonDictionaryStorage
  865. del emptied[1]
  866. not_empty = {42:1}
  867. #negative cases
  868. for bad_stuff in [
  869. [1],
  870. {}, {1:1}, {(1,2): 1},
  871. set()]:
  872. try:
  873. dummy = bad_stuff in empty
  874. Fail(str(bad_stuff) + " is unhashable")
  875. except TypeError:
  876. pass
  877. try:
  878. dummy = bad_stuff in emptied
  879. Fail(str(bad_stuff) + " is unhashable")
  880. except TypeError:
  881. pass
  882. try:
  883. dummy = bad_stuff in not_empty
  884. Fail(str(bad_stuff) + " is unhashable")
  885. except TypeError:
  886. pass
  887. class C1(object):
  888. pass
  889. c1=C1()
  890. class C2:
  891. pass
  892. c2=C2()
  893. #positive cases
  894. for stuff in [
  895. (), (None),
  896. (-1), (0), (1), (2),
  897. (1, 2), (1, 2, 3),
  898. xrange(3), 1j, object, test_cp35348,
  899. (xrange(3)), (1j), (object), (test_cp35348),
  900. (()), ((())), c1, c2,
  901. ]:
  902. AssertFalse(stuff in empty)
  903. AssertFalse(stuff in emptied)
  904. AssertFalse(stuff in not_empty)
  905. for stuff in [
  906. (), (None),
  907. (-1), (0), (1), (2),
  908. (1, 2), (1, 2, 3),
  909. xrange(3), 1j, object, test_cp35348,
  910. (xrange(3)), (1j), (object), (test_cp35348),
  911. (()), ((())), c1, c2,
  912. ]:
  913. emptied[stuff] = 'test_cp35348'
  914. Assert(stuff in emptied)
  915. del emptied[stuff]
  916. AreEqual(len(empty), 0)
  917. not_empty[stuff] = 'test_cp35348'
  918. Assert(stuff in not_empty)
  919. del not_empty[stuff]
  920. AreEqual(len(not_empty), 1)
  921. def test_cp35667():
  922. try:
  923. AssertFalse(type([]) in {})
  924. AssertFalse(type({}) in {})
  925. d = {list:1, dict:2}
  926. Assert(list in d)
  927. Assert(dict in d)
  928. except Exception as ex:
  929. Assert(False, "unexpected exception: %s" % ex)
  930. def test_comparison_operators():
  931. x = {2:3}
  932. y = {2:4}
  933. for oper in ('__lt__', '__gt__', '__le__', '__ge__'):
  934. for data in (y, None, 1, 1.0, 1L, (), [], 1j, "abc"):
  935. AreEqual(getattr(x, oper)(data), NotImplemented)
  936. def test_cp16519():
  937. __main__ = __import__(__name__)
  938. __main__.Dict = {"1": "a"}
  939. AreEqual(__main__.Dict["1"], "a")
  940. del __main__.Dict
  941. import sys
  942. sys.Dict = {"1": "b"}
  943. AreEqual(sys.Dict["1"], "b")
  944. del sys.Dict
  945. import testpkg1
  946. testpkg1.Dict = {"1": "c"}
  947. AreEqual(testpkg1.Dict["1"], "c")
  948. del testpkg1.Dict
  949. def test_dict_equality_lookup():
  950. """dictionaries check object equality before running normal equality"""
  951. class x(object):
  952. def __eq__(self, other):
  953. return False
  954. def __ne__(self, other):
  955. return True
  956. a = x()
  957. d = {}
  958. d[a] = 42
  959. AreEqual(d[a], 42)
  960. def test_missing():
  961. class Foo(dict):
  962. def __missing__(self, key):
  963. raise TypeError('Foo.__missing__ should not be called')
  964. f = Foo()
  965. AreEqual(f.setdefault(1, 2), 2)
  966. AreEqual(f.get(2), None)
  967. AreEqual(f.get(2, 3), 3)
  968. AssertError(KeyError, f.pop, 3)
  969. AreEqual(f.pop(3, 4), 4)
  970. x = {2:3}
  971. for f in (Foo({'abc':3}), Foo()):
  972. Assert(x != f)
  973. Assert(f != x)
  974. AreEqual(x.__eq__(f), False)
  975. AreEqual(f.__eq__(x), False)
  976. def test_cp29914():
  977. AreEqual(dict(o=42), {'o':42})
  978. def test_cp32527():
  979. '''test for duplicate key in dict under specific hash value conditions'''
  980. d = {'1': 1, '2': 1, '3': 1, 'a7': 1, 'a8': 1}
  981. #d now has 7 buckets internally, and computed hash for a7 and a8 keys will land on same starting bucket index
  982. #recycle the a7 bucket
  983. d.pop('a7')
  984. #attempt to update the a8 bucket, which now comes after the recycled a7
  985. d['a8'] = 5
  986. #if working properly, there will now be a recycled bucket (former home of a7) and a single a8 bucket
  987. #if not working properly, there will instead be two a8 buckets
  988. expected = 1
  989. actual = d.keys().count('a8')
  990. AreEqual(actual, expected)
  991. def test_cp34770():
  992. # Entries added with Int64/UInt64 should be findable with Python long
  993. from System import Int64, UInt64
  994. i64 = Int64(1110766100758387874)
  995. u64 = UInt64(9223372036854775808)
  996. m = {}
  997. m[i64] = 'a'
  998. AreEqual(m[1110766100758387874L], 'a')
  999. m[u64] = 'b'
  1000. AreEqual(m[9223372036854775808L], 'b')
  1001. run_test(__name__)