test_pyparse.py 19 KB

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