test_codecontext.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. "Test codecontext, coverage 100%"
  2. from idlelib import codecontext
  3. import unittest
  4. import unittest.mock
  5. from test.support import requires
  6. from tkinter import NSEW, Tk, Frame, Text, TclError
  7. from unittest import mock
  8. import re
  9. from idlelib import config
  10. usercfg = codecontext.idleConf.userCfg
  11. testcfg = {
  12. 'main': config.IdleUserConfParser(''),
  13. 'highlight': config.IdleUserConfParser(''),
  14. 'keys': config.IdleUserConfParser(''),
  15. 'extensions': config.IdleUserConfParser(''),
  16. }
  17. code_sample = """\
  18. class C1():
  19. # Class comment.
  20. def __init__(self, a, b):
  21. self.a = a
  22. self.b = b
  23. def compare(self):
  24. if a > b:
  25. return a
  26. elif a < b:
  27. return b
  28. else:
  29. return None
  30. """
  31. class DummyEditwin:
  32. def __init__(self, root, frame, text):
  33. self.root = root
  34. self.top = root
  35. self.text_frame = frame
  36. self.text = text
  37. self.label = ''
  38. def getlineno(self, index):
  39. return int(float(self.text.index(index)))
  40. def update_menu_label(self, **kwargs):
  41. self.label = kwargs['label']
  42. class CodeContextTest(unittest.TestCase):
  43. @classmethod
  44. def setUpClass(cls):
  45. requires('gui')
  46. root = cls.root = Tk()
  47. root.withdraw()
  48. frame = cls.frame = Frame(root)
  49. text = cls.text = Text(frame)
  50. text.insert('1.0', code_sample)
  51. # Need to pack for creation of code context text widget.
  52. frame.pack(side='left', fill='both', expand=1)
  53. text.grid(row=1, column=1, sticky=NSEW)
  54. cls.editor = DummyEditwin(root, frame, text)
  55. codecontext.idleConf.userCfg = testcfg
  56. @classmethod
  57. def tearDownClass(cls):
  58. codecontext.idleConf.userCfg = usercfg
  59. cls.editor.text.delete('1.0', 'end')
  60. del cls.editor, cls.frame, cls.text
  61. cls.root.update_idletasks()
  62. cls.root.destroy()
  63. del cls.root
  64. def setUp(self):
  65. self.text.yview(0)
  66. self.text['font'] = 'TkFixedFont'
  67. self.cc = codecontext.CodeContext(self.editor)
  68. self.highlight_cfg = {"background": '#abcdef',
  69. "foreground": '#123456'}
  70. orig_idleConf_GetHighlight = codecontext.idleConf.GetHighlight
  71. def mock_idleconf_GetHighlight(theme, element):
  72. if element == 'context':
  73. return self.highlight_cfg
  74. return orig_idleConf_GetHighlight(theme, element)
  75. GetHighlight_patcher = unittest.mock.patch.object(
  76. codecontext.idleConf, 'GetHighlight', mock_idleconf_GetHighlight)
  77. GetHighlight_patcher.start()
  78. self.addCleanup(GetHighlight_patcher.stop)
  79. self.font_override = 'TkFixedFont'
  80. def mock_idleconf_GetFont(root, configType, section):
  81. return self.font_override
  82. GetFont_patcher = unittest.mock.patch.object(
  83. codecontext.idleConf, 'GetFont', mock_idleconf_GetFont)
  84. GetFont_patcher.start()
  85. self.addCleanup(GetFont_patcher.stop)
  86. def tearDown(self):
  87. if self.cc.context:
  88. self.cc.context.destroy()
  89. # Explicitly call __del__ to remove scheduled scripts.
  90. self.cc.__del__()
  91. del self.cc.context, self.cc
  92. def test_init(self):
  93. eq = self.assertEqual
  94. ed = self.editor
  95. cc = self.cc
  96. eq(cc.editwin, ed)
  97. eq(cc.text, ed.text)
  98. eq(cc.text['font'], ed.text['font'])
  99. self.assertIsNone(cc.context)
  100. eq(cc.info, [(0, -1, '', False)])
  101. eq(cc.topvisible, 1)
  102. self.assertIsNone(self.cc.t1)
  103. def test_del(self):
  104. self.cc.__del__()
  105. def test_del_with_timer(self):
  106. timer = self.cc.t1 = self.text.after(10000, lambda: None)
  107. self.cc.__del__()
  108. with self.assertRaises(TclError) as cm:
  109. self.root.tk.call('after', 'info', timer)
  110. self.assertIn("doesn't exist", str(cm.exception))
  111. def test_reload(self):
  112. codecontext.CodeContext.reload()
  113. self.assertEqual(self.cc.context_depth, 15)
  114. def test_toggle_code_context_event(self):
  115. eq = self.assertEqual
  116. cc = self.cc
  117. toggle = cc.toggle_code_context_event
  118. # Make sure code context is off.
  119. if cc.context:
  120. toggle()
  121. # Toggle on.
  122. toggle()
  123. self.assertIsNotNone(cc.context)
  124. eq(cc.context['font'], self.text['font'])
  125. eq(cc.context['fg'], self.highlight_cfg['foreground'])
  126. eq(cc.context['bg'], self.highlight_cfg['background'])
  127. eq(cc.context.get('1.0', 'end-1c'), '')
  128. eq(cc.editwin.label, 'Hide Code Context')
  129. eq(self.root.tk.call('after', 'info', self.cc.t1)[1], 'timer')
  130. # Toggle off.
  131. toggle()
  132. self.assertIsNone(cc.context)
  133. eq(cc.editwin.label, 'Show Code Context')
  134. self.assertIsNone(self.cc.t1)
  135. # Scroll down and toggle back on.
  136. line11_context = '\n'.join(x[2] for x in cc.get_context(11)[0])
  137. cc.text.yview(11)
  138. toggle()
  139. eq(cc.context.get('1.0', 'end-1c'), line11_context)
  140. # Toggle off and on again.
  141. toggle()
  142. toggle()
  143. eq(cc.context.get('1.0', 'end-1c'), line11_context)
  144. def test_get_context(self):
  145. eq = self.assertEqual
  146. gc = self.cc.get_context
  147. # stopline must be greater than 0.
  148. with self.assertRaises(AssertionError):
  149. gc(1, stopline=0)
  150. eq(gc(3), ([(2, 0, 'class C1():', 'class')], 0))
  151. # Don't return comment.
  152. eq(gc(4), ([(2, 0, 'class C1():', 'class')], 0))
  153. # Two indentation levels and no comment.
  154. eq(gc(5), ([(2, 0, 'class C1():', 'class'),
  155. (4, 4, ' def __init__(self, a, b):', 'def')], 0))
  156. # Only one 'def' is returned, not both at the same indent level.
  157. eq(gc(10), ([(2, 0, 'class C1():', 'class'),
  158. (7, 4, ' def compare(self):', 'def'),
  159. (8, 8, ' if a > b:', 'if')], 0))
  160. # With 'elif', also show the 'if' even though it's at the same level.
  161. eq(gc(11), ([(2, 0, 'class C1():', 'class'),
  162. (7, 4, ' def compare(self):', 'def'),
  163. (8, 8, ' if a > b:', 'if'),
  164. (10, 8, ' elif a < b:', 'elif')], 0))
  165. # Set stop_line to not go back to first line in source code.
  166. # Return includes stop_line.
  167. eq(gc(11, stopline=2), ([(2, 0, 'class C1():', 'class'),
  168. (7, 4, ' def compare(self):', 'def'),
  169. (8, 8, ' if a > b:', 'if'),
  170. (10, 8, ' elif a < b:', 'elif')], 0))
  171. eq(gc(11, stopline=3), ([(7, 4, ' def compare(self):', 'def'),
  172. (8, 8, ' if a > b:', 'if'),
  173. (10, 8, ' elif a < b:', 'elif')], 4))
  174. eq(gc(11, stopline=8), ([(8, 8, ' if a > b:', 'if'),
  175. (10, 8, ' elif a < b:', 'elif')], 8))
  176. # Set stop_indent to test indent level to stop at.
  177. eq(gc(11, stopindent=4), ([(7, 4, ' def compare(self):', 'def'),
  178. (8, 8, ' if a > b:', 'if'),
  179. (10, 8, ' elif a < b:', 'elif')], 4))
  180. # Check that the 'if' is included.
  181. eq(gc(11, stopindent=8), ([(8, 8, ' if a > b:', 'if'),
  182. (10, 8, ' elif a < b:', 'elif')], 8))
  183. def test_update_code_context(self):
  184. eq = self.assertEqual
  185. cc = self.cc
  186. # Ensure code context is active.
  187. if not cc.context:
  188. cc.toggle_code_context_event()
  189. # Invoke update_code_context without scrolling - nothing happens.
  190. self.assertIsNone(cc.update_code_context())
  191. eq(cc.info, [(0, -1, '', False)])
  192. eq(cc.topvisible, 1)
  193. # Scroll down to line 1.
  194. cc.text.yview(1)
  195. cc.update_code_context()
  196. eq(cc.info, [(0, -1, '', False)])
  197. eq(cc.topvisible, 2)
  198. eq(cc.context.get('1.0', 'end-1c'), '')
  199. # Scroll down to line 2.
  200. cc.text.yview(2)
  201. cc.update_code_context()
  202. eq(cc.info, [(0, -1, '', False), (2, 0, 'class C1():', 'class')])
  203. eq(cc.topvisible, 3)
  204. eq(cc.context.get('1.0', 'end-1c'), 'class C1():')
  205. # Scroll down to line 3. Since it's a comment, nothing changes.
  206. cc.text.yview(3)
  207. cc.update_code_context()
  208. eq(cc.info, [(0, -1, '', False), (2, 0, 'class C1():', 'class')])
  209. eq(cc.topvisible, 4)
  210. eq(cc.context.get('1.0', 'end-1c'), 'class C1():')
  211. # Scroll down to line 4.
  212. cc.text.yview(4)
  213. cc.update_code_context()
  214. eq(cc.info, [(0, -1, '', False),
  215. (2, 0, 'class C1():', 'class'),
  216. (4, 4, ' def __init__(self, a, b):', 'def')])
  217. eq(cc.topvisible, 5)
  218. eq(cc.context.get('1.0', 'end-1c'), 'class C1():\n'
  219. ' def __init__(self, a, b):')
  220. # Scroll down to line 11. Last 'def' is removed.
  221. cc.text.yview(11)
  222. cc.update_code_context()
  223. eq(cc.info, [(0, -1, '', False),
  224. (2, 0, 'class C1():', 'class'),
  225. (7, 4, ' def compare(self):', 'def'),
  226. (8, 8, ' if a > b:', 'if'),
  227. (10, 8, ' elif a < b:', 'elif')])
  228. eq(cc.topvisible, 12)
  229. eq(cc.context.get('1.0', 'end-1c'), 'class C1():\n'
  230. ' def compare(self):\n'
  231. ' if a > b:\n'
  232. ' elif a < b:')
  233. # No scroll. No update, even though context_depth changed.
  234. cc.update_code_context()
  235. cc.context_depth = 1
  236. eq(cc.info, [(0, -1, '', False),
  237. (2, 0, 'class C1():', 'class'),
  238. (7, 4, ' def compare(self):', 'def'),
  239. (8, 8, ' if a > b:', 'if'),
  240. (10, 8, ' elif a < b:', 'elif')])
  241. eq(cc.topvisible, 12)
  242. eq(cc.context.get('1.0', 'end-1c'), 'class C1():\n'
  243. ' def compare(self):\n'
  244. ' if a > b:\n'
  245. ' elif a < b:')
  246. # Scroll up.
  247. cc.text.yview(5)
  248. cc.update_code_context()
  249. eq(cc.info, [(0, -1, '', False),
  250. (2, 0, 'class C1():', 'class'),
  251. (4, 4, ' def __init__(self, a, b):', 'def')])
  252. eq(cc.topvisible, 6)
  253. # context_depth is 1.
  254. eq(cc.context.get('1.0', 'end-1c'), ' def __init__(self, a, b):')
  255. def test_jumptoline(self):
  256. eq = self.assertEqual
  257. cc = self.cc
  258. jump = cc.jumptoline
  259. if not cc.context:
  260. cc.toggle_code_context_event()
  261. # Empty context.
  262. cc.text.yview('2.0')
  263. cc.update_code_context()
  264. eq(cc.topvisible, 2)
  265. cc.context.mark_set('insert', '1.5')
  266. jump()
  267. eq(cc.topvisible, 1)
  268. # 4 lines of context showing.
  269. cc.text.yview('12.0')
  270. cc.update_code_context()
  271. eq(cc.topvisible, 12)
  272. cc.context.mark_set('insert', '3.0')
  273. jump()
  274. eq(cc.topvisible, 8)
  275. # More context lines than limit.
  276. cc.context_depth = 2
  277. cc.text.yview('12.0')
  278. cc.update_code_context()
  279. eq(cc.topvisible, 12)
  280. cc.context.mark_set('insert', '1.0')
  281. jump()
  282. eq(cc.topvisible, 8)
  283. # Context selection stops jump.
  284. cc.text.yview('5.0')
  285. cc.update_code_context()
  286. cc.context.tag_add('sel', '1.0', '2.0')
  287. cc.context.mark_set('insert', '1.0')
  288. jump() # Without selection, to line 2.
  289. eq(cc.topvisible, 5)
  290. @mock.patch.object(codecontext.CodeContext, 'update_code_context')
  291. def test_timer_event(self, mock_update):
  292. # Ensure code context is not active.
  293. if self.cc.context:
  294. self.cc.toggle_code_context_event()
  295. self.cc.timer_event()
  296. mock_update.assert_not_called()
  297. # Activate code context.
  298. self.cc.toggle_code_context_event()
  299. self.cc.timer_event()
  300. mock_update.assert_called()
  301. def test_font(self):
  302. eq = self.assertEqual
  303. cc = self.cc
  304. orig_font = cc.text['font']
  305. test_font = 'TkTextFont'
  306. self.assertNotEqual(orig_font, test_font)
  307. # Ensure code context is not active.
  308. if cc.context is not None:
  309. cc.toggle_code_context_event()
  310. self.font_override = test_font
  311. # Nothing breaks or changes with inactive code context.
  312. cc.update_font()
  313. # Activate code context, previous font change is immediately effective.
  314. cc.toggle_code_context_event()
  315. eq(cc.context['font'], test_font)
  316. # Call the font update, change is picked up.
  317. self.font_override = orig_font
  318. cc.update_font()
  319. eq(cc.context['font'], orig_font)
  320. def test_highlight_colors(self):
  321. eq = self.assertEqual
  322. cc = self.cc
  323. orig_colors = dict(self.highlight_cfg)
  324. test_colors = {'background': '#222222', 'foreground': '#ffff00'}
  325. def assert_colors_are_equal(colors):
  326. eq(cc.context['background'], colors['background'])
  327. eq(cc.context['foreground'], colors['foreground'])
  328. # Ensure code context is not active.
  329. if cc.context:
  330. cc.toggle_code_context_event()
  331. self.highlight_cfg = test_colors
  332. # Nothing breaks with inactive code context.
  333. cc.update_highlight_colors()
  334. # Activate code context, previous colors change is immediately effective.
  335. cc.toggle_code_context_event()
  336. assert_colors_are_equal(test_colors)
  337. # Call colors update with no change to the configured colors.
  338. cc.update_highlight_colors()
  339. assert_colors_are_equal(test_colors)
  340. # Call the colors update with code context active, change is picked up.
  341. self.highlight_cfg = orig_colors
  342. cc.update_highlight_colors()
  343. assert_colors_are_equal(orig_colors)
  344. class HelperFunctionText(unittest.TestCase):
  345. def test_get_spaces_firstword(self):
  346. get = codecontext.get_spaces_firstword
  347. test_lines = (
  348. (' first word', (' ', 'first')),
  349. ('\tfirst word', ('\t', 'first')),
  350. (' \u19D4\u19D2: ', (' ', '\u19D4\u19D2')),
  351. ('no spaces', ('', 'no')),
  352. ('', ('', '')),
  353. ('# TEST COMMENT', ('', '')),
  354. (' (continuation)', (' ', ''))
  355. )
  356. for line, expected_output in test_lines:
  357. self.assertEqual(get(line), expected_output)
  358. # Send the pattern in the call.
  359. self.assertEqual(get(' (continuation)',
  360. c=re.compile(r'^(\s*)([^\s]*)')),
  361. (' ', '(continuation)'))
  362. def test_get_line_info(self):
  363. eq = self.assertEqual
  364. gli = codecontext.get_line_info
  365. lines = code_sample.splitlines()
  366. # Line 1 is not a BLOCKOPENER.
  367. eq(gli(lines[0]), (codecontext.INFINITY, '', False))
  368. # Line 2 is a BLOCKOPENER without an indent.
  369. eq(gli(lines[1]), (0, 'class C1():', 'class'))
  370. # Line 3 is not a BLOCKOPENER and does not return the indent level.
  371. eq(gli(lines[2]), (codecontext.INFINITY, ' # Class comment.', False))
  372. # Line 4 is a BLOCKOPENER and is indented.
  373. eq(gli(lines[3]), (4, ' def __init__(self, a, b):', 'def'))
  374. # Line 8 is a different BLOCKOPENER and is indented.
  375. eq(gli(lines[7]), (8, ' if a > b:', 'if'))
  376. # Test tab.
  377. eq(gli('\tif a == b:'), (1, '\tif a == b:', 'if'))
  378. if __name__ == '__main__':
  379. unittest.main(verbosity=2)