python3.8_grammar.py 49 KB

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