run-dicts.test 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. # Test cases for dicts (compile and run)
  2. [case testDictStuff]
  3. from typing import Dict, Any, List, Set, Tuple
  4. from defaultdictwrap import make_dict
  5. def f(x: int) -> int:
  6. dict1 = {} # type: Dict[int, int]
  7. dict1[1] = 1
  8. dict2 = {} # type: Dict[int, int]
  9. dict2[x] = 2
  10. dict1.update(dict2)
  11. l = [(5, 2)] # type: Any
  12. dict1.update(l)
  13. d2 = {6: 4} # type: Any
  14. dict1.update(d2)
  15. return dict1[1]
  16. def g() -> int:
  17. d = make_dict()
  18. d['a'] = 10
  19. d['a'] += 10
  20. d['b'] += 10
  21. l = [('c', 2)] # type: Any
  22. d.update(l)
  23. d2 = {'d': 4} # type: Any
  24. d.update(d2)
  25. return d['a'] + d['b']
  26. def h() -> None:
  27. d = {} # type: Dict[Any, Any]
  28. d[{}]
  29. def update_dict(x: Dict[Any, Any], y: Any):
  30. x.update(y)
  31. def make_dict1(x: Any) -> Dict[Any, Any]:
  32. return dict(x)
  33. def make_dict2(x: Dict[Any, Any]) -> Dict[Any, Any]:
  34. return dict(x)
  35. def u(x: int) -> int:
  36. d = {} # type: Dict[str, int]
  37. d.update(x=x)
  38. return d['x']
  39. def get_content(d: Dict[int, int]) -> Tuple[List[int], List[int], List[Tuple[int, int]]]:
  40. return list(d.keys()), list(d.values()), list(d.items())
  41. def get_content_set(d: Dict[int, int]) -> Tuple[Set[int], Set[int], Set[Tuple[int, int]]]:
  42. return set(d.keys()), set(d.values()), set(d.items())
  43. [file defaultdictwrap.py]
  44. from typing import Dict
  45. from collections import defaultdict # type: ignore
  46. def make_dict() -> Dict[str, int]:
  47. return defaultdict(int)
  48. [file driver.py]
  49. from collections import OrderedDict
  50. from native import (
  51. f, g, h, u, make_dict1, make_dict2, update_dict, get_content, get_content_set
  52. )
  53. assert f(1) == 2
  54. assert f(2) == 1
  55. assert g() == 30
  56. # Make sure we get a TypeError from indexing with unhashable and not KeyError
  57. try:
  58. h()
  59. except TypeError:
  60. pass
  61. else:
  62. assert False
  63. d = {'a': 1, 'b': 2}
  64. assert make_dict1(d) == d
  65. assert make_dict1(d.items()) == d
  66. assert make_dict2(d) == d
  67. # object.__dict__ is a "mappingproxy" and not a dict
  68. assert make_dict1(object.__dict__) == dict(object.__dict__)
  69. d = {}
  70. update_dict(d, object.__dict__)
  71. assert d == dict(object.__dict__)
  72. assert u(10) == 10
  73. assert get_content({1: 2}) == ([1], [2], [(1, 2)])
  74. od = OrderedDict([(1, 2), (3, 4)])
  75. assert get_content(od) == ([1, 3], [2, 4], [(1, 2), (3, 4)])
  76. od.move_to_end(1)
  77. assert get_content(od) == ([3, 1], [4, 2], [(3, 4), (1, 2)])
  78. assert get_content_set({1: 2}) == ({1}, {2}, {(1, 2)})
  79. assert get_content_set(od) == ({1, 3}, {2, 4}, {(1, 2), (3, 4)})
  80. [typing fixtures/typing-full.pyi]
  81. [case testDictIterationMethodsRun]
  82. from typing import Dict, Union
  83. from typing_extensions import TypedDict
  84. class ExtensionDict(TypedDict):
  85. python: str
  86. c: str
  87. def print_dict_methods(d1: Dict[int, int],
  88. d2: Dict[int, int],
  89. d3: Dict[int, int]) -> None:
  90. for k in d1.keys():
  91. print(k)
  92. for k, v in d2.items():
  93. print(k)
  94. print(v)
  95. for v in d3.values():
  96. print(v)
  97. def print_dict_methods_special(d1: Union[Dict[int, int], Dict[str, str]],
  98. d2: ExtensionDict) -> None:
  99. for k in d1.keys():
  100. print(k)
  101. for k, v in d1.items():
  102. print(k)
  103. print(v)
  104. for v2 in d2.values():
  105. print(v2)
  106. for k2, v2 in d2.items():
  107. print(k2)
  108. print(v2)
  109. def clear_during_iter(d: Dict[int, int]) -> None:
  110. for k in d:
  111. d.clear()
  112. class Custom(Dict[int, int]): pass
  113. [file driver.py]
  114. from native import print_dict_methods, print_dict_methods_special, Custom, clear_during_iter
  115. from collections import OrderedDict
  116. print_dict_methods({}, {}, {})
  117. print_dict_methods({1: 2}, {3: 4, 5: 6}, {7: 8})
  118. print('==')
  119. c = Custom({0: 1})
  120. print_dict_methods(c, c, c)
  121. print('==')
  122. d = OrderedDict([(1, 2), (3, 4)])
  123. print_dict_methods(d, d, d)
  124. print('==')
  125. print_dict_methods_special({1: 2}, {"python": ".py", "c": ".c"})
  126. d.move_to_end(1)
  127. print_dict_methods(d, d, d)
  128. clear_during_iter({}) # OK
  129. try:
  130. clear_during_iter({1: 2, 3: 4})
  131. except RuntimeError as e:
  132. assert str(e) == "dictionary changed size during iteration"
  133. else:
  134. assert False
  135. try:
  136. clear_during_iter(d)
  137. except RuntimeError as e:
  138. assert str(e) == "OrderedDict changed size during iteration"
  139. else:
  140. assert False
  141. class CustomMad(dict):
  142. def __iter__(self):
  143. return self
  144. def __next__(self):
  145. raise ValueError
  146. m = CustomMad()
  147. try:
  148. clear_during_iter(m)
  149. except ValueError:
  150. pass
  151. else:
  152. assert False
  153. class CustomBad(dict):
  154. def items(self):
  155. return [(1, 2, 3)] # Oops
  156. b = CustomBad()
  157. try:
  158. print_dict_methods(b, b, b)
  159. except TypeError as e:
  160. assert str(e) == "a tuple of length 2 expected"
  161. else:
  162. assert False
  163. [out]
  164. 1
  165. 3
  166. 4
  167. 5
  168. 6
  169. 8
  170. ==
  171. 0
  172. 0
  173. 1
  174. 1
  175. ==
  176. 1
  177. 3
  178. 1
  179. 2
  180. 3
  181. 4
  182. 2
  183. 4
  184. ==
  185. 1
  186. 1
  187. 2
  188. .py
  189. .c
  190. python
  191. .py
  192. c
  193. .c
  194. 3
  195. 1
  196. 3
  197. 4
  198. 1
  199. 2
  200. 4
  201. 2
  202. [case testDictMethods]
  203. from collections import defaultdict
  204. from typing import Dict, Optional, List, Set
  205. def test_dict_clear() -> None:
  206. d = {'a': 1, 'b': 2}
  207. d.clear()
  208. assert d == {}
  209. dd: Dict[str, int] = defaultdict(int)
  210. dd['a'] = 1
  211. dd.clear()
  212. assert dd == {}
  213. def test_dict_copy() -> None:
  214. d: Dict[str, int] = {}
  215. assert d.copy() == d
  216. d = {'a': 1, 'b': 2}
  217. assert d.copy() == d
  218. assert d.copy() is not d
  219. dd: Dict[str, int] = defaultdict(int)
  220. dd['a'] = 1
  221. assert dd.copy() == dd
  222. assert isinstance(dd.copy(), defaultdict)
  223. class MyDict(dict):
  224. def __init__(self, *args, **kwargs):
  225. self.update(*args, **kwargs)
  226. def setdefault(self, k, v=None):
  227. if v is None:
  228. if k in self.keys():
  229. return self[k]
  230. else:
  231. return None
  232. else:
  233. return super().setdefault(k, v) + 10
  234. def test_dict_setdefault() -> None:
  235. d: Dict[str, Optional[int]] = {'a': 1, 'b': 2}
  236. assert d.setdefault('a', 2) == 1
  237. assert d.setdefault('b', 2) == 2
  238. assert d.setdefault('c', 3) == 3
  239. assert d['a'] == 1
  240. assert d['c'] == 3
  241. assert d.setdefault('a') == 1
  242. assert d.setdefault('e') == None
  243. assert d.setdefault('e', 100) == None
  244. def test_dict_subclass_setdefault() -> None:
  245. d = MyDict()
  246. d['a'] = 1
  247. assert d.setdefault('a', 2) == 11
  248. assert d.setdefault('b', 2) == 12
  249. assert d.setdefault('c', 3) == 13
  250. assert d['a'] == 1
  251. assert d['c'] == 3
  252. assert d.setdefault('a') == 1
  253. assert d.setdefault('e') == None
  254. assert d.setdefault('e', 100) == 110
  255. def test_dict_empty_collection_setdefault() -> None:
  256. d1: Dict[str, List[int]] = {'a': [1, 2, 3]}
  257. assert d1.setdefault('a', []) == [1, 2, 3]
  258. assert d1.setdefault('b', []) == []
  259. assert 'b' in d1
  260. d1.setdefault('b', []).append(3)
  261. assert d1['b'] == [3]
  262. assert d1.setdefault('c', [1]) == [1]
  263. d2: Dict[str, Dict[str, int]] = {'a': {'a': 1}}
  264. assert d2.setdefault('a', {}) == {'a': 1}
  265. assert d2.setdefault('b', {}) == {}
  266. assert 'b' in d2
  267. d2.setdefault('b', {})['aa'] = 2
  268. d2.setdefault('b', {})['bb'] = 3
  269. assert d2['b'] == {'aa': 2, 'bb': 3}
  270. assert d2.setdefault('c', {'cc': 1}) == {'cc': 1}
  271. d3: Dict[str, Set[str]] = {'a': set('a')}
  272. assert d3.setdefault('a', set()) == {'a'}
  273. assert d3.setdefault('b', set()) == set()
  274. d3.setdefault('b', set()).add('b')
  275. d3.setdefault('b', set()).add('c')
  276. assert d3['b'] == {'b', 'c'}
  277. assert d3.setdefault('c', set('d')) == {'d'}
  278. [case testDictToBool]
  279. from typing import Dict, List
  280. def is_true(x: dict) -> bool:
  281. if x:
  282. return True
  283. else:
  284. return False
  285. def is_false(x: dict) -> bool:
  286. if not x:
  287. return True
  288. else:
  289. return False
  290. def test_dict_to_bool() -> None:
  291. assert is_false({})
  292. assert not is_true({})
  293. tmp_list: List[Dict] = [{2: bool}, {'a': 'b'}]
  294. for x in tmp_list:
  295. assert is_true(x)
  296. assert not is_false(x)