test_grammar.py 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013
  1. # Python test set -- part 1, grammar.
  2. # This just tests whether the parser accepts them all.
  3. from test.support import check_syntax_error
  4. from test.support import import_helper
  5. from test.support.warnings_helper import check_syntax_warning
  6. import inspect
  7. import unittest
  8. import sys
  9. import warnings
  10. # testing import *
  11. from sys import *
  12. # different import patterns to check that __annotations__ does not interfere
  13. # with import machinery
  14. import test.ann_module as ann_module
  15. import typing
  16. from collections import ChainMap
  17. from test import ann_module2
  18. import test
  19. # These are shared with test_tokenize and other test modules.
  20. #
  21. # Note: since several test cases filter out floats by looking for "e" and ".",
  22. # don't add hexadecimal literals that contain "e" or "E".
  23. VALID_UNDERSCORE_LITERALS = [
  24. '0_0_0',
  25. '4_2',
  26. '1_0000_0000',
  27. '0b1001_0100',
  28. '0xffff_ffff',
  29. '0o5_7_7',
  30. '1_00_00.5',
  31. '1_00_00.5e5',
  32. '1_00_00e5_1',
  33. '1e1_0',
  34. '.1_4',
  35. '.1_4e1',
  36. '0b_0',
  37. '0x_f',
  38. '0o_5',
  39. '1_00_00j',
  40. '1_00_00.5j',
  41. '1_00_00e5_1j',
  42. '.1_4j',
  43. '(1_2.5+3_3j)',
  44. '(.5_6j)',
  45. ]
  46. INVALID_UNDERSCORE_LITERALS = [
  47. # Trailing underscores:
  48. '0_',
  49. '42_',
  50. '1.4j_',
  51. '0x_',
  52. '0b1_',
  53. '0xf_',
  54. '0o5_',
  55. '0 if 1_Else 1',
  56. # Underscores in the base selector:
  57. '0_b0',
  58. '0_xf',
  59. '0_o5',
  60. # Old-style octal, still disallowed:
  61. '0_7',
  62. '09_99',
  63. # Multiple consecutive underscores:
  64. '4_______2',
  65. '0.1__4',
  66. '0.1__4j',
  67. '0b1001__0100',
  68. '0xffff__ffff',
  69. '0x___',
  70. '0o5__77',
  71. '1e1__0',
  72. '1e1__0j',
  73. # Underscore right before a dot:
  74. '1_.4',
  75. '1_.4j',
  76. # Underscore right after a dot:
  77. '1._4',
  78. '1._4j',
  79. '._5',
  80. '._5j',
  81. # Underscore right after a sign:
  82. '1.0e+_1',
  83. '1.0e+_1j',
  84. # Underscore right before j:
  85. '1.4_j',
  86. '1.4e5_j',
  87. # Underscore right before e:
  88. '1_e1',
  89. '1.4_e1',
  90. '1.4_e1j',
  91. # Underscore right after e:
  92. '1e_1',
  93. '1.4e_1',
  94. '1.4e_1j',
  95. # Complex cases with parens:
  96. '(1+1.5_j_)',
  97. '(1+1.5_j)',
  98. ]
  99. class TokenTests(unittest.TestCase):
  100. from test.support import check_syntax_error
  101. from test.support.warnings_helper import check_syntax_warning
  102. def test_backslash(self):
  103. # Backslash means line continuation:
  104. x = 1 \
  105. + 1
  106. self.assertEqual(x, 2, 'backslash for line continuation')
  107. # Backslash does not means continuation in comments :\
  108. x = 0
  109. self.assertEqual(x, 0, 'backslash ending comment')
  110. def test_plain_integers(self):
  111. self.assertEqual(type(000), type(0))
  112. self.assertEqual(0xff, 255)
  113. self.assertEqual(0o377, 255)
  114. self.assertEqual(2147483647, 0o17777777777)
  115. self.assertEqual(0b1001, 9)
  116. # "0x" is not a valid literal
  117. self.assertRaises(SyntaxError, eval, "0x")
  118. from sys import maxsize
  119. if maxsize == 2147483647:
  120. self.assertEqual(-2147483647-1, -0o20000000000)
  121. # XXX -2147483648
  122. self.assertTrue(0o37777777777 > 0)
  123. self.assertTrue(0xffffffff > 0)
  124. self.assertTrue(0b1111111111111111111111111111111 > 0)
  125. for s in ('2147483648', '0o40000000000', '0x100000000',
  126. '0b10000000000000000000000000000000'):
  127. try:
  128. x = eval(s)
  129. except OverflowError:
  130. self.fail("OverflowError on huge integer literal %r" % s)
  131. elif maxsize == 9223372036854775807:
  132. self.assertEqual(-9223372036854775807-1, -0o1000000000000000000000)
  133. self.assertTrue(0o1777777777777777777777 > 0)
  134. self.assertTrue(0xffffffffffffffff > 0)
  135. self.assertTrue(0b11111111111111111111111111111111111111111111111111111111111111 > 0)
  136. for s in '9223372036854775808', '0o2000000000000000000000', \
  137. '0x10000000000000000', \
  138. '0b100000000000000000000000000000000000000000000000000000000000000':
  139. try:
  140. x = eval(s)
  141. except OverflowError:
  142. self.fail("OverflowError on huge integer literal %r" % s)
  143. else:
  144. self.fail('Weird maxsize value %r' % maxsize)
  145. def test_long_integers(self):
  146. x = 0
  147. x = 0xffffffffffffffff
  148. x = 0Xffffffffffffffff
  149. x = 0o77777777777777777
  150. x = 0O77777777777777777
  151. x = 123456789012345678901234567890
  152. x = 0b100000000000000000000000000000000000000000000000000000000000000000000
  153. x = 0B111111111111111111111111111111111111111111111111111111111111111111111
  154. def test_floats(self):
  155. x = 3.14
  156. x = 314.
  157. x = 0.314
  158. # XXX x = 000.314
  159. x = .314
  160. x = 3e14
  161. x = 3E14
  162. x = 3e-14
  163. x = 3e+14
  164. x = 3.e14
  165. x = .3e14
  166. x = 3.1e4
  167. def test_float_exponent_tokenization(self):
  168. # See issue 21642.
  169. with warnings.catch_warnings():
  170. warnings.simplefilter('ignore', SyntaxWarning)
  171. self.assertEqual(eval("1 if 1else 0"), 1)
  172. self.assertEqual(eval("1 if 0else 0"), 0)
  173. self.assertRaises(SyntaxError, eval, "0 if 1Else 0")
  174. def test_underscore_literals(self):
  175. for lit in VALID_UNDERSCORE_LITERALS:
  176. self.assertEqual(eval(lit), eval(lit.replace('_', '')))
  177. for lit in INVALID_UNDERSCORE_LITERALS:
  178. self.assertRaises(SyntaxError, eval, lit)
  179. # Sanity check: no literal begins with an underscore
  180. self.assertRaises(NameError, eval, "_0")
  181. def test_bad_numerical_literals(self):
  182. check = self.check_syntax_error
  183. check("0b12", "invalid digit '2' in binary literal")
  184. check("0b1_2", "invalid digit '2' in binary literal")
  185. check("0b2", "invalid digit '2' in binary literal")
  186. check("0b1_", "invalid binary literal")
  187. check("0b", "invalid binary literal")
  188. check("0o18", "invalid digit '8' in octal literal")
  189. check("0o1_8", "invalid digit '8' in octal literal")
  190. check("0o8", "invalid digit '8' in octal literal")
  191. check("0o1_", "invalid octal literal")
  192. check("0o", "invalid octal literal")
  193. check("0x1_", "invalid hexadecimal literal")
  194. check("0x", "invalid hexadecimal literal")
  195. check("1_", "invalid decimal literal")
  196. check("012",
  197. "leading zeros in decimal integer literals are not permitted; "
  198. "use an 0o prefix for octal integers")
  199. check("1.2_", "invalid decimal literal")
  200. check("1e2_", "invalid decimal literal")
  201. check("1e+", "invalid decimal literal")
  202. def test_end_of_numerical_literals(self):
  203. def check(test, error=False):
  204. with self.subTest(expr=test):
  205. if error:
  206. with warnings.catch_warnings(record=True) as w:
  207. with self.assertRaisesRegex(SyntaxError,
  208. r'invalid \w+ literal'):
  209. compile(test, "<testcase>", "eval")
  210. self.assertEqual(w, [])
  211. else:
  212. self.check_syntax_warning(test,
  213. errtext=r'invalid \w+ literal')
  214. for num in "0xf", "0o7", "0b1", "9", "0", "1.", "1e3", "1j":
  215. compile(num, "<testcase>", "eval")
  216. check(f"{num}and x", error=(num == "0xf"))
  217. check(f"{num}or x", error=(num == "0"))
  218. check(f"{num}in x")
  219. check(f"{num}not in x")
  220. check(f"{num}if x else y")
  221. check(f"x if {num}else y", error=(num == "0xf"))
  222. check(f"[{num}for x in ()]")
  223. check(f"{num}spam", error=True)
  224. with warnings.catch_warnings():
  225. warnings.filterwarnings('ignore', '"is" with a literal',
  226. SyntaxWarning)
  227. with self.assertWarnsRegex(SyntaxWarning,
  228. r'invalid \w+ literal'):
  229. compile(f"{num}is x", "<testcase>", "eval")
  230. warnings.simplefilter('error', SyntaxWarning)
  231. with self.assertRaisesRegex(SyntaxError,
  232. r'invalid \w+ literal'):
  233. compile(f"{num}is x", "<testcase>", "eval")
  234. check("[0x1ffor x in ()]")
  235. check("[0x1for x in ()]")
  236. check("[0xfor x in ()]")
  237. def test_string_literals(self):
  238. x = ''; y = ""; self.assertTrue(len(x) == 0 and x == y)
  239. x = '\''; y = "'"; self.assertTrue(len(x) == 1 and x == y and ord(x) == 39)
  240. x = '"'; y = "\""; self.assertTrue(len(x) == 1 and x == y and ord(x) == 34)
  241. x = "doesn't \"shrink\" does it"
  242. y = 'doesn\'t "shrink" does it'
  243. self.assertTrue(len(x) == 24 and x == y)
  244. x = "does \"shrink\" doesn't it"
  245. y = 'does "shrink" doesn\'t it'
  246. self.assertTrue(len(x) == 24 and x == y)
  247. x = """
  248. The "quick"
  249. brown fox
  250. jumps over
  251. the 'lazy' dog.
  252. """
  253. y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
  254. self.assertEqual(x, y)
  255. y = '''
  256. The "quick"
  257. brown fox
  258. jumps over
  259. the 'lazy' dog.
  260. '''
  261. self.assertEqual(x, y)
  262. y = "\n\
  263. The \"quick\"\n\
  264. brown fox\n\
  265. jumps over\n\
  266. the 'lazy' dog.\n\
  267. "
  268. self.assertEqual(x, y)
  269. y = '\n\
  270. The \"quick\"\n\
  271. brown fox\n\
  272. jumps over\n\
  273. the \'lazy\' dog.\n\
  274. '
  275. self.assertEqual(x, y)
  276. def test_ellipsis(self):
  277. x = ...
  278. self.assertTrue(x is Ellipsis)
  279. self.assertRaises(SyntaxError, eval, ".. .")
  280. def test_eof_error(self):
  281. samples = ("def foo(", "\ndef foo(", "def foo(\n")
  282. for s in samples:
  283. with self.assertRaises(SyntaxError) as cm:
  284. compile(s, "<test>", "exec")
  285. self.assertIn("was never closed", str(cm.exception))
  286. var_annot_global: int # a global annotated is necessary for test_var_annot
  287. # custom namespace for testing __annotations__
  288. class CNS:
  289. def __init__(self):
  290. self._dct = {}
  291. def __setitem__(self, item, value):
  292. self._dct[item.lower()] = value
  293. def __getitem__(self, item):
  294. return self._dct[item]
  295. class GrammarTests(unittest.TestCase):
  296. from test.support import check_syntax_error
  297. from test.support.warnings_helper import check_syntax_warning
  298. from test.support.warnings_helper import check_no_warnings
  299. # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
  300. # XXX can't test in a script -- this rule is only used when interactive
  301. # file_input: (NEWLINE | stmt)* ENDMARKER
  302. # Being tested as this very moment this very module
  303. # expr_input: testlist NEWLINE
  304. # XXX Hard to test -- used only in calls to input()
  305. def test_eval_input(self):
  306. # testlist ENDMARKER
  307. x = eval('1, 0 or 1')
  308. def test_var_annot_basics(self):
  309. # all these should be allowed
  310. var1: int = 5
  311. var2: [int, str]
  312. my_lst = [42]
  313. def one():
  314. return 1
  315. int.new_attr: int
  316. [list][0]: type
  317. my_lst[one()-1]: int = 5
  318. self.assertEqual(my_lst, [5])
  319. def test_var_annot_syntax_errors(self):
  320. # parser pass
  321. check_syntax_error(self, "def f: int")
  322. check_syntax_error(self, "x: int: str")
  323. check_syntax_error(self, "def f():\n"
  324. " nonlocal x: int\n")
  325. # AST pass
  326. check_syntax_error(self, "[x, 0]: int\n")
  327. check_syntax_error(self, "f(): int\n")
  328. check_syntax_error(self, "(x,): int")
  329. check_syntax_error(self, "def f():\n"
  330. " (x, y): int = (1, 2)\n")
  331. # symtable pass
  332. check_syntax_error(self, "def f():\n"
  333. " x: int\n"
  334. " global x\n")
  335. check_syntax_error(self, "def f():\n"
  336. " global x\n"
  337. " x: int\n")
  338. def test_var_annot_basic_semantics(self):
  339. # execution order
  340. with self.assertRaises(ZeroDivisionError):
  341. no_name[does_not_exist]: no_name_again = 1/0
  342. with self.assertRaises(NameError):
  343. no_name[does_not_exist]: 1/0 = 0
  344. global var_annot_global
  345. # function semantics
  346. def f():
  347. st: str = "Hello"
  348. a.b: int = (1, 2)
  349. return st
  350. self.assertEqual(f.__annotations__, {})
  351. def f_OK():
  352. x: 1/0
  353. f_OK()
  354. def fbad():
  355. x: int
  356. print(x)
  357. with self.assertRaises(UnboundLocalError):
  358. fbad()
  359. def f2bad():
  360. (no_such_global): int
  361. print(no_such_global)
  362. try:
  363. f2bad()
  364. except Exception as e:
  365. self.assertIs(type(e), NameError)
  366. # class semantics
  367. class C:
  368. __foo: int
  369. s: str = "attr"
  370. z = 2
  371. def __init__(self, x):
  372. self.x: int = x
  373. self.assertEqual(C.__annotations__, {'_C__foo': int, 's': str})
  374. with self.assertRaises(NameError):
  375. class CBad:
  376. no_such_name_defined.attr: int = 0
  377. with self.assertRaises(NameError):
  378. class Cbad2(C):
  379. x: int
  380. x.y: list = []
  381. def test_annotations_inheritance(self):
  382. # Check that annotations are not inherited by derived classes
  383. class A:
  384. attr: int
  385. class B(A):
  386. pass
  387. class C(A):
  388. attr: str
  389. class D:
  390. attr2: int
  391. class E(A, D):
  392. pass
  393. class F(C, A):
  394. pass
  395. self.assertEqual(A.__annotations__, {"attr": int})
  396. self.assertEqual(B.__annotations__, {})
  397. self.assertEqual(C.__annotations__, {"attr" : str})
  398. self.assertEqual(D.__annotations__, {"attr2" : int})
  399. self.assertEqual(E.__annotations__, {})
  400. self.assertEqual(F.__annotations__, {})
  401. def test_var_annot_metaclass_semantics(self):
  402. class CMeta(type):
  403. @classmethod
  404. def __prepare__(metacls, name, bases, **kwds):
  405. return {'__annotations__': CNS()}
  406. class CC(metaclass=CMeta):
  407. XX: 'ANNOT'
  408. self.assertEqual(CC.__annotations__['xx'], 'ANNOT')
  409. def test_var_annot_module_semantics(self):
  410. self.assertEqual(test.__annotations__, {})
  411. self.assertEqual(ann_module.__annotations__,
  412. {1: 2, 'x': int, 'y': str, 'f': typing.Tuple[int, int], 'u': int | float})
  413. self.assertEqual(ann_module.M.__annotations__,
  414. {'123': 123, 'o': type})
  415. self.assertEqual(ann_module2.__annotations__, {})
  416. def test_var_annot_in_module(self):
  417. # check that functions fail the same way when executed
  418. # outside of module where they were defined
  419. ann_module3 = import_helper.import_fresh_module("test.ann_module3")
  420. with self.assertRaises(NameError):
  421. ann_module3.f_bad_ann()
  422. with self.assertRaises(NameError):
  423. ann_module3.g_bad_ann()
  424. with self.assertRaises(NameError):
  425. ann_module3.D_bad_ann(5)
  426. def test_var_annot_simple_exec(self):
  427. gns = {}; lns= {}
  428. exec("'docstring'\n"
  429. "__annotations__[1] = 2\n"
  430. "x: int = 5\n", gns, lns)
  431. self.assertEqual(lns["__annotations__"], {1: 2, 'x': int})
  432. with self.assertRaises(KeyError):
  433. gns['__annotations__']
  434. def test_var_annot_custom_maps(self):
  435. # tests with custom locals() and __annotations__
  436. ns = {'__annotations__': CNS()}
  437. exec('X: int; Z: str = "Z"; (w): complex = 1j', ns)
  438. self.assertEqual(ns['__annotations__']['x'], int)
  439. self.assertEqual(ns['__annotations__']['z'], str)
  440. with self.assertRaises(KeyError):
  441. ns['__annotations__']['w']
  442. nonloc_ns = {}
  443. class CNS2:
  444. def __init__(self):
  445. self._dct = {}
  446. def __setitem__(self, item, value):
  447. nonlocal nonloc_ns
  448. self._dct[item] = value
  449. nonloc_ns[item] = value
  450. def __getitem__(self, item):
  451. return self._dct[item]
  452. exec('x: int = 1', {}, CNS2())
  453. self.assertEqual(nonloc_ns['__annotations__']['x'], int)
  454. def test_var_annot_refleak(self):
  455. # complex case: custom locals plus custom __annotations__
  456. # this was causing refleak
  457. cns = CNS()
  458. nonloc_ns = {'__annotations__': cns}
  459. class CNS2:
  460. def __init__(self):
  461. self._dct = {'__annotations__': cns}
  462. def __setitem__(self, item, value):
  463. nonlocal nonloc_ns
  464. self._dct[item] = value
  465. nonloc_ns[item] = value
  466. def __getitem__(self, item):
  467. return self._dct[item]
  468. exec('X: str', {}, CNS2())
  469. self.assertEqual(nonloc_ns['__annotations__']['x'], str)
  470. def test_var_annot_rhs(self):
  471. ns = {}
  472. exec('x: tuple = 1, 2', ns)
  473. self.assertEqual(ns['x'], (1, 2))
  474. stmt = ('def f():\n'
  475. ' x: int = yield')
  476. exec(stmt, ns)
  477. self.assertEqual(list(ns['f']()), [None])
  478. ns = {"a": 1, 'b': (2, 3, 4), "c":5, "Tuple": typing.Tuple}
  479. exec('x: Tuple[int, ...] = a,*b,c', ns)
  480. self.assertEqual(ns['x'], (1, 2, 3, 4, 5))
  481. def test_funcdef(self):
  482. ### [decorators] 'def' NAME parameters ['->' test] ':' suite
  483. ### decorator: '@' namedexpr_test NEWLINE
  484. ### decorators: decorator+
  485. ### parameters: '(' [typedargslist] ')'
  486. ### typedargslist: ((tfpdef ['=' test] ',')*
  487. ### ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
  488. ### | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
  489. ### tfpdef: NAME [':' test]
  490. ### varargslist: ((vfpdef ['=' test] ',')*
  491. ### ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef)
  492. ### | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
  493. ### vfpdef: NAME
  494. def f1(): pass
  495. f1()
  496. f1(*())
  497. f1(*(), **{})
  498. def f2(one_argument): pass
  499. def f3(two, arguments): pass
  500. self.assertEqual(f2.__code__.co_varnames, ('one_argument',))
  501. self.assertEqual(f3.__code__.co_varnames, ('two', 'arguments'))
  502. def a1(one_arg,): pass
  503. def a2(two, args,): pass
  504. def v0(*rest): pass
  505. def v1(a, *rest): pass
  506. def v2(a, b, *rest): pass
  507. f1()
  508. f2(1)
  509. f2(1,)
  510. f3(1, 2)
  511. f3(1, 2,)
  512. v0()
  513. v0(1)
  514. v0(1,)
  515. v0(1,2)
  516. v0(1,2,3,4,5,6,7,8,9,0)
  517. v1(1)
  518. v1(1,)
  519. v1(1,2)
  520. v1(1,2,3)
  521. v1(1,2,3,4,5,6,7,8,9,0)
  522. v2(1,2)
  523. v2(1,2,3)
  524. v2(1,2,3,4)
  525. v2(1,2,3,4,5,6,7,8,9,0)
  526. def d01(a=1): pass
  527. d01()
  528. d01(1)
  529. d01(*(1,))
  530. d01(*[] or [2])
  531. d01(*() or (), *{} and (), **() or {})
  532. d01(**{'a':2})
  533. d01(**{'a':2} or {})
  534. def d11(a, b=1): pass
  535. d11(1)
  536. d11(1, 2)
  537. d11(1, **{'b':2})
  538. def d21(a, b, c=1): pass
  539. d21(1, 2)
  540. d21(1, 2, 3)
  541. d21(*(1, 2, 3))
  542. d21(1, *(2, 3))
  543. d21(1, 2, *(3,))
  544. d21(1, 2, **{'c':3})
  545. def d02(a=1, b=2): pass
  546. d02()
  547. d02(1)
  548. d02(1, 2)
  549. d02(*(1, 2))
  550. d02(1, *(2,))
  551. d02(1, **{'b':2})
  552. d02(**{'a': 1, 'b': 2})
  553. def d12(a, b=1, c=2): pass
  554. d12(1)
  555. d12(1, 2)
  556. d12(1, 2, 3)
  557. def d22(a, b, c=1, d=2): pass
  558. d22(1, 2)
  559. d22(1, 2, 3)
  560. d22(1, 2, 3, 4)
  561. def d01v(a=1, *rest): pass
  562. d01v()
  563. d01v(1)
  564. d01v(1, 2)
  565. d01v(*(1, 2, 3, 4))
  566. d01v(*(1,))
  567. d01v(**{'a':2})
  568. def d11v(a, b=1, *rest): pass
  569. d11v(1)
  570. d11v(1, 2)
  571. d11v(1, 2, 3)
  572. def d21v(a, b, c=1, *rest): pass
  573. d21v(1, 2)
  574. d21v(1, 2, 3)
  575. d21v(1, 2, 3, 4)
  576. d21v(*(1, 2, 3, 4))
  577. d21v(1, 2, **{'c': 3})
  578. def d02v(a=1, b=2, *rest): pass
  579. d02v()
  580. d02v(1)
  581. d02v(1, 2)
  582. d02v(1, 2, 3)
  583. d02v(1, *(2, 3, 4))
  584. d02v(**{'a': 1, 'b': 2})
  585. def d12v(a, b=1, c=2, *rest): pass
  586. d12v(1)
  587. d12v(1, 2)
  588. d12v(1, 2, 3)
  589. d12v(1, 2, 3, 4)
  590. d12v(*(1, 2, 3, 4))
  591. d12v(1, 2, *(3, 4, 5))
  592. d12v(1, *(2,), **{'c': 3})
  593. def d22v(a, b, c=1, d=2, *rest): pass
  594. d22v(1, 2)
  595. d22v(1, 2, 3)
  596. d22v(1, 2, 3, 4)
  597. d22v(1, 2, 3, 4, 5)
  598. d22v(*(1, 2, 3, 4))
  599. d22v(1, 2, *(3, 4, 5))
  600. d22v(1, *(2, 3), **{'d': 4})
  601. # keyword argument type tests
  602. with warnings.catch_warnings():
  603. warnings.simplefilter('ignore', BytesWarning)
  604. try:
  605. str('x', **{b'foo':1 })
  606. except TypeError:
  607. pass
  608. else:
  609. self.fail('Bytes should not work as keyword argument names')
  610. # keyword only argument tests
  611. def pos0key1(*, key): return key
  612. pos0key1(key=100)
  613. def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2
  614. pos2key2(1, 2, k1=100)
  615. pos2key2(1, 2, k1=100, k2=200)
  616. pos2key2(1, 2, k2=100, k1=200)
  617. def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg
  618. pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200)
  619. pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100)
  620. self.assertRaises(SyntaxError, eval, "def f(*): pass")
  621. self.assertRaises(SyntaxError, eval, "def f(*,): pass")
  622. self.assertRaises(SyntaxError, eval, "def f(*, **kwds): pass")
  623. # keyword arguments after *arglist
  624. def f(*args, **kwargs):
  625. return args, kwargs
  626. self.assertEqual(f(1, x=2, *[3, 4], y=5), ((1, 3, 4),
  627. {'x':2, 'y':5}))
  628. self.assertEqual(f(1, *(2,3), 4), ((1, 2, 3, 4), {}))
  629. self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
  630. self.assertEqual(f(**{'eggs':'scrambled', 'spam':'fried'}),
  631. ((), {'eggs':'scrambled', 'spam':'fried'}))
  632. self.assertEqual(f(spam='fried', **{'eggs':'scrambled'}),
  633. ((), {'eggs':'scrambled', 'spam':'fried'}))
  634. # Check ast errors in *args and *kwargs
  635. check_syntax_error(self, "f(*g(1=2))")
  636. check_syntax_error(self, "f(**g(1=2))")
  637. # argument annotation tests
  638. def f(x) -> list: pass
  639. self.assertEqual(f.__annotations__, {'return': list})
  640. def f(x: int): pass
  641. self.assertEqual(f.__annotations__, {'x': int})
  642. def f(x: int, /): pass
  643. self.assertEqual(f.__annotations__, {'x': int})
  644. def f(x: int = 34, /): pass
  645. self.assertEqual(f.__annotations__, {'x': int})
  646. def f(*x: str): pass
  647. self.assertEqual(f.__annotations__, {'x': str})
  648. def f(**x: float): pass
  649. self.assertEqual(f.__annotations__, {'x': float})
  650. def f(x, y: 1+2): pass
  651. self.assertEqual(f.__annotations__, {'y': 3})
  652. def f(x, y: 1+2, /): pass
  653. self.assertEqual(f.__annotations__, {'y': 3})
  654. def f(a, b: 1, c: 2, d): pass
  655. self.assertEqual(f.__annotations__, {'b': 1, 'c': 2})
  656. def f(a, b: 1, /, c: 2, d): pass
  657. self.assertEqual(f.__annotations__, {'b': 1, 'c': 2})
  658. def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6): pass
  659. self.assertEqual(f.__annotations__,
  660. {'b': 1, 'c': 2, 'e': 3, 'g': 6})
  661. def f(a, b: 1, c: 2, d, e: 3 = 4, f=5, *g: 6, h: 7, i=8, j: 9 = 10,
  662. **k: 11) -> 12: pass
  663. self.assertEqual(f.__annotations__,
  664. {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9,
  665. 'k': 11, 'return': 12})
  666. def f(a, b: 1, c: 2, d, e: 3 = 4, f: int = 5, /, *g: 6, h: 7, i=8, j: 9 = 10,
  667. **k: 11) -> 12: pass
  668. self.assertEqual(f.__annotations__,
  669. {'b': 1, 'c': 2, 'e': 3, 'f': int, 'g': 6, 'h': 7, 'j': 9,
  670. 'k': 11, 'return': 12})
  671. # Check for issue #20625 -- annotations mangling
  672. class Spam:
  673. def f(self, *, __kw: 1):
  674. pass
  675. class Ham(Spam): pass
  676. self.assertEqual(Spam.f.__annotations__, {'_Spam__kw': 1})
  677. self.assertEqual(Ham.f.__annotations__, {'_Spam__kw': 1})
  678. # Check for SF Bug #1697248 - mixing decorators and a return annotation
  679. def null(x): return x
  680. @null
  681. def f(x) -> list: pass
  682. self.assertEqual(f.__annotations__, {'return': list})
  683. # Test expressions as decorators (PEP 614):
  684. @False or null
  685. def f(x): pass
  686. @d := null
  687. def f(x): pass
  688. @lambda f: null(f)
  689. def f(x): pass
  690. @[..., null, ...][1]
  691. def f(x): pass
  692. @null(null)(null)
  693. def f(x): pass
  694. @[null][0].__call__.__call__
  695. def f(x): pass
  696. # test closures with a variety of opargs
  697. closure = 1
  698. def f(): return closure
  699. def f(x=1): return closure
  700. def f(*, k=1): return closure
  701. def f() -> int: return closure
  702. # Check trailing commas are permitted in funcdef argument list
  703. def f(a,): pass
  704. def f(*args,): pass
  705. def f(**kwds,): pass
  706. def f(a, *args,): pass
  707. def f(a, **kwds,): pass
  708. def f(*args, b,): pass
  709. def f(*, b,): pass
  710. def f(*args, **kwds,): pass
  711. def f(a, *args, b,): pass
  712. def f(a, *, b,): pass
  713. def f(a, *args, **kwds,): pass
  714. def f(*args, b, **kwds,): pass
  715. def f(*, b, **kwds,): pass
  716. def f(a, *args, b, **kwds,): pass
  717. def f(a, *, b, **kwds,): pass
  718. def test_lambdef(self):
  719. ### lambdef: 'lambda' [varargslist] ':' test
  720. l1 = lambda : 0
  721. self.assertEqual(l1(), 0)
  722. l2 = lambda : a[d] # XXX just testing the expression
  723. l3 = lambda : [2 < x for x in [-1, 3, 0]]
  724. self.assertEqual(l3(), [0, 1, 0])
  725. l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
  726. self.assertEqual(l4(), 1)
  727. l5 = lambda x, y, z=2: x + y + z
  728. self.assertEqual(l5(1, 2), 5)
  729. self.assertEqual(l5(1, 2, 3), 6)
  730. check_syntax_error(self, "lambda x: x = 2")
  731. check_syntax_error(self, "lambda (None,): None")
  732. l6 = lambda x, y, *, k=20: x+y+k
  733. self.assertEqual(l6(1,2), 1+2+20)
  734. self.assertEqual(l6(1,2,k=10), 1+2+10)
  735. # check that trailing commas are permitted
  736. l10 = lambda a,: 0
  737. l11 = lambda *args,: 0
  738. l12 = lambda **kwds,: 0
  739. l13 = lambda a, *args,: 0
  740. l14 = lambda a, **kwds,: 0
  741. l15 = lambda *args, b,: 0
  742. l16 = lambda *, b,: 0
  743. l17 = lambda *args, **kwds,: 0
  744. l18 = lambda a, *args, b,: 0
  745. l19 = lambda a, *, b,: 0
  746. l20 = lambda a, *args, **kwds,: 0
  747. l21 = lambda *args, b, **kwds,: 0
  748. l22 = lambda *, b, **kwds,: 0
  749. l23 = lambda a, *args, b, **kwds,: 0
  750. l24 = lambda a, *, b, **kwds,: 0
  751. ### stmt: simple_stmt | compound_stmt
  752. # Tested below
  753. def test_simple_stmt(self):
  754. ### simple_stmt: small_stmt (';' small_stmt)* [';']
  755. x = 1; pass; del x
  756. def foo():
  757. # verify statements that end with semi-colons
  758. x = 1; pass; del x;
  759. foo()
  760. ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
  761. # Tested below
  762. def test_expr_stmt(self):
  763. # (exprlist '=')* exprlist
  764. 1
  765. 1, 2, 3
  766. x = 1
  767. x = 1, 2, 3
  768. x = y = z = 1, 2, 3
  769. x, y, z = 1, 2, 3
  770. abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
  771. check_syntax_error(self, "x + 1 = 1")
  772. check_syntax_error(self, "a + 1 = b + 2")
  773. # Check the heuristic for print & exec covers significant cases
  774. # As well as placing some limits on false positives
  775. def test_former_statements_refer_to_builtins(self):
  776. keywords = "print", "exec"
  777. # Cases where we want the custom error
  778. cases = [
  779. "{} foo",
  780. "{} {{1:foo}}",
  781. "if 1: {} foo",
  782. "if 1: {} {{1:foo}}",
  783. "if 1:\n {} foo",
  784. "if 1:\n {} {{1:foo}}",
  785. ]
  786. for keyword in keywords:
  787. custom_msg = "call to '{}'".format(keyword)
  788. for case in cases:
  789. source = case.format(keyword)
  790. with self.subTest(source=source):
  791. with self.assertRaisesRegex(SyntaxError, custom_msg):
  792. exec(source)
  793. source = source.replace("foo", "(foo.)")
  794. with self.subTest(source=source):
  795. with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
  796. exec(source)
  797. def test_del_stmt(self):
  798. # 'del' exprlist
  799. abc = [1,2,3]
  800. x, y, z = abc
  801. xyz = x, y, z
  802. del abc
  803. del x, y, (z, xyz)
  804. x, y, z = "xyz"
  805. del x
  806. del y,
  807. del (z)
  808. del ()
  809. a, b, c, d, e, f, g = "abcdefg"
  810. del a, (b, c), (d, (e, f))
  811. a, b, c, d, e, f, g = "abcdefg"
  812. del a, [b, c], (d, [e, f])
  813. abcd = list("abcd")
  814. del abcd[1:2]
  815. compile("del a, (b[0].c, (d.e, f.g[1:2])), [h.i.j], ()", "<testcase>", "exec")
  816. def test_pass_stmt(self):
  817. # 'pass'
  818. pass
  819. # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
  820. # Tested below
  821. def test_break_stmt(self):
  822. # 'break'
  823. while 1: break
  824. def test_continue_stmt(self):
  825. # 'continue'
  826. i = 1
  827. while i: i = 0; continue
  828. msg = ""
  829. while not msg:
  830. msg = "ok"
  831. try:
  832. continue
  833. msg = "continue failed to continue inside try"
  834. except:
  835. msg = "continue inside try called except block"
  836. if msg != "ok":
  837. self.fail(msg)
  838. msg = ""
  839. while not msg:
  840. msg = "finally block not called"
  841. try:
  842. continue
  843. finally:
  844. msg = "ok"
  845. if msg != "ok":
  846. self.fail(msg)
  847. def test_break_continue_loop(self):
  848. # This test warrants an explanation. It is a test specifically for SF bugs
  849. # #463359 and #462937. The bug is that a 'break' statement executed or
  850. # exception raised inside a try/except inside a loop, *after* a continue
  851. # statement has been executed in that loop, will cause the wrong number of
  852. # arguments to be popped off the stack and the instruction pointer reset to
  853. # a very small number (usually 0.) Because of this, the following test
  854. # *must* written as a function, and the tracking vars *must* be function
  855. # arguments with default values. Otherwise, the test will loop and loop.
  856. def test_inner(extra_burning_oil = 1, count=0):
  857. big_hippo = 2
  858. while big_hippo:
  859. count += 1
  860. try:
  861. if extra_burning_oil and big_hippo == 1:
  862. extra_burning_oil -= 1
  863. break
  864. big_hippo -= 1
  865. continue
  866. except:
  867. raise
  868. if count > 2 or big_hippo != 1:
  869. self.fail("continue then break in try/except in loop broken!")
  870. test_inner()
  871. def test_return(self):
  872. # 'return' [testlist_star_expr]
  873. def g1(): return
  874. def g2(): return 1
  875. def g3():
  876. z = [2, 3]
  877. return 1, *z
  878. g1()
  879. x = g2()
  880. y = g3()
  881. self.assertEqual(y, (1, 2, 3), "unparenthesized star expr return")
  882. check_syntax_error(self, "class foo:return 1")
  883. def test_break_in_finally(self):
  884. count = 0
  885. while count < 2:
  886. count += 1
  887. try:
  888. pass
  889. finally:
  890. break
  891. self.assertEqual(count, 1)
  892. count = 0
  893. while count < 2:
  894. count += 1
  895. try:
  896. continue
  897. finally:
  898. break
  899. self.assertEqual(count, 1)
  900. count = 0
  901. while count < 2:
  902. count += 1
  903. try:
  904. 1/0
  905. finally:
  906. break
  907. self.assertEqual(count, 1)
  908. for count in [0, 1]:
  909. self.assertEqual(count, 0)
  910. try:
  911. pass
  912. finally:
  913. break
  914. self.assertEqual(count, 0)
  915. for count in [0, 1]:
  916. self.assertEqual(count, 0)
  917. try:
  918. continue
  919. finally:
  920. break
  921. self.assertEqual(count, 0)
  922. for count in [0, 1]:
  923. self.assertEqual(count, 0)
  924. try:
  925. 1/0
  926. finally:
  927. break
  928. self.assertEqual(count, 0)
  929. def test_continue_in_finally(self):
  930. count = 0
  931. while count < 2:
  932. count += 1
  933. try:
  934. pass
  935. finally:
  936. continue
  937. break
  938. self.assertEqual(count, 2)
  939. count = 0
  940. while count < 2:
  941. count += 1
  942. try:
  943. break
  944. finally:
  945. continue
  946. self.assertEqual(count, 2)
  947. count = 0
  948. while count < 2:
  949. count += 1
  950. try:
  951. 1/0
  952. finally:
  953. continue
  954. break
  955. self.assertEqual(count, 2)
  956. for count in [0, 1]:
  957. try:
  958. pass
  959. finally:
  960. continue
  961. break
  962. self.assertEqual(count, 1)
  963. for count in [0, 1]:
  964. try:
  965. break
  966. finally:
  967. continue
  968. self.assertEqual(count, 1)
  969. for count in [0, 1]:
  970. try:
  971. 1/0
  972. finally:
  973. continue
  974. break
  975. self.assertEqual(count, 1)
  976. def test_return_in_finally(self):
  977. def g1():
  978. try:
  979. pass
  980. finally:
  981. return 1
  982. self.assertEqual(g1(), 1)
  983. def g2():
  984. try:
  985. return 2
  986. finally:
  987. return 3
  988. self.assertEqual(g2(), 3)
  989. def g3():
  990. try:
  991. 1/0
  992. finally:
  993. return 4
  994. self.assertEqual(g3(), 4)
  995. def test_break_in_finally_after_return(self):
  996. # See issue #37830
  997. def g1(x):
  998. for count in [0, 1]:
  999. count2 = 0
  1000. while count2 < 20:
  1001. count2 += 10
  1002. try:
  1003. return count + count2
  1004. finally:
  1005. if x:
  1006. break
  1007. return 'end', count, count2
  1008. self.assertEqual(g1(False), 10)
  1009. self.assertEqual(g1(True), ('end', 1, 10))
  1010. def g2(x):
  1011. for count in [0, 1]:
  1012. for count2 in [10, 20]:
  1013. try:
  1014. return count + count2
  1015. finally:
  1016. if x:
  1017. break
  1018. return 'end', count, count2
  1019. self.assertEqual(g2(False), 10)
  1020. self.assertEqual(g2(True), ('end', 1, 10))
  1021. def test_continue_in_finally_after_return(self):
  1022. # See issue #37830
  1023. def g1(x):
  1024. count = 0
  1025. while count < 100:
  1026. count += 1
  1027. try:
  1028. return count
  1029. finally:
  1030. if x:
  1031. continue
  1032. return 'end', count
  1033. self.assertEqual(g1(False), 1)
  1034. self.assertEqual(g1(True), ('end', 100))
  1035. def g2(x):
  1036. for count in [0, 1]:
  1037. try:
  1038. return count
  1039. finally:
  1040. if x:
  1041. continue
  1042. return 'end', count
  1043. self.assertEqual(g2(False), 0)
  1044. self.assertEqual(g2(True), ('end', 1))
  1045. def test_yield(self):
  1046. # Allowed as standalone statement
  1047. def g(): yield 1
  1048. def g(): yield from ()
  1049. # Allowed as RHS of assignment
  1050. def g(): x = yield 1
  1051. def g(): x = yield from ()
  1052. # Ordinary yield accepts implicit tuples
  1053. def g(): yield 1, 1
  1054. def g(): x = yield 1, 1
  1055. # 'yield from' does not
  1056. check_syntax_error(self, "def g(): yield from (), 1")
  1057. check_syntax_error(self, "def g(): x = yield from (), 1")
  1058. # Requires parentheses as subexpression
  1059. def g(): 1, (yield 1)
  1060. def g(): 1, (yield from ())
  1061. check_syntax_error(self, "def g(): 1, yield 1")
  1062. check_syntax_error(self, "def g(): 1, yield from ()")
  1063. # Requires parentheses as call argument
  1064. def g(): f((yield 1))
  1065. def g(): f((yield 1), 1)
  1066. def g(): f((yield from ()))
  1067. def g(): f((yield from ()), 1)
  1068. # Do not require parenthesis for tuple unpacking
  1069. def g(): rest = 4, 5, 6; yield 1, 2, 3, *rest
  1070. self.assertEqual(list(g()), [(1, 2, 3, 4, 5, 6)])
  1071. check_syntax_error(self, "def g(): f(yield 1)")
  1072. check_syntax_error(self, "def g(): f(yield 1, 1)")
  1073. check_syntax_error(self, "def g(): f(yield from ())")
  1074. check_syntax_error(self, "def g(): f(yield from (), 1)")
  1075. # Not allowed at top level
  1076. check_syntax_error(self, "yield")
  1077. check_syntax_error(self, "yield from")
  1078. # Not allowed at class scope
  1079. check_syntax_error(self, "class foo:yield 1")
  1080. check_syntax_error(self, "class foo:yield from ()")
  1081. # Check annotation refleak on SyntaxError
  1082. check_syntax_error(self, "def g(a:(yield)): pass")
  1083. def test_yield_in_comprehensions(self):
  1084. # Check yield in comprehensions
  1085. def g(): [x for x in [(yield 1)]]
  1086. def g(): [x for x in [(yield from ())]]
  1087. check = self.check_syntax_error
  1088. check("def g(): [(yield x) for x in ()]",
  1089. "'yield' inside list comprehension")
  1090. check("def g(): [x for x in () if not (yield x)]",
  1091. "'yield' inside list comprehension")
  1092. check("def g(): [y for x in () for y in [(yield x)]]",
  1093. "'yield' inside list comprehension")
  1094. check("def g(): {(yield x) for x in ()}",
  1095. "'yield' inside set comprehension")
  1096. check("def g(): {(yield x): x for x in ()}",
  1097. "'yield' inside dict comprehension")
  1098. check("def g(): {x: (yield x) for x in ()}",
  1099. "'yield' inside dict comprehension")
  1100. check("def g(): ((yield x) for x in ())",
  1101. "'yield' inside generator expression")
  1102. check("def g(): [(yield from x) for x in ()]",
  1103. "'yield' inside list comprehension")
  1104. check("class C: [(yield x) for x in ()]",
  1105. "'yield' inside list comprehension")
  1106. check("[(yield x) for x in ()]",
  1107. "'yield' inside list comprehension")
  1108. def test_raise(self):
  1109. # 'raise' test [',' test]
  1110. try: raise RuntimeError('just testing')
  1111. except RuntimeError: pass
  1112. try: raise KeyboardInterrupt
  1113. except KeyboardInterrupt: pass
  1114. def test_import(self):
  1115. # 'import' dotted_as_names
  1116. import sys
  1117. import time, sys
  1118. # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
  1119. from time import time
  1120. from time import (time)
  1121. # not testable inside a function, but already done at top of the module
  1122. # from sys import *
  1123. from sys import path, argv
  1124. from sys import (path, argv)
  1125. from sys import (path, argv,)
  1126. def test_global(self):
  1127. # 'global' NAME (',' NAME)*
  1128. global a
  1129. global a, b
  1130. global one, two, three, four, five, six, seven, eight, nine, ten
  1131. def test_nonlocal(self):
  1132. # 'nonlocal' NAME (',' NAME)*
  1133. x = 0
  1134. y = 0
  1135. def f():
  1136. nonlocal x
  1137. nonlocal x, y
  1138. def test_assert(self):
  1139. # assertTruestmt: 'assert' test [',' test]
  1140. assert 1
  1141. assert 1, 1
  1142. assert lambda x:x
  1143. assert 1, lambda x:x+1
  1144. try:
  1145. assert True
  1146. except AssertionError as e:
  1147. self.fail("'assert True' should not have raised an AssertionError")
  1148. try:
  1149. assert True, 'this should always pass'
  1150. except AssertionError as e:
  1151. self.fail("'assert True, msg' should not have "
  1152. "raised an AssertionError")
  1153. # these tests fail if python is run with -O, so check __debug__
  1154. @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
  1155. def test_assert_failures(self):
  1156. try:
  1157. assert 0, "msg"
  1158. except AssertionError as e:
  1159. self.assertEqual(e.args[0], "msg")
  1160. else:
  1161. self.fail("AssertionError not raised by assert 0")
  1162. try:
  1163. assert False
  1164. except AssertionError as e:
  1165. self.assertEqual(len(e.args), 0)
  1166. else:
  1167. self.fail("AssertionError not raised by 'assert False'")
  1168. def test_assert_syntax_warnings(self):
  1169. # Ensure that we warn users if they provide a non-zero length tuple as
  1170. # the assertion test.
  1171. self.check_syntax_warning('assert(x, "msg")',
  1172. 'assertion is always true')
  1173. self.check_syntax_warning('assert(False, "msg")',
  1174. 'assertion is always true')
  1175. self.check_syntax_warning('assert(False,)',
  1176. 'assertion is always true')
  1177. with self.check_no_warnings(category=SyntaxWarning):
  1178. compile('assert x, "msg"', '<testcase>', 'exec')
  1179. compile('assert False, "msg"', '<testcase>', 'exec')
  1180. def test_assert_warning_promotes_to_syntax_error(self):
  1181. # If SyntaxWarning is configured to be an error, it actually raises a
  1182. # SyntaxError.
  1183. # https://bugs.python.org/issue35029
  1184. with warnings.catch_warnings():
  1185. warnings.simplefilter('error', SyntaxWarning)
  1186. try:
  1187. compile('assert x, "msg" ', '<testcase>', 'exec')
  1188. except SyntaxError:
  1189. self.fail('SyntaxError incorrectly raised for \'assert x, "msg"\'')
  1190. with self.assertRaises(SyntaxError):
  1191. compile('assert(x, "msg")', '<testcase>', 'exec')
  1192. with self.assertRaises(SyntaxError):
  1193. compile('assert(False, "msg")', '<testcase>', 'exec')
  1194. with self.assertRaises(SyntaxError):
  1195. compile('assert(False,)', '<testcase>', 'exec')
  1196. ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
  1197. # Tested below
  1198. def test_if(self):
  1199. # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
  1200. if 1: pass
  1201. if 1: pass
  1202. else: pass
  1203. if 0: pass
  1204. elif 0: pass
  1205. if 0: pass
  1206. elif 0: pass
  1207. elif 0: pass
  1208. elif 0: pass
  1209. else: pass
  1210. def test_while(self):
  1211. # 'while' test ':' suite ['else' ':' suite]
  1212. while 0: pass
  1213. while 0: pass
  1214. else: pass
  1215. # Issue1920: "while 0" is optimized away,
  1216. # ensure that the "else" clause is still present.
  1217. x = 0
  1218. while 0:
  1219. x = 1
  1220. else:
  1221. x = 2
  1222. self.assertEqual(x, 2)
  1223. def test_for(self):
  1224. # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
  1225. for i in 1, 2, 3: pass
  1226. for i, j, k in (): pass
  1227. else: pass
  1228. class Squares:
  1229. def __init__(self, max):
  1230. self.max = max
  1231. self.sofar = []
  1232. def __len__(self): return len(self.sofar)
  1233. def __getitem__(self, i):
  1234. if not 0 <= i < self.max: raise IndexError
  1235. n = len(self.sofar)
  1236. while n <= i:
  1237. self.sofar.append(n*n)
  1238. n = n+1
  1239. return self.sofar[i]
  1240. n = 0
  1241. for x in Squares(10): n = n+x
  1242. if n != 285:
  1243. self.fail('for over growing sequence')
  1244. result = []
  1245. for x, in [(1,), (2,), (3,)]:
  1246. result.append(x)
  1247. self.assertEqual(result, [1, 2, 3])
  1248. result = []
  1249. a = b = c = [1, 2, 3]
  1250. for x in *a, *b, *c:
  1251. result.append(x)
  1252. self.assertEqual(result, 3 * a)
  1253. def test_try(self):
  1254. ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
  1255. ### | 'try' ':' suite 'finally' ':' suite
  1256. ### except_clause: 'except' [expr ['as' NAME]]
  1257. try:
  1258. 1/0
  1259. except ZeroDivisionError:
  1260. pass
  1261. else:
  1262. pass
  1263. try: 1/0
  1264. except EOFError: pass
  1265. except TypeError as msg: pass
  1266. except: pass
  1267. else: pass
  1268. try: 1/0
  1269. except (EOFError, TypeError, ZeroDivisionError): pass
  1270. try: 1/0
  1271. except (EOFError, TypeError, ZeroDivisionError) as msg: pass
  1272. try: pass
  1273. finally: pass
  1274. with self.assertRaises(SyntaxError):
  1275. compile("try:\n pass\nexcept Exception as a.b:\n pass", "?", "exec")
  1276. compile("try:\n pass\nexcept Exception as a[b]:\n pass", "?", "exec")
  1277. def test_try_star(self):
  1278. ### try_stmt: 'try': suite (except_star_clause : suite) + ['else' ':' suite]
  1279. ### except_star_clause: 'except*' expr ['as' NAME]
  1280. try:
  1281. 1/0
  1282. except* ZeroDivisionError:
  1283. pass
  1284. else:
  1285. pass
  1286. try: 1/0
  1287. except* EOFError: pass
  1288. except* ZeroDivisionError as msg: pass
  1289. else: pass
  1290. try: 1/0
  1291. except* (EOFError, TypeError, ZeroDivisionError): pass
  1292. try: 1/0
  1293. except* (EOFError, TypeError, ZeroDivisionError) as msg: pass
  1294. try: pass
  1295. finally: pass
  1296. with self.assertRaises(SyntaxError):
  1297. compile("try:\n pass\nexcept* Exception as a.b:\n pass", "?", "exec")
  1298. compile("try:\n pass\nexcept* Exception as a[b]:\n pass", "?", "exec")
  1299. compile("try:\n pass\nexcept*:\n pass", "?", "exec")
  1300. def test_suite(self):
  1301. # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
  1302. if 1: pass
  1303. if 1:
  1304. pass
  1305. if 1:
  1306. #
  1307. #
  1308. #
  1309. pass
  1310. pass
  1311. #
  1312. pass
  1313. #
  1314. def test_test(self):
  1315. ### and_test ('or' and_test)*
  1316. ### and_test: not_test ('and' not_test)*
  1317. ### not_test: 'not' not_test | comparison
  1318. if not 1: pass
  1319. if 1 and 1: pass
  1320. if 1 or 1: pass
  1321. if not not not 1: pass
  1322. if not 1 and 1 and 1: pass
  1323. if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
  1324. def test_comparison(self):
  1325. ### comparison: expr (comp_op expr)*
  1326. ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
  1327. if 1: pass
  1328. x = (1 == 1)
  1329. if 1 == 1: pass
  1330. if 1 != 1: pass
  1331. if 1 < 1: pass
  1332. if 1 > 1: pass
  1333. if 1 <= 1: pass
  1334. if 1 >= 1: pass
  1335. if x is x: pass
  1336. if x is not x: pass
  1337. if 1 in (): pass
  1338. if 1 not in (): pass
  1339. if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in x is x is not x: pass
  1340. def test_comparison_is_literal(self):
  1341. def check(test, msg='"is" with a literal'):
  1342. self.check_syntax_warning(test, msg)
  1343. check('x is 1')
  1344. check('x is "thing"')
  1345. check('1 is x')
  1346. check('x is y is 1')
  1347. check('x is not 1', '"is not" with a literal')
  1348. with warnings.catch_warnings():
  1349. warnings.simplefilter('error', SyntaxWarning)
  1350. compile('x is None', '<testcase>', 'exec')
  1351. compile('x is False', '<testcase>', 'exec')
  1352. compile('x is True', '<testcase>', 'exec')
  1353. compile('x is ...', '<testcase>', 'exec')
  1354. def test_warn_missed_comma(self):
  1355. def check(test):
  1356. self.check_syntax_warning(test, msg)
  1357. msg=r'is not callable; perhaps you missed a comma\?'
  1358. check('[(1, 2) (3, 4)]')
  1359. check('[(x, y) (3, 4)]')
  1360. check('[[1, 2] (3, 4)]')
  1361. check('[{1, 2} (3, 4)]')
  1362. check('[{1: 2} (3, 4)]')
  1363. check('[[i for i in range(5)] (3, 4)]')
  1364. check('[{i for i in range(5)} (3, 4)]')
  1365. check('[(i for i in range(5)) (3, 4)]')
  1366. check('[{i: i for i in range(5)} (3, 4)]')
  1367. check('[f"{x}" (3, 4)]')
  1368. check('[f"x={x}" (3, 4)]')
  1369. check('["abc" (3, 4)]')
  1370. check('[b"abc" (3, 4)]')
  1371. check('[123 (3, 4)]')
  1372. check('[12.3 (3, 4)]')
  1373. check('[12.3j (3, 4)]')
  1374. check('[None (3, 4)]')
  1375. check('[True (3, 4)]')
  1376. check('[... (3, 4)]')
  1377. msg=r'is not subscriptable; perhaps you missed a comma\?'
  1378. check('[{1, 2} [i, j]]')
  1379. check('[{i for i in range(5)} [i, j]]')
  1380. check('[(i for i in range(5)) [i, j]]')
  1381. check('[(lambda x, y: x) [i, j]]')
  1382. check('[123 [i, j]]')
  1383. check('[12.3 [i, j]]')
  1384. check('[12.3j [i, j]]')
  1385. check('[None [i, j]]')
  1386. check('[True [i, j]]')
  1387. check('[... [i, j]]')
  1388. msg=r'indices must be integers or slices, not tuple; perhaps you missed a comma\?'
  1389. check('[(1, 2) [i, j]]')
  1390. check('[(x, y) [i, j]]')
  1391. check('[[1, 2] [i, j]]')
  1392. check('[[i for i in range(5)] [i, j]]')
  1393. check('[f"{x}" [i, j]]')
  1394. check('[f"x={x}" [i, j]]')
  1395. check('["abc" [i, j]]')
  1396. check('[b"abc" [i, j]]')
  1397. msg=r'indices must be integers or slices, not tuple;'
  1398. check('[[1, 2] [3, 4]]')
  1399. msg=r'indices must be integers or slices, not list;'
  1400. check('[[1, 2] [[3, 4]]]')
  1401. check('[[1, 2] [[i for i in range(5)]]]')
  1402. msg=r'indices must be integers or slices, not set;'
  1403. check('[[1, 2] [{3, 4}]]')
  1404. check('[[1, 2] [{i for i in range(5)}]]')
  1405. msg=r'indices must be integers or slices, not dict;'
  1406. check('[[1, 2] [{3: 4}]]')
  1407. check('[[1, 2] [{i: i for i in range(5)}]]')
  1408. msg=r'indices must be integers or slices, not generator;'
  1409. check('[[1, 2] [(i for i in range(5))]]')
  1410. msg=r'indices must be integers or slices, not function;'
  1411. check('[[1, 2] [(lambda x, y: x)]]')
  1412. msg=r'indices must be integers or slices, not str;'
  1413. check('[[1, 2] [f"{x}"]]')
  1414. check('[[1, 2] [f"x={x}"]]')
  1415. check('[[1, 2] ["abc"]]')
  1416. msg=r'indices must be integers or slices, not'
  1417. check('[[1, 2] [b"abc"]]')
  1418. check('[[1, 2] [12.3]]')
  1419. check('[[1, 2] [12.3j]]')
  1420. check('[[1, 2] [None]]')
  1421. check('[[1, 2] [...]]')
  1422. with warnings.catch_warnings():
  1423. warnings.simplefilter('error', SyntaxWarning)
  1424. compile('[(lambda x, y: x) (3, 4)]', '<testcase>', 'exec')
  1425. compile('[[1, 2] [i]]', '<testcase>', 'exec')
  1426. compile('[[1, 2] [0]]', '<testcase>', 'exec')
  1427. compile('[[1, 2] [True]]', '<testcase>', 'exec')
  1428. compile('[[1, 2] [1:2]]', '<testcase>', 'exec')
  1429. compile('[{(1, 2): 3} [i, j]]', '<testcase>', 'exec')
  1430. def test_binary_mask_ops(self):
  1431. x = 1 & 1
  1432. x = 1 ^ 1
  1433. x = 1 | 1
  1434. def test_shift_ops(self):
  1435. x = 1 << 1
  1436. x = 1 >> 1
  1437. x = 1 << 1 >> 1
  1438. def test_additive_ops(self):
  1439. x = 1
  1440. x = 1 + 1
  1441. x = 1 - 1 - 1
  1442. x = 1 - 1 + 1 - 1 + 1
  1443. def test_multiplicative_ops(self):
  1444. x = 1 * 1
  1445. x = 1 / 1
  1446. x = 1 % 1
  1447. x = 1 / 1 * 1 % 1
  1448. def test_unary_ops(self):
  1449. x = +1
  1450. x = -1
  1451. x = ~1
  1452. x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
  1453. x = -1*1/1 + 1*1 - ---1*1
  1454. def test_selectors(self):
  1455. ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
  1456. ### subscript: expr | [expr] ':' [expr]
  1457. import sys, time
  1458. c = sys.path[0]
  1459. x = time.time()
  1460. x = sys.modules['time'].time()
  1461. a = '01234'
  1462. c = a[0]
  1463. c = a[-1]
  1464. s = a[0:5]
  1465. s = a[:5]
  1466. s = a[0:]
  1467. s = a[:]
  1468. s = a[-5:]
  1469. s = a[:-1]
  1470. s = a[-4:-3]
  1471. # A rough test of SF bug 1333982. http://python.org/sf/1333982
  1472. # The testing here is fairly incomplete.
  1473. # Test cases should include: commas with 1 and 2 colons
  1474. d = {}
  1475. d[1] = 1
  1476. d[1,] = 2
  1477. d[1,2] = 3
  1478. d[1,2,3] = 4
  1479. L = list(d)
  1480. L.sort(key=lambda x: (type(x).__name__, x))
  1481. self.assertEqual(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
  1482. def test_atoms(self):
  1483. ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
  1484. ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
  1485. x = (1)
  1486. x = (1 or 2 or 3)
  1487. x = (1 or 2 or 3, 2, 3)
  1488. x = []
  1489. x = [1]
  1490. x = [1 or 2 or 3]
  1491. x = [1 or 2 or 3, 2, 3]
  1492. x = []
  1493. x = {}
  1494. x = {'one': 1}
  1495. x = {'one': 1,}
  1496. x = {'one' or 'two': 1 or 2}
  1497. x = {'one': 1, 'two': 2}
  1498. x = {'one': 1, 'two': 2,}
  1499. x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
  1500. x = {'one'}
  1501. x = {'one', 1,}
  1502. x = {'one', 'two', 'three'}
  1503. x = {2, 3, 4,}
  1504. x = x
  1505. x = 'x'
  1506. x = 123
  1507. ### exprlist: expr (',' expr)* [',']
  1508. ### testlist: test (',' test)* [',']
  1509. # These have been exercised enough above
  1510. def test_classdef(self):
  1511. # 'class' NAME ['(' [testlist] ')'] ':' suite
  1512. class B: pass
  1513. class B2(): pass
  1514. class C1(B): pass
  1515. class C2(B): pass
  1516. class D(C1, C2, B): pass
  1517. class C:
  1518. def meth1(self): pass
  1519. def meth2(self, arg): pass
  1520. def meth3(self, a1, a2): pass
  1521. # decorator: '@' namedexpr_test NEWLINE
  1522. # decorators: decorator+
  1523. # decorated: decorators (classdef | funcdef)
  1524. def class_decorator(x): return x
  1525. @class_decorator
  1526. class G: pass
  1527. # Test expressions as decorators (PEP 614):
  1528. @False or class_decorator
  1529. class H: pass
  1530. @d := class_decorator
  1531. class I: pass
  1532. @lambda c: class_decorator(c)
  1533. class J: pass
  1534. @[..., class_decorator, ...][1]
  1535. class K: pass
  1536. @class_decorator(class_decorator)(class_decorator)
  1537. class L: pass
  1538. @[class_decorator][0].__call__.__call__
  1539. class M: pass
  1540. def test_dictcomps(self):
  1541. # dictorsetmaker: ( (test ':' test (comp_for |
  1542. # (',' test ':' test)* [','])) |
  1543. # (test (comp_for | (',' test)* [','])) )
  1544. nums = [1, 2, 3]
  1545. self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4})
  1546. def test_listcomps(self):
  1547. # list comprehension tests
  1548. nums = [1, 2, 3, 4, 5]
  1549. strs = ["Apple", "Banana", "Coconut"]
  1550. spcs = [" Apple", " Banana ", "Coco nut "]
  1551. self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
  1552. self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
  1553. self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
  1554. self.assertEqual([(i, s) for i in nums for s in strs],
  1555. [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
  1556. (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
  1557. (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
  1558. (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
  1559. (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
  1560. self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
  1561. [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
  1562. (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
  1563. (5, 'Banana'), (5, 'Coconut')])
  1564. self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
  1565. [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
  1566. def test_in_func(l):
  1567. return [0 < x < 3 for x in l if x > 2]
  1568. self.assertEqual(test_in_func(nums), [False, False, False])
  1569. def test_nested_front():
  1570. self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
  1571. [[1, 2], [3, 4], [5, 6]])
  1572. test_nested_front()
  1573. check_syntax_error(self, "[i, s for i in nums for s in strs]")
  1574. check_syntax_error(self, "[x if y]")
  1575. suppliers = [
  1576. (1, "Boeing"),
  1577. (2, "Ford"),
  1578. (3, "Macdonalds")
  1579. ]
  1580. parts = [
  1581. (10, "Airliner"),
  1582. (20, "Engine"),
  1583. (30, "Cheeseburger")
  1584. ]
  1585. suppart = [
  1586. (1, 10), (1, 20), (2, 20), (3, 30)
  1587. ]
  1588. x = [
  1589. (sname, pname)
  1590. for (sno, sname) in suppliers
  1591. for (pno, pname) in parts
  1592. for (sp_sno, sp_pno) in suppart
  1593. if sno == sp_sno and pno == sp_pno
  1594. ]
  1595. self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
  1596. ('Macdonalds', 'Cheeseburger')])
  1597. def test_genexps(self):
  1598. # generator expression tests
  1599. g = ([x for x in range(10)] for x in range(1))
  1600. self.assertEqual(next(g), [x for x in range(10)])
  1601. try:
  1602. next(g)
  1603. self.fail('should produce StopIteration exception')
  1604. except StopIteration:
  1605. pass
  1606. a = 1
  1607. try:
  1608. g = (a for d in a)
  1609. next(g)
  1610. self.fail('should produce TypeError')
  1611. except TypeError:
  1612. pass
  1613. self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
  1614. self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
  1615. a = [x for x in range(10)]
  1616. b = (x for x in (y for y in a))
  1617. self.assertEqual(sum(b), sum([x for x in range(10)]))
  1618. self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
  1619. self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
  1620. self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
  1621. self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
  1622. self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
  1623. self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True)) if True), sum([x for x in range(10)]))
  1624. self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
  1625. check_syntax_error(self, "foo(x for x in range(10), 100)")
  1626. check_syntax_error(self, "foo(100, x for x in range(10))")
  1627. def test_comprehension_specials(self):
  1628. # test for outmost iterable precomputation
  1629. x = 10; g = (i for i in range(x)); x = 5
  1630. self.assertEqual(len(list(g)), 10)
  1631. # This should hold, since we're only precomputing outmost iterable.
  1632. x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
  1633. x = 5; t = True;
  1634. self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
  1635. # Grammar allows multiple adjacent 'if's in listcomps and genexps,
  1636. # even though it's silly. Make sure it works (ifelse broke this.)
  1637. self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
  1638. self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
  1639. # verify unpacking single element tuples in listcomp/genexp.
  1640. self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
  1641. self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
  1642. def test_with_statement(self):
  1643. class manager(object):
  1644. def __enter__(self):
  1645. return (1, 2)
  1646. def __exit__(self, *args):
  1647. pass
  1648. with manager():
  1649. pass
  1650. with manager() as x:
  1651. pass
  1652. with manager() as (x, y):
  1653. pass
  1654. with manager(), manager():
  1655. pass
  1656. with manager() as x, manager() as y:
  1657. pass
  1658. with manager() as x, manager():
  1659. pass
  1660. with (
  1661. manager()
  1662. ):
  1663. pass
  1664. with (
  1665. manager() as x
  1666. ):
  1667. pass
  1668. with (
  1669. manager() as (x, y),
  1670. manager() as z,
  1671. ):
  1672. pass
  1673. with (
  1674. manager(),
  1675. manager()
  1676. ):
  1677. pass
  1678. with (
  1679. manager() as x,
  1680. manager() as y
  1681. ):
  1682. pass
  1683. with (
  1684. manager() as x,
  1685. manager()
  1686. ):
  1687. pass
  1688. with (
  1689. manager() as x,
  1690. manager() as y,
  1691. manager() as z,
  1692. ):
  1693. pass
  1694. with (
  1695. manager() as x,
  1696. manager() as y,
  1697. manager(),
  1698. ):
  1699. pass
  1700. def test_if_else_expr(self):
  1701. # Test ifelse expressions in various cases
  1702. def _checkeval(msg, ret):
  1703. "helper to check that evaluation of expressions is done correctly"
  1704. print(msg)
  1705. return ret
  1706. # the next line is not allowed anymore
  1707. #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
  1708. self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
  1709. self.assertEqual([ x(False) for x in (lambda x: False if x else True, lambda x: True if x else False) if x(False) ], [True])
  1710. self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
  1711. self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
  1712. self.assertEqual((5 and 6 if 0 else 1), 1)
  1713. self.assertEqual(((5 and 6) if 0 else 1), 1)
  1714. self.assertEqual((5 and (6 if 1 else 1)), 6)
  1715. self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
  1716. self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
  1717. self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
  1718. self.assertEqual((not 5 if 1 else 1), False)
  1719. self.assertEqual((not 5 if 0 else 1), 1)
  1720. self.assertEqual((6 + 1 if 1 else 2), 7)
  1721. self.assertEqual((6 - 1 if 1 else 2), 5)
  1722. self.assertEqual((6 * 2 if 1 else 4), 12)
  1723. self.assertEqual((6 / 2 if 1 else 3), 3)
  1724. self.assertEqual((6 < 4 if 0 else 2), 2)
  1725. def test_paren_evaluation(self):
  1726. self.assertEqual(16 // (4 // 2), 8)
  1727. self.assertEqual((16 // 4) // 2, 2)
  1728. self.assertEqual(16 // 4 // 2, 2)
  1729. x = 2
  1730. y = 3
  1731. self.assertTrue(False is (x is y))
  1732. self.assertFalse((False is x) is y)
  1733. self.assertFalse(False is x is y)
  1734. def test_matrix_mul(self):
  1735. # This is not intended to be a comprehensive test, rather just to be few
  1736. # samples of the @ operator in test_grammar.py.
  1737. class M:
  1738. def __matmul__(self, o):
  1739. return 4
  1740. def __imatmul__(self, o):
  1741. self.other = o
  1742. return self
  1743. m = M()
  1744. self.assertEqual(m @ m, 4)
  1745. m @= 42
  1746. self.assertEqual(m.other, 42)
  1747. def test_async_await(self):
  1748. async def test():
  1749. def sum():
  1750. pass
  1751. if 1:
  1752. await someobj()
  1753. self.assertEqual(test.__name__, 'test')
  1754. self.assertTrue(bool(test.__code__.co_flags & inspect.CO_COROUTINE))
  1755. def decorator(func):
  1756. setattr(func, '_marked', True)
  1757. return func
  1758. @decorator
  1759. async def test2():
  1760. return 22
  1761. self.assertTrue(test2._marked)
  1762. self.assertEqual(test2.__name__, 'test2')
  1763. self.assertTrue(bool(test2.__code__.co_flags & inspect.CO_COROUTINE))
  1764. def test_async_for(self):
  1765. class Done(Exception): pass
  1766. class AIter:
  1767. def __aiter__(self):
  1768. return self
  1769. async def __anext__(self):
  1770. raise StopAsyncIteration
  1771. async def foo():
  1772. async for i in AIter():
  1773. pass
  1774. async for i, j in AIter():
  1775. pass
  1776. async for i in AIter():
  1777. pass
  1778. else:
  1779. pass
  1780. raise Done
  1781. with self.assertRaises(Done):
  1782. foo().send(None)
  1783. def test_async_with(self):
  1784. class Done(Exception): pass
  1785. class manager:
  1786. async def __aenter__(self):
  1787. return (1, 2)
  1788. async def __aexit__(self, *exc):
  1789. return False
  1790. async def foo():
  1791. async with manager():
  1792. pass
  1793. async with manager() as x:
  1794. pass
  1795. async with manager() as (x, y):
  1796. pass
  1797. async with manager(), manager():
  1798. pass
  1799. async with manager() as x, manager() as y:
  1800. pass
  1801. async with manager() as x, manager():
  1802. pass
  1803. raise Done
  1804. with self.assertRaises(Done):
  1805. foo().send(None)
  1806. if __name__ == '__main__':
  1807. unittest.main()