test_parser.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. """Test suite for 2to3's parser and grammar files.
  2. This is the place to add tests for changes to 2to3's grammar, such as those
  3. merging the grammars for Python 2 and 3. In addition to specific tests for
  4. parts of the grammar we've changed, we also make sure we can parse the
  5. test_grammar.py files from both Python 2 and Python 3.
  6. """
  7. # Testing imports
  8. from . import support
  9. from .support import driver, driver_no_print_statement
  10. # Python imports
  11. import difflib
  12. import importlib
  13. import operator
  14. import os
  15. import pickle
  16. import shutil
  17. import subprocess
  18. import sys
  19. import tempfile
  20. import test.support
  21. import unittest
  22. # Local imports
  23. from lib2to3.pgen2 import driver as pgen2_driver
  24. from lib2to3.pgen2 import tokenize
  25. from ..pgen2.parse import ParseError
  26. from lib2to3.pygram import python_symbols as syms
  27. class TestDriver(support.TestCase):
  28. def test_formfeed(self):
  29. s = """print 1\n\x0Cprint 2\n"""
  30. t = driver.parse_string(s)
  31. self.assertEqual(t.children[0].children[0].type, syms.print_stmt)
  32. self.assertEqual(t.children[1].children[0].type, syms.print_stmt)
  33. class TestPgen2Caching(support.TestCase):
  34. def test_load_grammar_from_txt_file(self):
  35. pgen2_driver.load_grammar(support.grammar_path, save=False, force=True)
  36. def test_load_grammar_from_pickle(self):
  37. # Make a copy of the grammar file in a temp directory we are
  38. # guaranteed to be able to write to.
  39. tmpdir = tempfile.mkdtemp()
  40. try:
  41. grammar_copy = os.path.join(
  42. tmpdir, os.path.basename(support.grammar_path))
  43. shutil.copy(support.grammar_path, grammar_copy)
  44. pickle_name = pgen2_driver._generate_pickle_name(grammar_copy)
  45. pgen2_driver.load_grammar(grammar_copy, save=True, force=True)
  46. self.assertTrue(os.path.exists(pickle_name))
  47. os.unlink(grammar_copy) # Only the pickle remains...
  48. pgen2_driver.load_grammar(grammar_copy, save=False, force=False)
  49. finally:
  50. shutil.rmtree(tmpdir)
  51. @unittest.skipIf(sys.executable is None, 'sys.executable required')
  52. def test_load_grammar_from_subprocess(self):
  53. tmpdir = tempfile.mkdtemp()
  54. tmpsubdir = os.path.join(tmpdir, 'subdir')
  55. try:
  56. os.mkdir(tmpsubdir)
  57. grammar_base = os.path.basename(support.grammar_path)
  58. grammar_copy = os.path.join(tmpdir, grammar_base)
  59. grammar_sub_copy = os.path.join(tmpsubdir, grammar_base)
  60. shutil.copy(support.grammar_path, grammar_copy)
  61. shutil.copy(support.grammar_path, grammar_sub_copy)
  62. pickle_name = pgen2_driver._generate_pickle_name(grammar_copy)
  63. pickle_sub_name = pgen2_driver._generate_pickle_name(
  64. grammar_sub_copy)
  65. self.assertNotEqual(pickle_name, pickle_sub_name)
  66. # Generate a pickle file from this process.
  67. pgen2_driver.load_grammar(grammar_copy, save=True, force=True)
  68. self.assertTrue(os.path.exists(pickle_name))
  69. # Generate a new pickle file in a subprocess with a most likely
  70. # different hash randomization seed.
  71. sub_env = dict(os.environ)
  72. sub_env['PYTHONHASHSEED'] = 'random'
  73. subprocess.check_call(
  74. [sys.executable, '-c', """
  75. from lib2to3.pgen2 import driver as pgen2_driver
  76. pgen2_driver.load_grammar(%r, save=True, force=True)
  77. """ % (grammar_sub_copy,)],
  78. env=sub_env)
  79. self.assertTrue(os.path.exists(pickle_sub_name))
  80. with open(pickle_name, 'rb') as pickle_f_1, \
  81. open(pickle_sub_name, 'rb') as pickle_f_2:
  82. self.assertEqual(
  83. pickle_f_1.read(), pickle_f_2.read(),
  84. msg='Grammar caches generated using different hash seeds'
  85. ' were not identical.')
  86. finally:
  87. shutil.rmtree(tmpdir)
  88. def test_load_packaged_grammar(self):
  89. modname = __name__ + '.load_test'
  90. class MyLoader:
  91. def get_data(self, where):
  92. return pickle.dumps({'elephant': 19})
  93. class MyModule:
  94. __file__ = 'parsertestmodule'
  95. __spec__ = importlib.util.spec_from_loader(modname, MyLoader())
  96. sys.modules[modname] = MyModule()
  97. self.addCleanup(operator.delitem, sys.modules, modname)
  98. g = pgen2_driver.load_packaged_grammar(modname, 'Grammar.txt')
  99. self.assertEqual(g.elephant, 19)
  100. class GrammarTest(support.TestCase):
  101. def validate(self, code):
  102. support.parse_string(code)
  103. def invalid_syntax(self, code):
  104. try:
  105. self.validate(code)
  106. except ParseError:
  107. pass
  108. else:
  109. raise AssertionError("Syntax shouldn't have been valid")
  110. class TestMatrixMultiplication(GrammarTest):
  111. def test_matrix_multiplication_operator(self):
  112. self.validate("a @ b")
  113. self.validate("a @= b")
  114. class TestYieldFrom(GrammarTest):
  115. def test_yield_from(self):
  116. self.validate("yield from x")
  117. self.validate("(yield from x) + y")
  118. self.invalid_syntax("yield from")
  119. class TestAsyncAwait(GrammarTest):
  120. def test_await_expr(self):
  121. self.validate("""async def foo():
  122. await x
  123. """)
  124. self.validate("""async def foo():
  125. [i async for i in b]
  126. """)
  127. self.validate("""async def foo():
  128. {i for i in b
  129. async for i in a if await i
  130. for b in i}
  131. """)
  132. self.validate("""async def foo():
  133. [await i for i in b if await c]
  134. """)
  135. self.validate("""async def foo():
  136. [ i for i in b if c]
  137. """)
  138. self.validate("""async def foo():
  139. def foo(): pass
  140. def foo(): pass
  141. await x
  142. """)
  143. self.validate("""async def foo(): return await a""")
  144. self.validate("""def foo():
  145. def foo(): pass
  146. async def foo(): await x
  147. """)
  148. self.invalid_syntax("await x")
  149. self.invalid_syntax("""def foo():
  150. await x""")
  151. self.invalid_syntax("""def foo():
  152. def foo(): pass
  153. async def foo(): pass
  154. await x
  155. """)
  156. def test_async_var(self):
  157. self.validate("""async = 1""")
  158. self.validate("""await = 1""")
  159. self.validate("""def async(): pass""")
  160. def test_async_for(self):
  161. self.validate("""async def foo():
  162. async for a in b: pass""")
  163. def test_async_with(self):
  164. self.validate("""async def foo():
  165. async with a: pass""")
  166. self.invalid_syntax("""def foo():
  167. async with a: pass""")
  168. def test_async_generator(self):
  169. self.validate(
  170. """async def foo():
  171. return (i * 2 async for i in arange(42))"""
  172. )
  173. self.validate(
  174. """def foo():
  175. return (i * 2 async for i in arange(42))"""
  176. )
  177. class TestRaiseChanges(GrammarTest):
  178. def test_2x_style_1(self):
  179. self.validate("raise")
  180. def test_2x_style_2(self):
  181. self.validate("raise E, V")
  182. def test_2x_style_3(self):
  183. self.validate("raise E, V, T")
  184. def test_2x_style_invalid_1(self):
  185. self.invalid_syntax("raise E, V, T, Z")
  186. def test_3x_style(self):
  187. self.validate("raise E1 from E2")
  188. def test_3x_style_invalid_1(self):
  189. self.invalid_syntax("raise E, V from E1")
  190. def test_3x_style_invalid_2(self):
  191. self.invalid_syntax("raise E from E1, E2")
  192. def test_3x_style_invalid_3(self):
  193. self.invalid_syntax("raise from E1, E2")
  194. def test_3x_style_invalid_4(self):
  195. self.invalid_syntax("raise E from")
  196. # Modelled after Lib/test/test_grammar.py:TokenTests.test_funcdef issue2292
  197. # and Lib/test/text_parser.py test_list_displays, test_set_displays,
  198. # test_dict_displays, test_argument_unpacking, ... changes.
  199. class TestUnpackingGeneralizations(GrammarTest):
  200. def test_mid_positional_star(self):
  201. self.validate("""func(1, *(2, 3), 4)""")
  202. def test_double_star_dict_literal(self):
  203. self.validate("""func(**{'eggs':'scrambled', 'spam':'fried'})""")
  204. def test_double_star_dict_literal_after_keywords(self):
  205. self.validate("""func(spam='fried', **{'eggs':'scrambled'})""")
  206. def test_double_star_expression(self):
  207. self.validate("""func(**{'a':2} or {})""")
  208. self.validate("""func(**() or {})""")
  209. def test_star_expression(self):
  210. self.validate("""func(*[] or [2])""")
  211. def test_list_display(self):
  212. self.validate("""[*{2}, 3, *[4]]""")
  213. def test_set_display(self):
  214. self.validate("""{*{2}, 3, *[4]}""")
  215. def test_dict_display_1(self):
  216. self.validate("""{**{}}""")
  217. def test_dict_display_2(self):
  218. self.validate("""{**{}, 3:4, **{5:6, 7:8}}""")
  219. def test_complex_star_expression(self):
  220. self.validate("func(* [] or [1])")
  221. def test_complex_double_star_expression(self):
  222. self.validate("func(**{1: 3} if False else {x: x for x in range(3)})")
  223. def test_argument_unpacking_1(self):
  224. self.validate("""f(a, *b, *c, d)""")
  225. def test_argument_unpacking_2(self):
  226. self.validate("""f(**a, **b)""")
  227. def test_argument_unpacking_3(self):
  228. self.validate("""f(2, *a, *b, **b, **c, **d)""")
  229. def test_trailing_commas_1(self):
  230. self.validate("def f(a, b): call(a, b)")
  231. self.validate("def f(a, b,): call(a, b,)")
  232. def test_trailing_commas_2(self):
  233. self.validate("def f(a, *b): call(a, *b)")
  234. self.validate("def f(a, *b,): call(a, *b,)")
  235. def test_trailing_commas_3(self):
  236. self.validate("def f(a, b=1): call(a, b=1)")
  237. self.validate("def f(a, b=1,): call(a, b=1,)")
  238. def test_trailing_commas_4(self):
  239. self.validate("def f(a, **b): call(a, **b)")
  240. self.validate("def f(a, **b,): call(a, **b,)")
  241. def test_trailing_commas_5(self):
  242. self.validate("def f(*a, b=1): call(*a, b=1)")
  243. self.validate("def f(*a, b=1,): call(*a, b=1,)")
  244. def test_trailing_commas_6(self):
  245. self.validate("def f(*a, **b): call(*a, **b)")
  246. self.validate("def f(*a, **b,): call(*a, **b,)")
  247. def test_trailing_commas_7(self):
  248. self.validate("def f(*, b=1): call(*b)")
  249. self.validate("def f(*, b=1,): call(*b,)")
  250. def test_trailing_commas_8(self):
  251. self.validate("def f(a=1, b=2): call(a=1, b=2)")
  252. self.validate("def f(a=1, b=2,): call(a=1, b=2,)")
  253. def test_trailing_commas_9(self):
  254. self.validate("def f(a=1, **b): call(a=1, **b)")
  255. self.validate("def f(a=1, **b,): call(a=1, **b,)")
  256. def test_trailing_commas_lambda_1(self):
  257. self.validate("f = lambda a, b: call(a, b)")
  258. self.validate("f = lambda a, b,: call(a, b,)")
  259. def test_trailing_commas_lambda_2(self):
  260. self.validate("f = lambda a, *b: call(a, *b)")
  261. self.validate("f = lambda a, *b,: call(a, *b,)")
  262. def test_trailing_commas_lambda_3(self):
  263. self.validate("f = lambda a, b=1: call(a, b=1)")
  264. self.validate("f = lambda a, b=1,: call(a, b=1,)")
  265. def test_trailing_commas_lambda_4(self):
  266. self.validate("f = lambda a, **b: call(a, **b)")
  267. self.validate("f = lambda a, **b,: call(a, **b,)")
  268. def test_trailing_commas_lambda_5(self):
  269. self.validate("f = lambda *a, b=1: call(*a, b=1)")
  270. self.validate("f = lambda *a, b=1,: call(*a, b=1,)")
  271. def test_trailing_commas_lambda_6(self):
  272. self.validate("f = lambda *a, **b: call(*a, **b)")
  273. self.validate("f = lambda *a, **b,: call(*a, **b,)")
  274. def test_trailing_commas_lambda_7(self):
  275. self.validate("f = lambda *, b=1: call(*b)")
  276. self.validate("f = lambda *, b=1,: call(*b,)")
  277. def test_trailing_commas_lambda_8(self):
  278. self.validate("f = lambda a=1, b=2: call(a=1, b=2)")
  279. self.validate("f = lambda a=1, b=2,: call(a=1, b=2,)")
  280. def test_trailing_commas_lambda_9(self):
  281. self.validate("f = lambda a=1, **b: call(a=1, **b)")
  282. self.validate("f = lambda a=1, **b,: call(a=1, **b,)")
  283. # Adapted from Python 3's Lib/test/test_grammar.py:GrammarTests.testFuncdef
  284. class TestFunctionAnnotations(GrammarTest):
  285. def test_1(self):
  286. self.validate("""def f(x) -> list: pass""")
  287. def test_2(self):
  288. self.validate("""def f(x:int): pass""")
  289. def test_3(self):
  290. self.validate("""def f(*x:str): pass""")
  291. def test_4(self):
  292. self.validate("""def f(**x:float): pass""")
  293. def test_5(self):
  294. self.validate("""def f(x, y:1+2): pass""")
  295. def test_6(self):
  296. self.validate("""def f(a, (b:1, c:2, d)): pass""")
  297. def test_7(self):
  298. self.validate("""def f(a, (b:1, c:2, d), e:3=4, f=5, *g:6): pass""")
  299. def test_8(self):
  300. s = """def f(a, (b:1, c:2, d), e:3=4, f=5,
  301. *g:6, h:7, i=8, j:9=10, **k:11) -> 12: pass"""
  302. self.validate(s)
  303. def test_9(self):
  304. s = """def f(
  305. a: str,
  306. b: int,
  307. *,
  308. c: bool = False,
  309. **kwargs,
  310. ) -> None:
  311. call(c=c, **kwargs,)"""
  312. self.validate(s)
  313. def test_10(self):
  314. s = """def f(
  315. a: str,
  316. ) -> None:
  317. call(a,)"""
  318. self.validate(s)
  319. def test_11(self):
  320. s = """def f(
  321. a: str = '',
  322. ) -> None:
  323. call(a=a,)"""
  324. self.validate(s)
  325. def test_12(self):
  326. s = """def f(
  327. *args: str,
  328. ) -> None:
  329. call(*args,)"""
  330. self.validate(s)
  331. def test_13(self):
  332. self.validate("def f(a: str, b: int) -> None: call(a, b)")
  333. self.validate("def f(a: str, b: int,) -> None: call(a, b,)")
  334. def test_14(self):
  335. self.validate("def f(a: str, *b: int) -> None: call(a, *b)")
  336. self.validate("def f(a: str, *b: int,) -> None: call(a, *b,)")
  337. def test_15(self):
  338. self.validate("def f(a: str, b: int=1) -> None: call(a, b=1)")
  339. self.validate("def f(a: str, b: int=1,) -> None: call(a, b=1,)")
  340. def test_16(self):
  341. self.validate("def f(a: str, **b: int) -> None: call(a, **b)")
  342. self.validate("def f(a: str, **b: int,) -> None: call(a, **b,)")
  343. def test_17(self):
  344. self.validate("def f(*a: str, b: int=1) -> None: call(*a, b=1)")
  345. self.validate("def f(*a: str, b: int=1,) -> None: call(*a, b=1,)")
  346. def test_18(self):
  347. self.validate("def f(*a: str, **b: int) -> None: call(*a, **b)")
  348. self.validate("def f(*a: str, **b: int,) -> None: call(*a, **b,)")
  349. def test_19(self):
  350. self.validate("def f(*, b: int=1) -> None: call(*b)")
  351. self.validate("def f(*, b: int=1,) -> None: call(*b,)")
  352. def test_20(self):
  353. self.validate("def f(a: str='', b: int=2) -> None: call(a=a, b=2)")
  354. self.validate("def f(a: str='', b: int=2,) -> None: call(a=a, b=2,)")
  355. def test_21(self):
  356. self.validate("def f(a: str='', **b: int) -> None: call(a=a, **b)")
  357. self.validate("def f(a: str='', **b: int,) -> None: call(a=a, **b,)")
  358. # Adapted from Python 3's Lib/test/test_grammar.py:GrammarTests.test_var_annot
  359. class TestVarAnnotations(GrammarTest):
  360. def test_1(self):
  361. self.validate("var1: int = 5")
  362. def test_2(self):
  363. self.validate("var2: [int, str]")
  364. def test_3(self):
  365. self.validate("def f():\n"
  366. " st: str = 'Hello'\n"
  367. " a.b: int = (1, 2)\n"
  368. " return st\n")
  369. def test_4(self):
  370. self.validate("def fbad():\n"
  371. " x: int\n"
  372. " print(x)\n")
  373. def test_5(self):
  374. self.validate("class C:\n"
  375. " x: int\n"
  376. " s: str = 'attr'\n"
  377. " z = 2\n"
  378. " def __init__(self, x):\n"
  379. " self.x: int = x\n")
  380. def test_6(self):
  381. self.validate("lst: List[int] = []")
  382. class TestExcept(GrammarTest):
  383. def test_new(self):
  384. s = """
  385. try:
  386. x
  387. except E as N:
  388. y"""
  389. self.validate(s)
  390. def test_old(self):
  391. s = """
  392. try:
  393. x
  394. except E, N:
  395. y"""
  396. self.validate(s)
  397. class TestStringLiterals(GrammarTest):
  398. prefixes = ("'", '"',
  399. "r'", 'r"', "R'", 'R"',
  400. "u'", 'u"', "U'", 'U"',
  401. "b'", 'b"', "B'", 'B"',
  402. "f'", 'f"', "F'", 'F"',
  403. "ur'", 'ur"', "Ur'", 'Ur"',
  404. "uR'", 'uR"', "UR'", 'UR"',
  405. "br'", 'br"', "Br'", 'Br"',
  406. "bR'", 'bR"', "BR'", 'BR"',
  407. "rb'", 'rb"', "Rb'", 'Rb"',
  408. "rB'", 'rB"', "RB'", 'RB"',)
  409. def test_lit(self):
  410. for pre in self.prefixes:
  411. single = "{p}spamspamspam{s}".format(p=pre, s=pre[-1])
  412. self.validate(single)
  413. triple = "{p}{s}{s}eggs{s}{s}{s}".format(p=pre, s=pre[-1])
  414. self.validate(triple)
  415. # Adapted from Python 3's Lib/test/test_grammar.py:GrammarTests.testAtoms
  416. class TestSetLiteral(GrammarTest):
  417. def test_1(self):
  418. self.validate("""x = {'one'}""")
  419. def test_2(self):
  420. self.validate("""x = {'one', 1,}""")
  421. def test_3(self):
  422. self.validate("""x = {'one', 'two', 'three'}""")
  423. def test_4(self):
  424. self.validate("""x = {2, 3, 4,}""")
  425. # Adapted from Python 3's Lib/test/test_unicode_identifiers.py and
  426. # Lib/test/test_tokenize.py:TokenizeTest.test_non_ascii_identifiers
  427. class TestIdentifier(GrammarTest):
  428. def test_non_ascii_identifiers(self):
  429. self.validate("Örter = 'places'\ngrün = 'green'")
  430. self.validate("蟒 = a蟒 = 锦蛇 = 1")
  431. self.validate("µ = aµ = µµ = 1")
  432. self.validate("𝔘𝔫𝔦𝔠𝔬𝔡𝔢 = a_𝔘𝔫𝔦𝔠𝔬𝔡𝔢 = 1")
  433. class TestNumericLiterals(GrammarTest):
  434. def test_new_octal_notation(self):
  435. self.validate("""0o7777777777777""")
  436. self.invalid_syntax("""0o7324528887""")
  437. def test_new_binary_notation(self):
  438. self.validate("""0b101010""")
  439. self.invalid_syntax("""0b0101021""")
  440. class TestClassDef(GrammarTest):
  441. def test_new_syntax(self):
  442. self.validate("class B(t=7): pass")
  443. self.validate("class B(t, *args): pass")
  444. self.validate("class B(t, **kwargs): pass")
  445. self.validate("class B(t, *args, **kwargs): pass")
  446. self.validate("class B(t, y=9, *args, **kwargs,): pass")
  447. class TestParserIdempotency(support.TestCase):
  448. """A cut-down version of pytree_idempotency.py."""
  449. def parse_file(self, filepath):
  450. if test.support.verbose:
  451. print(f"Parse file: {filepath}")
  452. with open(filepath, "rb") as fp:
  453. encoding = tokenize.detect_encoding(fp.readline)[0]
  454. self.assertIsNotNone(encoding,
  455. "can't detect encoding for %s" % filepath)
  456. with open(filepath, "r", encoding=encoding) as fp:
  457. source = fp.read()
  458. try:
  459. tree = driver.parse_string(source)
  460. except ParseError:
  461. try:
  462. tree = driver_no_print_statement.parse_string(source)
  463. except ParseError as err:
  464. self.fail('ParseError on file %s (%s)' % (filepath, err))
  465. new = str(tree)
  466. if new != source:
  467. print(diff_texts(source, new, filepath))
  468. self.fail("Idempotency failed: %s" % filepath)
  469. def test_all_project_files(self):
  470. for filepath in support.all_project_files():
  471. with self.subTest(filepath=filepath):
  472. self.parse_file(filepath)
  473. def test_extended_unpacking(self):
  474. driver.parse_string("a, *b, c = x\n")
  475. driver.parse_string("[*a, b] = x\n")
  476. driver.parse_string("(z, *y, w) = m\n")
  477. driver.parse_string("for *z, m in d: pass\n")
  478. class TestLiterals(GrammarTest):
  479. def validate(self, s):
  480. driver.parse_string(support.dedent(s) + "\n\n")
  481. def test_multiline_bytes_literals(self):
  482. s = """
  483. md5test(b"\xaa" * 80,
  484. (b"Test Using Larger Than Block-Size Key "
  485. b"and Larger Than One Block-Size Data"),
  486. "6f630fad67cda0ee1fb1f562db3aa53e")
  487. """
  488. self.validate(s)
  489. def test_multiline_bytes_tripquote_literals(self):
  490. s = '''
  491. b"""
  492. <?xml version="1.0" encoding="UTF-8"?>
  493. <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN">
  494. """
  495. '''
  496. self.validate(s)
  497. def test_multiline_str_literals(self):
  498. s = """
  499. md5test("\xaa" * 80,
  500. ("Test Using Larger Than Block-Size Key "
  501. "and Larger Than One Block-Size Data"),
  502. "6f630fad67cda0ee1fb1f562db3aa53e")
  503. """
  504. self.validate(s)
  505. class TestNamedAssignments(GrammarTest):
  506. """Also known as the walrus operator."""
  507. def test_named_assignment_if(self):
  508. driver.parse_string("if f := x(): pass\n")
  509. def test_named_assignment_while(self):
  510. driver.parse_string("while f := x(): pass\n")
  511. def test_named_assignment_generator(self):
  512. driver.parse_string("any((lastNum := num) == 1 for num in [1, 2, 3])\n")
  513. def test_named_assignment_listcomp(self):
  514. driver.parse_string("[(lastNum := num) == 1 for num in [1, 2, 3]]\n")
  515. class TestPositionalOnlyArgs(GrammarTest):
  516. def test_one_pos_only_arg(self):
  517. driver.parse_string("def one_pos_only_arg(a, /): pass\n")
  518. def test_all_markers(self):
  519. driver.parse_string(
  520. "def all_markers(a, b=2, /, c, d=4, *, e=5, f): pass\n")
  521. def test_all_with_args_and_kwargs(self):
  522. driver.parse_string(
  523. """def all_markers_with_args_and_kwargs(
  524. aa, b, /, _cc, d, *args, e, f_f, **kwargs,
  525. ):
  526. pass\n""")
  527. def test_lambda_soup(self):
  528. driver.parse_string(
  529. "lambda a, b, /, c, d, *args, e, f, **kw: kw\n")
  530. def test_only_positional_or_keyword(self):
  531. driver.parse_string("def func(a,b,/,*,g,e=3): pass\n")
  532. class TestPickleableException(unittest.TestCase):
  533. def test_ParseError(self):
  534. err = ParseError('msg', 2, None, (1, 'context'))
  535. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  536. err2 = pickle.loads(pickle.dumps(err, protocol=proto))
  537. self.assertEqual(err.args, err2.args)
  538. self.assertEqual(err.msg, err2.msg)
  539. self.assertEqual(err.type, err2.type)
  540. self.assertEqual(err.value, err2.value)
  541. self.assertEqual(err.context, err2.context)
  542. def diff_texts(a, b, filename):
  543. a = a.splitlines()
  544. b = b.splitlines()
  545. return difflib.unified_diff(a, b, filename, filename,
  546. "(original)", "(reserialized)",
  547. lineterm="")
  548. if __name__ == '__main__':
  549. unittest.main()