run-misc.test 24 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  1. [case testMaybeUninitVar]
  2. class C:
  3. def __init__(self, x: int) -> None:
  4. self.x = x
  5. def f(b: bool) -> None:
  6. u = C(1)
  7. while b:
  8. v = C(2)
  9. if v is not u:
  10. break
  11. print(v.x)
  12. [file driver.py]
  13. from native import f
  14. f(True)
  15. [out]
  16. 2
  17. [case testUninitBoom]
  18. def f(a: bool, b: bool) -> None:
  19. if a:
  20. x = 'lol'
  21. if b:
  22. print(x)
  23. def g() -> None:
  24. try:
  25. [0][1]
  26. y = 1
  27. except Exception:
  28. pass
  29. print(y)
  30. [file driver.py]
  31. from native import f, g
  32. from testutil import assertRaises
  33. f(True, True)
  34. f(False, False)
  35. with assertRaises(NameError):
  36. f(False, True)
  37. with assertRaises(NameError):
  38. g()
  39. [out]
  40. lol
  41. [case testBuiltins]
  42. y = 10
  43. def f(x: int) -> None:
  44. print(5)
  45. d = globals()
  46. assert d['y'] == 10
  47. d['y'] = 20
  48. assert y == 20
  49. [file driver.py]
  50. from native import f
  51. f(5)
  52. [out]
  53. 5
  54. [case testOptional]
  55. from typing import Optional
  56. class A: pass
  57. def f(x: Optional[A]) -> Optional[A]:
  58. return x
  59. def g(x: Optional[A]) -> int:
  60. if x is None:
  61. return 1
  62. if x is not None:
  63. return 2
  64. return 3
  65. def h(x: Optional[int], y: Optional[bool]) -> None:
  66. pass
  67. [file driver.py]
  68. from native import f, g, A
  69. a = A()
  70. assert f(None) is None
  71. assert f(a) is a
  72. assert g(None) == 1
  73. assert g(a) == 2
  74. [case testInferredOptionalAssignment]
  75. from typing import Any, Generator
  76. def f(b: bool) -> Any:
  77. if b:
  78. x = None
  79. else:
  80. x = 1
  81. if b:
  82. y = 1
  83. else:
  84. y = None
  85. m = 1 if b else None
  86. n = None if b else 1
  87. return ((x, y), (m, n))
  88. def gen(b: bool) -> Generator[Any, None, None]:
  89. if b:
  90. y = 1
  91. else:
  92. y = None
  93. yield y
  94. assert f(False) == ((1, None), (None, 1))
  95. assert f(True) == ((None, 1), (1, None))
  96. assert next(gen(False)) is None
  97. assert next(gen(True)) == 1
  98. [case testWith]
  99. from typing import Any
  100. class Thing:
  101. def __init__(self, x: str) -> None:
  102. self.x = x
  103. def __enter__(self) -> str:
  104. print('enter!', self.x)
  105. if self.x == 'crash':
  106. raise Exception('ohno')
  107. return self.x
  108. def __exit__(self, x: Any, y: Any, z: Any) -> None:
  109. print('exit!', self.x, y)
  110. def foo(i: int) -> int:
  111. with Thing('a') as x:
  112. print("yooo?", x)
  113. if i == 0:
  114. return 10
  115. elif i == 1:
  116. raise Exception('exception!')
  117. return -1
  118. def bar() -> None:
  119. with Thing('a') as x, Thing('b') as y:
  120. print("yooo?", x, y)
  121. def baz() -> None:
  122. with Thing('a') as x, Thing('crash') as y:
  123. print("yooo?", x, y)
  124. [file driver.py]
  125. from native import foo, bar, baz
  126. assert foo(0) == 10
  127. print('== foo ==')
  128. try:
  129. foo(1)
  130. except Exception:
  131. print('caught')
  132. assert foo(2) == -1
  133. print('== bar ==')
  134. bar()
  135. print('== baz ==')
  136. try:
  137. baz()
  138. except Exception:
  139. print('caught')
  140. [out]
  141. enter! a
  142. yooo? a
  143. exit! a None
  144. == foo ==
  145. enter! a
  146. yooo? a
  147. exit! a exception!
  148. caught
  149. enter! a
  150. yooo? a
  151. exit! a None
  152. == bar ==
  153. enter! a
  154. enter! b
  155. yooo? a b
  156. exit! b None
  157. exit! a None
  158. == baz ==
  159. enter! a
  160. enter! crash
  161. exit! a ohno
  162. caught
  163. [case testDisplays]
  164. from typing import List, Set, Tuple, Sequence, Dict, Any, Mapping
  165. def listDisplay(x: List[int], y: List[int]) -> List[int]:
  166. return [1, 2, *x, *y, 3]
  167. def setDisplay(x: Set[int], y: Set[int]) -> Set[int]:
  168. return {1, 2, *x, *y, 3}
  169. def tupleDisplay(x: Sequence[str], y: Sequence[str]) -> Tuple[str, ...]:
  170. return ('1', '2', *x, *y, '3')
  171. def dictDisplay(x: str, y1: Dict[str, int], y2: Dict[str, int]) -> Dict[str, int]:
  172. return {x: 2, **y1, 'z': 3, **y2}
  173. def dictDisplayUnpackMapping(obj: Mapping[str, str]) -> Dict[str, str]:
  174. return {**obj, "env": "value"}
  175. [file driver.py]
  176. import os
  177. from native import listDisplay, setDisplay, tupleDisplay, dictDisplay, dictDisplayUnpackMapping
  178. assert listDisplay([4], [5, 6]) == [1, 2, 4, 5, 6, 3]
  179. assert setDisplay({4}, {5}) == {1, 2, 3, 4, 5}
  180. assert tupleDisplay(['4', '5'], ['6']) == ('1', '2', '4', '5', '6', '3')
  181. assert dictDisplay('x', {'y1': 1}, {'y2': 2, 'z': 5}) == {'x': 2, 'y1': 1, 'y2': 2, 'z': 5}
  182. assert dictDisplayUnpackMapping(os.environ) == {**os.environ, "env": "value"}
  183. [case testArbitraryLvalues]
  184. from typing import List, Dict, Any
  185. class O(object):
  186. def __init__(self) -> None:
  187. self.x = 1
  188. def increment_attr(a: Any) -> Any:
  189. a.x += 1
  190. return a
  191. def increment_attr_o(o: O) -> O:
  192. o.x += 1
  193. return o
  194. def increment_all_indices(l: List[int]) -> List[int]:
  195. for i in range(len(l)):
  196. l[i] += 1
  197. return l
  198. def increment_all_keys(d: Dict[str, int]) -> Dict[str, int]:
  199. for k in d:
  200. d[k] += 1
  201. return d
  202. [file driver.py]
  203. from native import O, increment_attr, increment_attr_o, increment_all_indices, increment_all_keys
  204. class P(object):
  205. def __init__(self) -> None:
  206. self.x = 0
  207. assert increment_attr(P()).x == 1
  208. assert increment_attr_o(O()).x == 2
  209. assert increment_all_indices([1, 2, 3]) == [2, 3, 4]
  210. assert increment_all_keys({'a':1, 'b':2, 'c':3}) == {'a':2, 'b':3, 'c':4}
  211. [case testControlFlowExprs]
  212. from typing import Tuple
  213. def foo() -> object:
  214. print('foo')
  215. return 'foo'
  216. def bar() -> object:
  217. print('bar')
  218. return 'bar'
  219. def t(x: int) -> int:
  220. print(x)
  221. return x
  222. def f(b: bool) -> Tuple[object, object, object]:
  223. x = foo() if b else bar()
  224. y = b or foo()
  225. z = b and foo()
  226. return (x, y, z)
  227. def g() -> Tuple[object, object]:
  228. return (foo() or bar(), foo() and bar())
  229. def nand(p: bool, q: bool) -> bool:
  230. if not (p and q):
  231. return True
  232. return False
  233. def chained(x: int, y: int, z: int) -> bool:
  234. return t(x) < t(y) > t(z)
  235. def chained2(x: int, y: int, z: int, w: int) -> bool:
  236. return t(x) < t(y) < t(z) < t(w)
  237. [file driver.py]
  238. from native import f, g, nand, chained, chained2
  239. assert f(True) == ('foo', True, 'foo')
  240. print()
  241. assert f(False) == ('bar', 'foo', False)
  242. print()
  243. assert g() == ('foo', 'bar')
  244. assert nand(True, True) == False
  245. assert nand(True, False) == True
  246. assert nand(False, True) == True
  247. assert nand(False, False) == True
  248. print()
  249. assert chained(10, 20, 15) == True
  250. print()
  251. assert chained(10, 20, 30) == False
  252. print()
  253. assert chained(21, 20, 30) == False
  254. print()
  255. assert chained2(1, 2, 3, 4) == True
  256. print()
  257. assert chained2(1, 0, 3, 4) == False
  258. print()
  259. assert chained2(1, 2, 0, 4) == False
  260. [out]
  261. foo
  262. foo
  263. bar
  264. foo
  265. foo
  266. foo
  267. bar
  268. 10
  269. 20
  270. 15
  271. 10
  272. 20
  273. 30
  274. 21
  275. 20
  276. 1
  277. 2
  278. 3
  279. 4
  280. 1
  281. 0
  282. 1
  283. 2
  284. 0
  285. [case testMultipleAssignment]
  286. from typing import Tuple, List, Any
  287. def from_tuple(t: Tuple[int, str]) -> List[Any]:
  288. x, y = t
  289. return [y, x]
  290. def from_tuple_sequence(t: Tuple[int, ...]) -> List[int]:
  291. x, y, z = t
  292. return [z, y, x]
  293. def from_list(l: List[int]) -> List[int]:
  294. x, y = l
  295. return [y, x]
  296. def from_list_complex(l: List[int]) -> List[int]:
  297. ll = l[:]
  298. ll[1], ll[0] = l
  299. return ll
  300. def from_any(o: Any) -> List[Any]:
  301. x, y = o
  302. return [y, x]
  303. def multiple_assignments(t: Tuple[int, str]) -> List[Any]:
  304. a, b = c, d = t
  305. e, f = g, h = 1, 2
  306. return [a, b, c, d, e, f, g, h]
  307. [file driver.py]
  308. from native import (
  309. from_tuple, from_tuple_sequence, from_list, from_list_complex, from_any, multiple_assignments
  310. )
  311. assert from_tuple((1, 'x')) == ['x', 1]
  312. assert from_tuple_sequence((1, 5, 4)) == [4, 5, 1]
  313. try:
  314. from_tuple_sequence((1, 5))
  315. except ValueError as e:
  316. assert 'not enough values to unpack (expected 3, got 2)' in str(e)
  317. else:
  318. assert False
  319. assert from_list([3, 4]) == [4, 3]
  320. try:
  321. from_list([5, 4, 3])
  322. except ValueError as e:
  323. assert 'too many values to unpack (expected 2)' in str(e)
  324. else:
  325. assert False
  326. assert from_list_complex([7, 6]) == [6, 7]
  327. try:
  328. from_list_complex([5, 4, 3])
  329. except ValueError as e:
  330. assert 'too many values to unpack (expected 2)' in str(e)
  331. else:
  332. assert False
  333. assert from_any('xy') == ['y', 'x']
  334. assert multiple_assignments((4, 'x')) == [4, 'x', 4, 'x', 1, 2, 1, 2]
  335. [case testUnpack]
  336. from typing import List
  337. a, *b = [1, 2, 3, 4, 5]
  338. *c, d = [1, 2, 3, 4, 5]
  339. e, *f = [1,2]
  340. j, *k, l = [1, 2, 3]
  341. m, *n, o = [1, 2, 3, 4, 5, 6]
  342. p, q, r, *s, t = [1,2,3,4,5,6,7,8,9,10]
  343. tup = (1,2,3)
  344. y, *z = tup
  345. def unpack1(l : List[int]) -> None:
  346. *v1, v2, v3 = l
  347. def unpack2(l : List[int]) -> None:
  348. v1, *v2, v3 = l
  349. def unpack3(l : List[int]) -> None:
  350. v1, v2, *v3 = l
  351. [file driver.py]
  352. from native import a, b, c, d, e, f, j, k, l, m, n, o, p, q, r, s, t, y, z
  353. from native import unpack1, unpack2, unpack3
  354. from testutil import assertRaises
  355. assert a == 1
  356. assert b == [2,3,4,5]
  357. assert c == [1,2,3,4]
  358. assert d == 5
  359. assert e == 1
  360. assert f == [2]
  361. assert j == 1
  362. assert k == [2]
  363. assert l == 3
  364. assert m == 1
  365. assert n == [2,3,4,5]
  366. assert o == 6
  367. assert p == 1
  368. assert q == 2
  369. assert r == 3
  370. assert s == [4,5,6,7,8,9]
  371. assert t == 10
  372. assert y == 1
  373. assert z == [2,3]
  374. with assertRaises(ValueError, "not enough values to unpack"):
  375. unpack1([1])
  376. with assertRaises(ValueError, "not enough values to unpack"):
  377. unpack2([1])
  378. with assertRaises(ValueError, "not enough values to unpack"):
  379. unpack3([1])
  380. [out]
  381. [case testModuleTopLevel]
  382. x = 1
  383. print(x)
  384. def f() -> None:
  385. print(x + 1)
  386. def g() -> None:
  387. global x
  388. x = 77
  389. [file driver.py]
  390. import native
  391. native.f()
  392. native.x = 5
  393. native.f()
  394. native.g()
  395. print(native.x)
  396. [out]
  397. 1
  398. 2
  399. 6
  400. 77
  401. [case testComprehensions]
  402. from typing import List
  403. # A list comprehension
  404. l = [str(x) + " " + str(y) + " " + str(x*y) for x in range(10)
  405. if x != 6 if x != 5 for y in range(x) if y*x != 8]
  406. # Test short-circuiting as well
  407. def pred(x: int) -> bool:
  408. if x > 6:
  409. raise Exception()
  410. return x > 3
  411. # If we fail to short-circuit, pred(x) will be called with x=7
  412. # eventually and will raise an exception.
  413. l2 = [x for x in range(10) if x <= 6 if pred(x)]
  414. src = ['x']
  415. def f() -> List[str]:
  416. global src
  417. res = src
  418. src = []
  419. return res
  420. l3 = [s for s in f()]
  421. l4 = [s for s in f()]
  422. # A dictionary comprehension
  423. d = {k: k*k for k in range(10) if k != 5 if k != 6}
  424. # A set comprehension
  425. s = {str(x) + " " + str(y) + " " + str(x*y) for x in range(10)
  426. if x != 6 if x != 5 for y in range(x) if y*x != 8}
  427. [file driver.py]
  428. from native import l, l2, l3, l4, d, s
  429. for a in l:
  430. print(a)
  431. print(tuple(l2))
  432. assert l3 == ['x']
  433. assert l4 == []
  434. for k in sorted(d):
  435. print(k, d[k])
  436. for a in sorted(s):
  437. print(a)
  438. [out]
  439. 1 0 0
  440. 2 0 0
  441. 2 1 2
  442. 3 0 0
  443. 3 1 3
  444. 3 2 6
  445. 4 0 0
  446. 4 1 4
  447. 4 3 12
  448. 7 0 0
  449. 7 1 7
  450. 7 2 14
  451. 7 3 21
  452. 7 4 28
  453. 7 5 35
  454. 7 6 42
  455. 8 0 0
  456. 8 2 16
  457. 8 3 24
  458. 8 4 32
  459. 8 5 40
  460. 8 6 48
  461. 8 7 56
  462. 9 0 0
  463. 9 1 9
  464. 9 2 18
  465. 9 3 27
  466. 9 4 36
  467. 9 5 45
  468. 9 6 54
  469. 9 7 63
  470. 9 8 72
  471. (4, 5, 6)
  472. 0 0
  473. 1 1
  474. 2 4
  475. 3 9
  476. 4 16
  477. 7 49
  478. 8 64
  479. 9 81
  480. 1 0 0
  481. 2 0 0
  482. 2 1 2
  483. 3 0 0
  484. 3 1 3
  485. 3 2 6
  486. 4 0 0
  487. 4 1 4
  488. 4 3 12
  489. 7 0 0
  490. 7 1 7
  491. 7 2 14
  492. 7 3 21
  493. 7 4 28
  494. 7 5 35
  495. 7 6 42
  496. 8 0 0
  497. 8 2 16
  498. 8 3 24
  499. 8 4 32
  500. 8 5 40
  501. 8 6 48
  502. 8 7 56
  503. 9 0 0
  504. 9 1 9
  505. 9 2 18
  506. 9 3 27
  507. 9 4 36
  508. 9 5 45
  509. 9 6 54
  510. 9 7 63
  511. 9 8 72
  512. [case testDummyTypes]
  513. from typing import Tuple, List, Dict, NamedTuple
  514. from typing_extensions import Literal, TypedDict, NewType
  515. class A:
  516. pass
  517. T = List[A]
  518. U = List[Tuple[int, str]]
  519. Z = List[List[int]]
  520. D = Dict[int, List[int]]
  521. N = NewType('N', int)
  522. G = Tuple[int, str]
  523. def foo(x: N) -> int:
  524. return x
  525. foo(N(10))
  526. z = N(10)
  527. Lol = NamedTuple('Lol', (('a', int), ('b', T)))
  528. x = Lol(1, [])
  529. def take_lol(x: Lol) -> int:
  530. return x.a
  531. TD = TypedDict('TD', {'a': int})
  532. def take_typed_dict(x: TD) -> int:
  533. return x['a']
  534. def take_literal(x: Literal[1, 2, 3]) -> None:
  535. print(x)
  536. [file driver.py]
  537. import sys
  538. from native import *
  539. if sys.version_info[:3] > (3, 5, 2):
  540. assert "%s %s %s %s" % (T, U, Z, D) == "typing.List[native.A] typing.List[typing.Tuple[int, str]] typing.List[typing.List[int]] typing.Dict[int, typing.List[int]]"
  541. print(x)
  542. print(z)
  543. print(take_lol(x))
  544. print(take_typed_dict({'a': 20}))
  545. try:
  546. take_typed_dict(None)
  547. except Exception as e:
  548. print(type(e).__name__)
  549. take_literal(1)
  550. # We check that the type is the real underlying type
  551. try:
  552. take_literal(None)
  553. except Exception as e:
  554. print(type(e).__name__)
  555. # ... but not that it is a valid literal value
  556. take_literal(10)
  557. [out]
  558. Lol(a=1, b=[])
  559. 10
  560. 1
  561. 20
  562. TypeError
  563. 1
  564. TypeError
  565. 10
  566. [case testClassBasedTypedDict]
  567. from typing_extensions import TypedDict
  568. class TD(TypedDict):
  569. a: int
  570. class TD2(TD):
  571. b: int
  572. class TD3(TypedDict, total=False):
  573. c: int
  574. class TD4(TD3, TD2, total=False):
  575. d: int
  576. def test_typed_dict() -> None:
  577. d = TD(a=5)
  578. assert d['a'] == 5
  579. assert type(d) == dict
  580. # TODO: This doesn't work yet
  581. # assert TD.__annotations__ == {'a': int}
  582. def test_inherited_typed_dict() -> None:
  583. d = TD2(a=5, b=3)
  584. assert d['a'] == 5
  585. assert d['b'] == 3
  586. assert type(d) == dict
  587. def test_non_total_typed_dict() -> None:
  588. d3 = TD3(c=3)
  589. d4 = TD4(a=1, b=2, c=3, d=4)
  590. assert d3['c'] == 3
  591. assert d4['d'] == 4
  592. [case testClassBasedNamedTuple]
  593. from typing import NamedTuple
  594. import sys
  595. # Class-based NamedTuple requires Python 3.6+
  596. version = sys.version_info[:2]
  597. if version[0] == 3 and version[1] < 6:
  598. exit()
  599. class NT(NamedTuple):
  600. a: int
  601. def test_named_tuple() -> None:
  602. t = NT(a=1)
  603. assert t.a == 1
  604. assert type(t) is NT
  605. assert isinstance(t, tuple)
  606. assert not isinstance(tuple([1]), NT)
  607. [case testUnion]
  608. from typing import Union
  609. class A:
  610. def __init__(self, x: int) -> None:
  611. self.x = x
  612. def f(self, y: int) -> int:
  613. return y + self.x
  614. class B:
  615. def __init__(self, x: object) -> None:
  616. self.x = x
  617. def f(self, y: object) -> object:
  618. return y
  619. def f(x: Union[A, str]) -> object:
  620. if isinstance(x, A):
  621. return x.x
  622. else:
  623. return x + 'x'
  624. def g(x: int) -> Union[A, int]:
  625. if x == 0:
  626. return A(1)
  627. else:
  628. return x + 1
  629. def get(x: Union[A, B]) -> object:
  630. return x.x
  631. def call(x: Union[A, B]) -> object:
  632. return x.f(5)
  633. [file driver.py]
  634. from native import A, B, f, g, get, call
  635. assert f('a') == 'ax'
  636. assert f(A(4)) == 4
  637. assert isinstance(g(0), A)
  638. assert g(2) == 3
  639. assert get(A(5)) == 5
  640. assert get(B('x')) == 'x'
  641. assert call(A(4)) == 9
  642. assert call(B('x')) == 5
  643. try:
  644. f(1)
  645. except TypeError:
  646. pass
  647. else:
  648. assert False
  649. [case testAnyAll]
  650. from typing import Iterable
  651. def call_any_nested(l: Iterable[Iterable[int]], val: int = 0) -> int:
  652. res = any(i == val for l2 in l for i in l2)
  653. return 0 if res else 1
  654. def call_any(l: Iterable[int], val: int = 0) -> int:
  655. res = any(i == val for i in l)
  656. return 0 if res else 1
  657. def call_all(l: Iterable[int], val: int = 0) -> int:
  658. res = all(i == val for i in l)
  659. return 0 if res else 1
  660. [file driver.py]
  661. from native import call_any, call_all, call_any_nested
  662. zeros = [0, 0, 0]
  663. ones = [1, 1, 1]
  664. mixed_001 = [0, 0, 1]
  665. mixed_010 = [0, 1, 0]
  666. mixed_100 = [1, 0, 0]
  667. mixed_011 = [0, 1, 1]
  668. mixed_101 = [1, 0, 1]
  669. mixed_110 = [1, 1, 0]
  670. assert call_any([]) == 1
  671. assert call_any(zeros) == 0
  672. assert call_any(ones) == 1
  673. assert call_any(mixed_001) == 0
  674. assert call_any(mixed_010) == 0
  675. assert call_any(mixed_100) == 0
  676. assert call_any(mixed_011) == 0
  677. assert call_any(mixed_101) == 0
  678. assert call_any(mixed_110) == 0
  679. assert call_all([]) == 0
  680. assert call_all(zeros) == 0
  681. assert call_all(ones) == 1
  682. assert call_all(mixed_001) == 1
  683. assert call_all(mixed_010) == 1
  684. assert call_all(mixed_100) == 1
  685. assert call_all(mixed_011) == 1
  686. assert call_all(mixed_101) == 1
  687. assert call_all(mixed_110) == 1
  688. assert call_any_nested([[1, 1, 1], [1, 1], []]) == 1
  689. assert call_any_nested([[1, 1, 1], [0, 1], []]) == 0
  690. [case testSum]
  691. [typing fixtures/typing-full.pyi]
  692. from typing import Any, List
  693. def test_sum_of_numbers() -> None:
  694. assert sum(x for x in [1, 2, 3]) == 6
  695. assert sum(x for x in [0.0, 1.2, 2]) == 6.2
  696. assert sum(x for x in [1, 1j]) == 1 + 1j
  697. def test_sum_callables() -> None:
  698. assert sum((lambda x: x == 0)(x) for x in []) == 0
  699. assert sum((lambda x: x == 0)(x) for x in [0]) == 1
  700. assert sum((lambda x: x == 0)(x) for x in [0, 0, 0]) == 3
  701. assert sum((lambda x: x == 0)(x) for x in [0, 1, 0]) == 2
  702. assert sum((lambda x: x % 2 == 0)(x) for x in range(2**10)) == 2**9
  703. def test_sum_comparisons() -> None:
  704. assert sum(x == 0 for x in []) == 0
  705. assert sum(x == 0 for x in [0]) == 1
  706. assert sum(x == 0 for x in [0, 0, 0]) == 3
  707. assert sum(x == 0 for x in [0, 1, 0]) == 2
  708. assert sum(x % 2 == 0 for x in range(2**10)) == 2**9
  709. def test_sum_multi() -> None:
  710. assert sum(i + j == 0 for i, j in zip([0, 0, 0], [0, 1, 0])) == 2
  711. def test_sum_misc() -> None:
  712. # misc cases we do optimize (note, according to sum's helptext, we don't need to support
  713. # non-numeric cases, but CPython and mypyc both do anyway)
  714. assert sum(c == 'd' for c in 'abcdd') == 2
  715. # misc cases we do not optimize
  716. assert sum([0, 1]) == 1
  717. assert sum([0, 1], 1) == 2
  718. def test_sum_start_given() -> None:
  719. a = 1
  720. assert sum((x == 0 for x in [0, 1]), a) == 2
  721. assert sum(((lambda x: x == 0)(x) for x in []), 1) == 1
  722. assert sum(((lambda x: x == 0)(x) for x in [0]), 1) == 2
  723. assert sum(((lambda x: x == 0)(x) for x in [0, 0, 0]), 1) == 4
  724. assert sum(((lambda x: x == 0)(x) for x in [0, 1, 0]), 1) == 3
  725. assert sum(((lambda x: x % 2 == 0)(x) for x in range(2**10)), 1) == 2**9 + 1
  726. assert sum((x for x in [1, 1j]), 2j) == 1 + 3j
  727. assert sum((c == 'd' for c in 'abcdd'), 1) == 3
  728. [case testNoneStuff]
  729. from typing import Optional
  730. class A:
  731. x: int
  732. def lol(x: A) -> None:
  733. setattr(x, 'x', 5)
  734. def none() -> None:
  735. return
  736. def arg(x: Optional[A]) -> bool:
  737. return x is None
  738. [file driver.py]
  739. import native
  740. native.lol(native.A())
  741. # Catch refcounting failures
  742. for i in range(10000):
  743. native.none()
  744. native.arg(None)
  745. [case testBorrowRefs]
  746. def make_garbage(arg: object) -> None:
  747. b = True
  748. while b:
  749. arg = None
  750. b = False
  751. [file driver.py]
  752. from native import make_garbage
  753. import sys
  754. def test():
  755. x = object()
  756. r0 = sys.getrefcount(x)
  757. make_garbage(x)
  758. r1 = sys.getrefcount(x)
  759. assert r0 == r1
  760. test()
  761. [case testFinalStaticRunFail]
  762. if False:
  763. from typing import Final
  764. if bool():
  765. x: 'Final' = [1]
  766. def f() -> int:
  767. return x[0]
  768. [file driver.py]
  769. from native import f
  770. try:
  771. print(f())
  772. except NameError as e:
  773. print(e.args[0])
  774. [out]
  775. value for final name "x" was not set
  776. [case testFinalStaticRunListTupleInt]
  777. if False:
  778. from typing import Final
  779. x: 'Final' = [1]
  780. y: 'Final' = (1, 2)
  781. z: 'Final' = 1 + 1
  782. def f() -> int:
  783. return x[0]
  784. def g() -> int:
  785. return y[0]
  786. def h() -> int:
  787. return z - 1
  788. [file driver.py]
  789. from native import f, g, h, x, y, z
  790. print(f())
  791. print(x[0])
  792. print(g())
  793. print(y)
  794. print(h())
  795. print(z)
  796. [out]
  797. 1
  798. 1
  799. 1
  800. (1, 2)
  801. 1
  802. 2
  803. [case testCheckVersion]
  804. import sys
  805. if sys.version_info[:2] == (3, 12):
  806. def version() -> int:
  807. return 12
  808. elif sys.version_info[:2] == (3, 11):
  809. def version() -> int:
  810. return 11
  811. elif sys.version_info[:2] == (3, 10):
  812. def version() -> int:
  813. return 10
  814. elif sys.version_info[:2] == (3, 9):
  815. def version() -> int:
  816. return 9
  817. elif sys.version_info[:2] == (3, 8):
  818. def version() -> int:
  819. return 8
  820. elif sys.version_info[:2] == (3, 7):
  821. def version() -> int:
  822. return 7
  823. elif sys.version_info[:2] == (3, 6):
  824. def version() -> int:
  825. return 6
  826. else:
  827. raise Exception("we don't support this version yet!")
  828. [file driver.py]
  829. import sys
  830. version = sys.version_info[:2]
  831. import native
  832. assert native.version() == sys.version_info[1]
  833. [case testTypeErrorMessages]
  834. from typing import Tuple
  835. class A:
  836. pass
  837. class B:
  838. pass
  839. def f(x: B) -> None:
  840. pass
  841. def g(x: Tuple[int, A]) -> None:
  842. pass
  843. [file driver.py]
  844. from testutil import assertRaises
  845. from native import A, f, g
  846. class Busted:
  847. pass
  848. Busted.__module__ = None
  849. with assertRaises(TypeError, "int"):
  850. f(0)
  851. with assertRaises(TypeError, "native.A"):
  852. f(A())
  853. with assertRaises(TypeError, "tuple[None, native.A]"):
  854. f((None, A()))
  855. with assertRaises(TypeError, "tuple[tuple[int, str], native.A]"):
  856. f(((1, "ha"), A()))
  857. with assertRaises(TypeError, "tuple[<50 items>]"):
  858. f(tuple(range(50)))
  859. with assertRaises(TypeError, "errored formatting real type!"):
  860. f(Busted())
  861. with assertRaises(TypeError, "tuple[int, native.A] object expected; got tuple[int, int]"):
  862. g((20, 30))
  863. [case testComprehensionShadowBinder]
  864. def foo(x: object) -> object:
  865. if isinstance(x, list):
  866. return tuple(x for x in x), x
  867. return None
  868. [file driver.py]
  869. from native import foo
  870. assert foo(None) == None
  871. assert foo([1, 2, 3]) == ((1, 2, 3), [1, 2, 3])
  872. [case testAllLiterals]
  873. # Test having all sorts of literals in a single file
  874. def test_str() -> None:
  875. assert '' == eval("''")
  876. assert len('foo bar' + str()) == 7
  877. assert 'foo bar' == eval("'foo bar'")
  878. assert 'foo\u1245\0bar' == eval("'foo' + chr(0x1245) + chr(0) + 'bar'")
  879. assert 'foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345' == eval("'foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345'")
  880. assert 'Zoobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar123' == eval("'Zoobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar123'")
  881. def test_bytes() -> None:
  882. assert b'' == eval("b''")
  883. assert b'foo bar' == eval("b'foo bar'")
  884. assert b'\xafde' == eval(r"b'\xafde'")
  885. assert b'foo\xde\0bar' == eval("b'foo' + bytes([0xde, 0]) + b'bar'")
  886. assert b'foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345' == eval("b'foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345'")
  887. def test_int() -> None:
  888. assert 2875872359823758923758923759 == eval('2875872359823758923758923759')
  889. assert -552875872359823758923758923759 == eval('-552875872359823758923758923759')
  890. def test_float() -> None:
  891. assert 1.5 == eval('1.5')
  892. assert -3.75 == eval('-3.75')
  893. assert 2.5e10 == eval('2.5e10')
  894. assert 2.5e50 == eval('2.5e50')
  895. assert 2.5e1000 == eval('2.5e1000')
  896. assert -2.5e1000 == eval('-2.5e1000')
  897. def test_complex() -> None:
  898. assert 1.5j == eval('1.5j')
  899. assert 1.5j + 2.5 == eval('2.5 + 1.5j')
  900. assert -3.75j == eval('-3.75j')
  901. assert 2.5e10j == eval('2.5e10j')
  902. assert 2.5e50j == eval('2.5e50j')
  903. assert 2.5e1000j == eval('2.5e1000j')
  904. assert 2.5e1000j + 3.5e2000 == eval('3.5e2000 + 2.5e1000j')
  905. assert -2.5e1000j == eval('-2.5e1000j')
  906. [case testUnreachableExpressions]
  907. from typing import cast
  908. import sys
  909. A = sys.platform == 'x' and foobar
  910. B = sys.platform == 'x' and sys.foobar
  911. C = sys.platform == 'x' and f(a, -b, 'y') > [c + e, g(y=2)]
  912. C = sys.platform == 'x' and cast(a, b[c])
  913. C = sys.platform == 'x' and (lambda x: y + x)
  914. # TODO: This still doesn't work
  915. # C = sys.platform == 'x' and (x for y in z)
  916. assert not A
  917. assert not B
  918. assert not C
  919. [case testDoesntSegfaultWhenTopLevelFails]
  920. # make the initial import fail
  921. assert False
  922. [file driver.py]
  923. # load native, cause PyInit to be run, create the module but don't finish initializing the globals
  924. for _ in range(2):
  925. try:
  926. import native
  927. raise RuntimeError('exception expected')
  928. except AssertionError:
  929. pass
  930. [case testRepeatedUnderscoreFunctions]
  931. def _(arg): pass
  932. def _(arg): pass
  933. [case testUnderscoreFunctionsInMethods]
  934. class A:
  935. def _(arg): pass
  936. def _(arg): pass
  937. class B(A):
  938. def _(arg): pass
  939. def _(arg): pass
  940. [case testGlobalRedefinition_toplevel]
  941. # mypy: allow-redefinition
  942. i = 0
  943. i += 1
  944. i = "foo"
  945. i += i
  946. i = b"foo"
  947. def test_redefinition() -> None:
  948. assert i == b"foo"
  949. [case testWithNative]
  950. class DummyContext:
  951. def __init__(self):
  952. self.c = 0
  953. def __enter__(self) -> None:
  954. self.c += 1
  955. def __exit__(self, exc_type, exc_val, exc_tb) -> None:
  956. self.c -= 1
  957. def test_dummy_context() -> None:
  958. c = DummyContext()
  959. with c:
  960. assert c.c == 1
  961. assert c.c == 0
  962. [case testWithNativeVarArgs]
  963. class DummyContext:
  964. def __init__(self):
  965. self.c = 0
  966. def __enter__(self) -> None:
  967. self.c += 1
  968. def __exit__(self, *args: object) -> None:
  969. self.c -= 1
  970. def test_dummy_context() -> None:
  971. c = DummyContext()
  972. with c:
  973. assert c.c == 1
  974. assert c.c == 0