test_pyparse.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. "Test pyparse, coverage 96%."
  2. from idlelib import pyparse
  3. import unittest
  4. from collections import namedtuple
  5. class ParseMapTest(unittest.TestCase):
  6. def test_parsemap(self):
  7. keepwhite = {ord(c): ord(c) for c in ' \t\n\r'}
  8. mapping = pyparse.ParseMap(keepwhite)
  9. self.assertEqual(mapping[ord('\t')], ord('\t'))
  10. self.assertEqual(mapping[ord('a')], ord('x'))
  11. self.assertEqual(mapping[1000], ord('x'))
  12. def test_trans(self):
  13. # trans is the production instance of ParseMap, used in _study1
  14. parser = pyparse.Parser(4, 4)
  15. self.assertEqual('\t a([{b}])b"c\'d\n'.translate(pyparse.trans),
  16. 'xxx(((x)))x"x\'x\n')
  17. class PyParseTest(unittest.TestCase):
  18. @classmethod
  19. def setUpClass(cls):
  20. cls.parser = pyparse.Parser(indentwidth=4, tabwidth=4)
  21. @classmethod
  22. def tearDownClass(cls):
  23. del cls.parser
  24. def test_init(self):
  25. self.assertEqual(self.parser.indentwidth, 4)
  26. self.assertEqual(self.parser.tabwidth, 4)
  27. def test_set_code(self):
  28. eq = self.assertEqual
  29. p = self.parser
  30. setcode = p.set_code
  31. # Not empty and doesn't end with newline.
  32. with self.assertRaises(AssertionError):
  33. setcode('a')
  34. tests = ('',
  35. 'a\n')
  36. for string in tests:
  37. with self.subTest(string=string):
  38. setcode(string)
  39. eq(p.code, string)
  40. eq(p.study_level, 0)
  41. def test_find_good_parse_start(self):
  42. eq = self.assertEqual
  43. p = self.parser
  44. setcode = p.set_code
  45. start = p.find_good_parse_start
  46. def char_in_string_false(index): return False
  47. # First line starts with 'def' and ends with ':', then 0 is the pos.
  48. setcode('def spam():\n')
  49. eq(start(char_in_string_false), 0)
  50. # First line begins with a keyword in the list and ends
  51. # with an open brace, then 0 is the pos. This is how
  52. # hyperparser calls this function as the newline is not added
  53. # in the editor, but rather on the call to setcode.
  54. setcode('class spam( ' + ' \n')
  55. eq(start(char_in_string_false), 0)
  56. # Split def across lines.
  57. setcode('"""This is a module docstring"""\n'
  58. 'class C:\n'
  59. ' def __init__(self, a,\n'
  60. ' b=True):\n'
  61. ' pass\n'
  62. )
  63. pos0, pos = 33, 42 # Start of 'class...', ' def' lines.
  64. # Passing no value or non-callable should fail (issue 32989).
  65. with self.assertRaises(TypeError):
  66. start()
  67. with self.assertRaises(TypeError):
  68. start(False)
  69. # Make text look like a string. This returns pos as the start
  70. # position, but it's set to None.
  71. self.assertIsNone(start(is_char_in_string=lambda index: True))
  72. # Make all text look like it's not in a string. This means that it
  73. # found a good start position.
  74. eq(start(char_in_string_false), pos)
  75. # If the beginning of the def line is not in a string, then it
  76. # returns that as the index.
  77. eq(start(is_char_in_string=lambda index: index > pos), pos)
  78. # If the beginning of the def line is in a string, then it
  79. # looks for a previous index.
  80. eq(start(is_char_in_string=lambda index: index >= pos), pos0)
  81. # If everything before the 'def' is in a string, then returns None.
  82. # The non-continuation def line returns 44 (see below).
  83. eq(start(is_char_in_string=lambda index: index < pos), None)
  84. # Code without extra line break in def line - mostly returns the same
  85. # values.
  86. setcode('"""This is a module docstring"""\n'
  87. 'class C:\n'
  88. ' def __init__(self, a, b=True):\n'
  89. ' pass\n'
  90. ) # Does not affect class, def positions.
  91. eq(start(char_in_string_false), pos)
  92. eq(start(is_char_in_string=lambda index: index > pos), pos)
  93. eq(start(is_char_in_string=lambda index: index >= pos), pos0)
  94. # When the def line isn't split, this returns which doesn't match the
  95. # split line test.
  96. eq(start(is_char_in_string=lambda index: index < pos), pos)
  97. def test_set_lo(self):
  98. code = (
  99. '"""This is a module docstring"""\n'
  100. 'class C:\n'
  101. ' def __init__(self, a,\n'
  102. ' b=True):\n'
  103. ' pass\n'
  104. )
  105. pos = 42
  106. p = self.parser
  107. p.set_code(code)
  108. # Previous character is not a newline.
  109. with self.assertRaises(AssertionError):
  110. p.set_lo(5)
  111. # A value of 0 doesn't change self.code.
  112. p.set_lo(0)
  113. self.assertEqual(p.code, code)
  114. # An index that is preceded by a newline.
  115. p.set_lo(pos)
  116. self.assertEqual(p.code, code[pos:])
  117. def test_study1(self):
  118. eq = self.assertEqual
  119. p = self.parser
  120. setcode = p.set_code
  121. study = p._study1
  122. (NONE, BACKSLASH, FIRST, NEXT, BRACKET) = range(5)
  123. TestInfo = namedtuple('TestInfo', ['string', 'goodlines',
  124. 'continuation'])
  125. tests = (
  126. TestInfo('', [0], NONE),
  127. # Docstrings.
  128. TestInfo('"""This is a complete docstring."""\n', [0, 1], NONE),
  129. TestInfo("'''This is a complete docstring.'''\n", [0, 1], NONE),
  130. TestInfo('"""This is a continued docstring.\n', [0, 1], FIRST),
  131. TestInfo("'''This is a continued docstring.\n", [0, 1], FIRST),
  132. TestInfo('"""Closing quote does not match."\n', [0, 1], FIRST),
  133. TestInfo('"""Bracket in docstring [\n', [0, 1], FIRST),
  134. TestInfo("'''Incomplete two line docstring.\n\n", [0, 2], NEXT),
  135. # Single-quoted strings.
  136. TestInfo('"This is a complete string."\n', [0, 1], NONE),
  137. TestInfo('"This is an incomplete string.\n', [0, 1], NONE),
  138. TestInfo("'This is more incomplete.\n\n", [0, 1, 2], NONE),
  139. # Comment (backslash does not continue comments).
  140. TestInfo('# Comment\\\n', [0, 1], NONE),
  141. # Brackets.
  142. TestInfo('("""Complete string in bracket"""\n', [0, 1], BRACKET),
  143. TestInfo('("""Open string in bracket\n', [0, 1], FIRST),
  144. TestInfo('a = (1 + 2) - 5 *\\\n', [0, 1], BACKSLASH), # No bracket.
  145. TestInfo('\n def function1(self, a,\n b):\n',
  146. [0, 1, 3], NONE),
  147. TestInfo('\n def function1(self, a,\\\n', [0, 1, 2], BRACKET),
  148. TestInfo('\n def function1(self, a,\n', [0, 1, 2], BRACKET),
  149. TestInfo('())\n', [0, 1], NONE), # Extra closer.
  150. TestInfo(')(\n', [0, 1], BRACKET), # Extra closer.
  151. # For the mismatched example, it doesn't look like continuation.
  152. TestInfo('{)(]\n', [0, 1], NONE), # Mismatched.
  153. )
  154. for test in tests:
  155. with self.subTest(string=test.string):
  156. setcode(test.string) # resets study_level
  157. study()
  158. eq(p.study_level, 1)
  159. eq(p.goodlines, test.goodlines)
  160. eq(p.continuation, test.continuation)
  161. # Called again, just returns without reprocessing.
  162. self.assertIsNone(study())
  163. def test_get_continuation_type(self):
  164. eq = self.assertEqual
  165. p = self.parser
  166. setcode = p.set_code
  167. gettype = p.get_continuation_type
  168. (NONE, BACKSLASH, FIRST, NEXT, BRACKET) = range(5)
  169. TestInfo = namedtuple('TestInfo', ['string', 'continuation'])
  170. tests = (
  171. TestInfo('', NONE),
  172. TestInfo('"""This is a continuation docstring.\n', FIRST),
  173. TestInfo("'''This is a multiline-continued docstring.\n\n", NEXT),
  174. TestInfo('a = (1 + 2) - 5 *\\\n', BACKSLASH),
  175. TestInfo('\n def function1(self, a,\\\n', BRACKET)
  176. )
  177. for test in tests:
  178. with self.subTest(string=test.string):
  179. setcode(test.string)
  180. eq(gettype(), test.continuation)
  181. def test_study2(self):
  182. eq = self.assertEqual
  183. p = self.parser
  184. setcode = p.set_code
  185. study = p._study2
  186. TestInfo = namedtuple('TestInfo', ['string', 'start', 'end', 'lastch',
  187. 'openbracket', 'bracketing'])
  188. tests = (
  189. TestInfo('', 0, 0, '', None, ((0, 0),)),
  190. TestInfo("'''This is a multiline continuation docstring.\n\n",
  191. 0, 48, "'", None, ((0, 0), (0, 1), (48, 0))),
  192. TestInfo(' # Comment\\\n',
  193. 0, 12, '', None, ((0, 0), (1, 1), (12, 0))),
  194. # A comment without a space is a special case
  195. TestInfo(' #Comment\\\n',
  196. 0, 0, '', None, ((0, 0),)),
  197. # Backslash continuation.
  198. TestInfo('a = (1 + 2) - 5 *\\\n',
  199. 0, 19, '*', None, ((0, 0), (4, 1), (11, 0))),
  200. # Bracket continuation with close.
  201. TestInfo('\n def function1(self, a,\n b):\n',
  202. 1, 48, ':', None, ((1, 0), (17, 1), (46, 0))),
  203. # Bracket continuation with unneeded backslash.
  204. TestInfo('\n def function1(self, a,\\\n',
  205. 1, 28, ',', 17, ((1, 0), (17, 1))),
  206. # Bracket continuation.
  207. TestInfo('\n def function1(self, a,\n',
  208. 1, 27, ',', 17, ((1, 0), (17, 1))),
  209. # Bracket continuation with comment at end of line with text.
  210. TestInfo('\n def function1(self, a, # End of line comment.\n',
  211. 1, 51, ',', 17, ((1, 0), (17, 1), (28, 2), (51, 1))),
  212. # Multi-line statement with comment line in between code lines.
  213. TestInfo(' a = ["first item",\n # Comment line\n "next item",\n',
  214. 0, 55, ',', 6, ((0, 0), (6, 1), (7, 2), (19, 1),
  215. (23, 2), (38, 1), (42, 2), (53, 1))),
  216. TestInfo('())\n',
  217. 0, 4, ')', None, ((0, 0), (0, 1), (2, 0), (3, 0))),
  218. TestInfo(')(\n', 0, 3, '(', 1, ((0, 0), (1, 0), (1, 1))),
  219. # Wrong closers still decrement stack level.
  220. TestInfo('{)(]\n',
  221. 0, 5, ']', None, ((0, 0), (0, 1), (2, 0), (2, 1), (4, 0))),
  222. # Character after backslash.
  223. TestInfo(':\\a\n', 0, 4, '\\a', None, ((0, 0),)),
  224. TestInfo('\n', 0, 0, '', None, ((0, 0),)),
  225. )
  226. for test in tests:
  227. with self.subTest(string=test.string):
  228. setcode(test.string)
  229. study()
  230. eq(p.study_level, 2)
  231. eq(p.stmt_start, test.start)
  232. eq(p.stmt_end, test.end)
  233. eq(p.lastch, test.lastch)
  234. eq(p.lastopenbracketpos, test.openbracket)
  235. eq(p.stmt_bracketing, test.bracketing)
  236. # Called again, just returns without reprocessing.
  237. self.assertIsNone(study())
  238. def test_get_num_lines_in_stmt(self):
  239. eq = self.assertEqual
  240. p = self.parser
  241. setcode = p.set_code
  242. getlines = p.get_num_lines_in_stmt
  243. TestInfo = namedtuple('TestInfo', ['string', 'lines'])
  244. tests = (
  245. TestInfo('[x for x in a]\n', 1), # Closed on one line.
  246. TestInfo('[x\nfor x in a\n', 2), # Not closed.
  247. TestInfo('[x\\\nfor x in a\\\n', 2), # "", unneeded backslashes.
  248. TestInfo('[x\nfor x in a\n]\n', 3), # Closed on multi-line.
  249. TestInfo('\n"""Docstring comment L1"""\nL2\nL3\nL4\n', 1),
  250. TestInfo('\n"""Docstring comment L1\nL2"""\nL3\nL4\n', 1),
  251. TestInfo('\n"""Docstring comment L1\\\nL2\\\nL3\\\nL4\\\n', 4),
  252. TestInfo('\n\n"""Docstring comment L1\\\nL2\\\nL3\\\nL4\\\n"""\n', 5)
  253. )
  254. # Blank string doesn't have enough elements in goodlines.
  255. setcode('')
  256. with self.assertRaises(IndexError):
  257. getlines()
  258. for test in tests:
  259. with self.subTest(string=test.string):
  260. setcode(test.string)
  261. eq(getlines(), test.lines)
  262. def test_compute_bracket_indent(self):
  263. eq = self.assertEqual
  264. p = self.parser
  265. setcode = p.set_code
  266. indent = p.compute_bracket_indent
  267. TestInfo = namedtuple('TestInfo', ['string', 'spaces'])
  268. tests = (
  269. TestInfo('def function1(self, a,\n', 14),
  270. # Characters after bracket.
  271. TestInfo('\n def function1(self, a,\n', 18),
  272. TestInfo('\n\tdef function1(self, a,\n', 18),
  273. # No characters after bracket.
  274. TestInfo('\n def function1(\n', 8),
  275. TestInfo('\n\tdef function1(\n', 8),
  276. TestInfo('\n def function1( \n', 8), # Ignore extra spaces.
  277. TestInfo('[\n"first item",\n # Comment line\n "next item",\n', 0),
  278. TestInfo('[\n "first item",\n # Comment line\n "next item",\n', 2),
  279. TestInfo('["first item",\n # Comment line\n "next item",\n', 1),
  280. TestInfo('(\n', 4),
  281. TestInfo('(a\n', 1),
  282. )
  283. # Must be C_BRACKET continuation type.
  284. setcode('def function1(self, a, b):\n')
  285. with self.assertRaises(AssertionError):
  286. indent()
  287. for test in tests:
  288. setcode(test.string)
  289. eq(indent(), test.spaces)
  290. def test_compute_backslash_indent(self):
  291. eq = self.assertEqual
  292. p = self.parser
  293. setcode = p.set_code
  294. indent = p.compute_backslash_indent
  295. # Must be C_BACKSLASH continuation type.
  296. errors = (('def function1(self, a, b\\\n'), # Bracket.
  297. (' """ (\\\n'), # Docstring.
  298. ('a = #\\\n'), # Inline comment.
  299. )
  300. for string in errors:
  301. with self.subTest(string=string):
  302. setcode(string)
  303. with self.assertRaises(AssertionError):
  304. indent()
  305. TestInfo = namedtuple('TestInfo', ('string', 'spaces'))
  306. tests = (TestInfo('a = (1 + 2) - 5 *\\\n', 4),
  307. TestInfo('a = 1 + 2 - 5 *\\\n', 4),
  308. TestInfo(' a = 1 + 2 - 5 *\\\n', 8),
  309. TestInfo(' a = "spam"\\\n', 6),
  310. TestInfo(' a = \\\n"a"\\\n', 4),
  311. TestInfo(' a = #\\\n"a"\\\n', 5),
  312. TestInfo('a == \\\n', 2),
  313. TestInfo('a != \\\n', 2),
  314. # Difference between containing = and those not.
  315. TestInfo('\\\n', 2),
  316. TestInfo(' \\\n', 6),
  317. TestInfo('\t\\\n', 6),
  318. TestInfo('a\\\n', 3),
  319. TestInfo('{}\\\n', 4),
  320. TestInfo('(1 + 2) - 5 *\\\n', 3),
  321. )
  322. for test in tests:
  323. with self.subTest(string=test.string):
  324. setcode(test.string)
  325. eq(indent(), test.spaces)
  326. def test_get_base_indent_string(self):
  327. eq = self.assertEqual
  328. p = self.parser
  329. setcode = p.set_code
  330. baseindent = p.get_base_indent_string
  331. TestInfo = namedtuple('TestInfo', ['string', 'indent'])
  332. tests = (TestInfo('', ''),
  333. TestInfo('def a():\n', ''),
  334. TestInfo('\tdef a():\n', '\t'),
  335. TestInfo(' def a():\n', ' '),
  336. TestInfo(' def a(\n', ' '),
  337. TestInfo('\t\n def a(\n', ' '),
  338. TestInfo('\t\n # Comment.\n', ' '),
  339. )
  340. for test in tests:
  341. with self.subTest(string=test.string):
  342. setcode(test.string)
  343. eq(baseindent(), test.indent)
  344. def test_is_block_opener(self):
  345. yes = self.assertTrue
  346. no = self.assertFalse
  347. p = self.parser
  348. setcode = p.set_code
  349. opener = p.is_block_opener
  350. TestInfo = namedtuple('TestInfo', ['string', 'assert_'])
  351. tests = (
  352. TestInfo('def a():\n', yes),
  353. TestInfo('\n def function1(self, a,\n b):\n', yes),
  354. TestInfo(':\n', yes),
  355. TestInfo('a:\n', yes),
  356. TestInfo('):\n', yes),
  357. TestInfo('(:\n', yes),
  358. TestInfo('":\n', no),
  359. TestInfo('\n def function1(self, a,\n', no),
  360. TestInfo('def function1(self, a):\n pass\n', no),
  361. TestInfo('# A comment:\n', no),
  362. TestInfo('"""A docstring:\n', no),
  363. TestInfo('"""A docstring:\n', no),
  364. )
  365. for test in tests:
  366. with self.subTest(string=test.string):
  367. setcode(test.string)
  368. test.assert_(opener())
  369. def test_is_block_closer(self):
  370. yes = self.assertTrue
  371. no = self.assertFalse
  372. p = self.parser
  373. setcode = p.set_code
  374. closer = p.is_block_closer
  375. TestInfo = namedtuple('TestInfo', ['string', 'assert_'])
  376. tests = (
  377. TestInfo('return\n', yes),
  378. TestInfo('\tbreak\n', yes),
  379. TestInfo(' continue\n', yes),
  380. TestInfo(' raise\n', yes),
  381. TestInfo('pass \n', yes),
  382. TestInfo('pass\t\n', yes),
  383. TestInfo('return #\n', yes),
  384. TestInfo('raised\n', no),
  385. TestInfo('returning\n', no),
  386. TestInfo('# return\n', no),
  387. TestInfo('"""break\n', no),
  388. TestInfo('"continue\n', no),
  389. TestInfo('def function1(self, a):\n pass\n', yes),
  390. )
  391. for test in tests:
  392. with self.subTest(string=test.string):
  393. setcode(test.string)
  394. test.assert_(closer())
  395. def test_get_last_stmt_bracketing(self):
  396. eq = self.assertEqual
  397. p = self.parser
  398. setcode = p.set_code
  399. bracketing = p.get_last_stmt_bracketing
  400. TestInfo = namedtuple('TestInfo', ['string', 'bracket'])
  401. tests = (
  402. TestInfo('', ((0, 0),)),
  403. TestInfo('a\n', ((0, 0),)),
  404. TestInfo('()()\n', ((0, 0), (0, 1), (2, 0), (2, 1), (4, 0))),
  405. TestInfo('(\n)()\n', ((0, 0), (0, 1), (3, 0), (3, 1), (5, 0))),
  406. TestInfo('()\n()\n', ((3, 0), (3, 1), (5, 0))),
  407. TestInfo('()(\n)\n', ((0, 0), (0, 1), (2, 0), (2, 1), (5, 0))),
  408. TestInfo('(())\n', ((0, 0), (0, 1), (1, 2), (3, 1), (4, 0))),
  409. TestInfo('(\n())\n', ((0, 0), (0, 1), (2, 2), (4, 1), (5, 0))),
  410. # Same as matched test.
  411. TestInfo('{)(]\n', ((0, 0), (0, 1), (2, 0), (2, 1), (4, 0))),
  412. TestInfo('(((())\n',
  413. ((0, 0), (0, 1), (1, 2), (2, 3), (3, 4), (5, 3), (6, 2))),
  414. )
  415. for test in tests:
  416. with self.subTest(string=test.string):
  417. setcode(test.string)
  418. eq(bracketing(), test.bracket)
  419. if __name__ == '__main__':
  420. unittest.main(verbosity=2)