test_squeezer.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. "Test squeezer, coverage 95%"
  2. from collections import namedtuple
  3. from textwrap import dedent
  4. from tkinter import Text, Tk
  5. import unittest
  6. from unittest.mock import Mock, NonCallableMagicMock, patch, sentinel, ANY
  7. from test.support import requires
  8. from idlelib.config import idleConf
  9. from idlelib.squeezer import count_lines_with_wrapping, ExpandingButton, \
  10. Squeezer
  11. from idlelib import macosx
  12. from idlelib.textview import view_text
  13. from idlelib.tooltip import Hovertip
  14. from idlelib.pyshell import PyShell
  15. SENTINEL_VALUE = sentinel.SENTINEL_VALUE
  16. def get_test_tk_root(test_instance):
  17. """Helper for tests: Create a root Tk object."""
  18. requires('gui')
  19. root = Tk()
  20. root.withdraw()
  21. def cleanup_root():
  22. root.update_idletasks()
  23. root.destroy()
  24. test_instance.addCleanup(cleanup_root)
  25. return root
  26. class CountLinesTest(unittest.TestCase):
  27. """Tests for the count_lines_with_wrapping function."""
  28. def check(self, expected, text, linewidth):
  29. return self.assertEqual(
  30. expected,
  31. count_lines_with_wrapping(text, linewidth),
  32. )
  33. def test_count_empty(self):
  34. """Test with an empty string."""
  35. self.assertEqual(count_lines_with_wrapping(""), 0)
  36. def test_count_begins_with_empty_line(self):
  37. """Test with a string which begins with a newline."""
  38. self.assertEqual(count_lines_with_wrapping("\ntext"), 2)
  39. def test_count_ends_with_empty_line(self):
  40. """Test with a string which ends with a newline."""
  41. self.assertEqual(count_lines_with_wrapping("text\n"), 1)
  42. def test_count_several_lines(self):
  43. """Test with several lines of text."""
  44. self.assertEqual(count_lines_with_wrapping("1\n2\n3\n"), 3)
  45. def test_empty_lines(self):
  46. self.check(expected=1, text='\n', linewidth=80)
  47. self.check(expected=2, text='\n\n', linewidth=80)
  48. self.check(expected=10, text='\n' * 10, linewidth=80)
  49. def test_long_line(self):
  50. self.check(expected=3, text='a' * 200, linewidth=80)
  51. self.check(expected=3, text='a' * 200 + '\n', linewidth=80)
  52. def test_several_lines_different_lengths(self):
  53. text = dedent("""\
  54. 13 characters
  55. 43 is the number of characters on this line
  56. 7 chars
  57. 13 characters""")
  58. self.check(expected=5, text=text, linewidth=80)
  59. self.check(expected=5, text=text + '\n', linewidth=80)
  60. self.check(expected=6, text=text, linewidth=40)
  61. self.check(expected=7, text=text, linewidth=20)
  62. self.check(expected=11, text=text, linewidth=10)
  63. class SqueezerTest(unittest.TestCase):
  64. """Tests for the Squeezer class."""
  65. def make_mock_editor_window(self, with_text_widget=False):
  66. """Create a mock EditorWindow instance."""
  67. editwin = NonCallableMagicMock()
  68. editwin.width = 80
  69. if with_text_widget:
  70. editwin.root = get_test_tk_root(self)
  71. text_widget = self.make_text_widget(root=editwin.root)
  72. editwin.text = editwin.per.bottom = text_widget
  73. return editwin
  74. def make_squeezer_instance(self, editor_window=None):
  75. """Create an actual Squeezer instance with a mock EditorWindow."""
  76. if editor_window is None:
  77. editor_window = self.make_mock_editor_window()
  78. squeezer = Squeezer(editor_window)
  79. return squeezer
  80. def make_text_widget(self, root=None):
  81. if root is None:
  82. root = get_test_tk_root(self)
  83. text_widget = Text(root)
  84. text_widget["font"] = ('Courier', 10)
  85. text_widget.mark_set("iomark", "1.0")
  86. return text_widget
  87. def set_idleconf_option_with_cleanup(self, configType, section, option, value):
  88. prev_val = idleConf.GetOption(configType, section, option)
  89. idleConf.SetOption(configType, section, option, value)
  90. self.addCleanup(idleConf.SetOption,
  91. configType, section, option, prev_val)
  92. def test_count_lines(self):
  93. """Test Squeezer.count_lines() with various inputs."""
  94. editwin = self.make_mock_editor_window()
  95. squeezer = self.make_squeezer_instance(editwin)
  96. for text_code, line_width, expected in [
  97. (r"'\n'", 80, 1),
  98. (r"'\n' * 3", 80, 3),
  99. (r"'a' * 40 + '\n'", 80, 1),
  100. (r"'a' * 80 + '\n'", 80, 1),
  101. (r"'a' * 200 + '\n'", 80, 3),
  102. (r"'aa\t' * 20", 80, 2),
  103. (r"'aa\t' * 21", 80, 3),
  104. (r"'aa\t' * 20", 40, 4),
  105. ]:
  106. with self.subTest(text_code=text_code,
  107. line_width=line_width,
  108. expected=expected):
  109. text = eval(text_code)
  110. with patch.object(editwin, 'width', line_width):
  111. self.assertEqual(squeezer.count_lines(text), expected)
  112. def test_init(self):
  113. """Test the creation of Squeezer instances."""
  114. editwin = self.make_mock_editor_window()
  115. squeezer = self.make_squeezer_instance(editwin)
  116. self.assertIs(squeezer.editwin, editwin)
  117. self.assertEqual(squeezer.expandingbuttons, [])
  118. def test_write_no_tags(self):
  119. """Test Squeezer's overriding of the EditorWindow's write() method."""
  120. editwin = self.make_mock_editor_window()
  121. for text in ['', 'TEXT', 'LONG TEXT' * 1000, 'MANY_LINES\n' * 100]:
  122. editwin.write = orig_write = Mock(return_value=SENTINEL_VALUE)
  123. squeezer = self.make_squeezer_instance(editwin)
  124. self.assertEqual(squeezer.editwin.write(text, ()), SENTINEL_VALUE)
  125. self.assertEqual(orig_write.call_count, 1)
  126. orig_write.assert_called_with(text, ())
  127. self.assertEqual(len(squeezer.expandingbuttons), 0)
  128. def test_write_not_stdout(self):
  129. """Test Squeezer's overriding of the EditorWindow's write() method."""
  130. for text in ['', 'TEXT', 'LONG TEXT' * 1000, 'MANY_LINES\n' * 100]:
  131. editwin = self.make_mock_editor_window()
  132. editwin.write.return_value = SENTINEL_VALUE
  133. orig_write = editwin.write
  134. squeezer = self.make_squeezer_instance(editwin)
  135. self.assertEqual(squeezer.editwin.write(text, "stderr"),
  136. SENTINEL_VALUE)
  137. self.assertEqual(orig_write.call_count, 1)
  138. orig_write.assert_called_with(text, "stderr")
  139. self.assertEqual(len(squeezer.expandingbuttons), 0)
  140. def test_write_stdout(self):
  141. """Test Squeezer's overriding of the EditorWindow's write() method."""
  142. editwin = self.make_mock_editor_window()
  143. for text in ['', 'TEXT']:
  144. editwin.write = orig_write = Mock(return_value=SENTINEL_VALUE)
  145. squeezer = self.make_squeezer_instance(editwin)
  146. squeezer.auto_squeeze_min_lines = 50
  147. self.assertEqual(squeezer.editwin.write(text, "stdout"),
  148. SENTINEL_VALUE)
  149. self.assertEqual(orig_write.call_count, 1)
  150. orig_write.assert_called_with(text, "stdout")
  151. self.assertEqual(len(squeezer.expandingbuttons), 0)
  152. for text in ['LONG TEXT' * 1000, 'MANY_LINES\n' * 100]:
  153. editwin.write = orig_write = Mock(return_value=SENTINEL_VALUE)
  154. squeezer = self.make_squeezer_instance(editwin)
  155. squeezer.auto_squeeze_min_lines = 50
  156. self.assertEqual(squeezer.editwin.write(text, "stdout"), None)
  157. self.assertEqual(orig_write.call_count, 0)
  158. self.assertEqual(len(squeezer.expandingbuttons), 1)
  159. def test_auto_squeeze(self):
  160. """Test that the auto-squeezing creates an ExpandingButton properly."""
  161. editwin = self.make_mock_editor_window(with_text_widget=True)
  162. text_widget = editwin.text
  163. squeezer = self.make_squeezer_instance(editwin)
  164. squeezer.auto_squeeze_min_lines = 5
  165. squeezer.count_lines = Mock(return_value=6)
  166. editwin.write('TEXT\n'*6, "stdout")
  167. self.assertEqual(text_widget.get('1.0', 'end'), '\n')
  168. self.assertEqual(len(squeezer.expandingbuttons), 1)
  169. def test_squeeze_current_text_event(self):
  170. """Test the squeeze_current_text event."""
  171. # Squeezing text should work for both stdout and stderr.
  172. for tag_name in ["stdout", "stderr"]:
  173. editwin = self.make_mock_editor_window(with_text_widget=True)
  174. text_widget = editwin.text
  175. squeezer = self.make_squeezer_instance(editwin)
  176. squeezer.count_lines = Mock(return_value=6)
  177. # Prepare some text in the Text widget.
  178. text_widget.insert("1.0", "SOME\nTEXT\n", tag_name)
  179. text_widget.mark_set("insert", "1.0")
  180. self.assertEqual(text_widget.get('1.0', 'end'), 'SOME\nTEXT\n\n')
  181. self.assertEqual(len(squeezer.expandingbuttons), 0)
  182. # Test squeezing the current text.
  183. retval = squeezer.squeeze_current_text_event(event=Mock())
  184. self.assertEqual(retval, "break")
  185. self.assertEqual(text_widget.get('1.0', 'end'), '\n\n')
  186. self.assertEqual(len(squeezer.expandingbuttons), 1)
  187. self.assertEqual(squeezer.expandingbuttons[0].s, 'SOME\nTEXT')
  188. # Test that expanding the squeezed text works and afterwards
  189. # the Text widget contains the original text.
  190. squeezer.expandingbuttons[0].expand(event=Mock())
  191. self.assertEqual(text_widget.get('1.0', 'end'), 'SOME\nTEXT\n\n')
  192. self.assertEqual(len(squeezer.expandingbuttons), 0)
  193. def test_squeeze_current_text_event_no_allowed_tags(self):
  194. """Test that the event doesn't squeeze text without a relevant tag."""
  195. editwin = self.make_mock_editor_window(with_text_widget=True)
  196. text_widget = editwin.text
  197. squeezer = self.make_squeezer_instance(editwin)
  198. squeezer.count_lines = Mock(return_value=6)
  199. # Prepare some text in the Text widget.
  200. text_widget.insert("1.0", "SOME\nTEXT\n", "TAG")
  201. text_widget.mark_set("insert", "1.0")
  202. self.assertEqual(text_widget.get('1.0', 'end'), 'SOME\nTEXT\n\n')
  203. self.assertEqual(len(squeezer.expandingbuttons), 0)
  204. # Test squeezing the current text.
  205. retval = squeezer.squeeze_current_text_event(event=Mock())
  206. self.assertEqual(retval, "break")
  207. self.assertEqual(text_widget.get('1.0', 'end'), 'SOME\nTEXT\n\n')
  208. self.assertEqual(len(squeezer.expandingbuttons), 0)
  209. def test_squeeze_text_before_existing_squeezed_text(self):
  210. """Test squeezing text before existing squeezed text."""
  211. editwin = self.make_mock_editor_window(with_text_widget=True)
  212. text_widget = editwin.text
  213. squeezer = self.make_squeezer_instance(editwin)
  214. squeezer.count_lines = Mock(return_value=6)
  215. # Prepare some text in the Text widget and squeeze it.
  216. text_widget.insert("1.0", "SOME\nTEXT\n", "stdout")
  217. text_widget.mark_set("insert", "1.0")
  218. squeezer.squeeze_current_text_event(event=Mock())
  219. self.assertEqual(len(squeezer.expandingbuttons), 1)
  220. # Test squeezing the current text.
  221. text_widget.insert("1.0", "MORE\nSTUFF\n", "stdout")
  222. text_widget.mark_set("insert", "1.0")
  223. retval = squeezer.squeeze_current_text_event(event=Mock())
  224. self.assertEqual(retval, "break")
  225. self.assertEqual(text_widget.get('1.0', 'end'), '\n\n\n')
  226. self.assertEqual(len(squeezer.expandingbuttons), 2)
  227. self.assertTrue(text_widget.compare(
  228. squeezer.expandingbuttons[0],
  229. '<',
  230. squeezer.expandingbuttons[1],
  231. ))
  232. def test_reload(self):
  233. """Test the reload() class-method."""
  234. editwin = self.make_mock_editor_window(with_text_widget=True)
  235. squeezer = self.make_squeezer_instance(editwin)
  236. orig_auto_squeeze_min_lines = squeezer.auto_squeeze_min_lines
  237. # Increase auto-squeeze-min-lines.
  238. new_auto_squeeze_min_lines = orig_auto_squeeze_min_lines + 10
  239. self.set_idleconf_option_with_cleanup(
  240. 'main', 'PyShell', 'auto-squeeze-min-lines',
  241. str(new_auto_squeeze_min_lines))
  242. Squeezer.reload()
  243. self.assertEqual(squeezer.auto_squeeze_min_lines,
  244. new_auto_squeeze_min_lines)
  245. def test_reload_no_squeezer_instances(self):
  246. """Test that Squeezer.reload() runs without any instances existing."""
  247. Squeezer.reload()
  248. class ExpandingButtonTest(unittest.TestCase):
  249. """Tests for the ExpandingButton class."""
  250. # In these tests the squeezer instance is a mock, but actual tkinter
  251. # Text and Button instances are created.
  252. def make_mock_squeezer(self):
  253. """Helper for tests: Create a mock Squeezer object."""
  254. root = get_test_tk_root(self)
  255. squeezer = Mock()
  256. squeezer.editwin.text = Text(root)
  257. # Set default values for the configuration settings.
  258. squeezer.auto_squeeze_min_lines = 50
  259. return squeezer
  260. @patch('idlelib.squeezer.Hovertip', autospec=Hovertip)
  261. def test_init(self, MockHovertip):
  262. """Test the simplest creation of an ExpandingButton."""
  263. squeezer = self.make_mock_squeezer()
  264. text_widget = squeezer.editwin.text
  265. expandingbutton = ExpandingButton('TEXT', 'TAGS', 50, squeezer)
  266. self.assertEqual(expandingbutton.s, 'TEXT')
  267. # Check that the underlying tkinter.Button is properly configured.
  268. self.assertEqual(expandingbutton.master, text_widget)
  269. self.assertTrue('50 lines' in expandingbutton.cget('text'))
  270. # Check that the text widget still contains no text.
  271. self.assertEqual(text_widget.get('1.0', 'end'), '\n')
  272. # Check that the mouse events are bound.
  273. self.assertIn('<Double-Button-1>', expandingbutton.bind())
  274. right_button_code = '<Button-%s>' % ('2' if macosx.isAquaTk() else '3')
  275. self.assertIn(right_button_code, expandingbutton.bind())
  276. # Check that ToolTip was called once, with appropriate values.
  277. self.assertEqual(MockHovertip.call_count, 1)
  278. MockHovertip.assert_called_with(expandingbutton, ANY, hover_delay=ANY)
  279. # Check that 'right-click' appears in the tooltip text.
  280. tooltip_text = MockHovertip.call_args[0][1]
  281. self.assertIn('right-click', tooltip_text.lower())
  282. def test_expand(self):
  283. """Test the expand event."""
  284. squeezer = self.make_mock_squeezer()
  285. expandingbutton = ExpandingButton('TEXT', 'TAGS', 50, squeezer)
  286. # Insert the button into the text widget
  287. # (this is normally done by the Squeezer class).
  288. text_widget = expandingbutton.text
  289. text_widget.window_create("1.0", window=expandingbutton)
  290. # Set base_text to the text widget, so that changes are actually
  291. # made to it (by ExpandingButton) and we can inspect these
  292. # changes afterwards.
  293. expandingbutton.base_text = expandingbutton.text
  294. # trigger the expand event
  295. retval = expandingbutton.expand(event=Mock())
  296. self.assertEqual(retval, None)
  297. # Check that the text was inserted into the text widget.
  298. self.assertEqual(text_widget.get('1.0', 'end'), 'TEXT\n')
  299. # Check that the 'TAGS' tag was set on the inserted text.
  300. text_end_index = text_widget.index('end-1c')
  301. self.assertEqual(text_widget.get('1.0', text_end_index), 'TEXT')
  302. self.assertEqual(text_widget.tag_nextrange('TAGS', '1.0'),
  303. ('1.0', text_end_index))
  304. # Check that the button removed itself from squeezer.expandingbuttons.
  305. self.assertEqual(squeezer.expandingbuttons.remove.call_count, 1)
  306. squeezer.expandingbuttons.remove.assert_called_with(expandingbutton)
  307. def test_expand_dangerous_oupput(self):
  308. """Test that expanding very long output asks user for confirmation."""
  309. squeezer = self.make_mock_squeezer()
  310. text = 'a' * 10**5
  311. expandingbutton = ExpandingButton(text, 'TAGS', 50, squeezer)
  312. expandingbutton.set_is_dangerous()
  313. self.assertTrue(expandingbutton.is_dangerous)
  314. # Insert the button into the text widget
  315. # (this is normally done by the Squeezer class).
  316. text_widget = expandingbutton.text
  317. text_widget.window_create("1.0", window=expandingbutton)
  318. # Set base_text to the text widget, so that changes are actually
  319. # made to it (by ExpandingButton) and we can inspect these
  320. # changes afterwards.
  321. expandingbutton.base_text = expandingbutton.text
  322. # Patch the message box module to always return False.
  323. with patch('idlelib.squeezer.tkMessageBox') as mock_msgbox:
  324. mock_msgbox.askokcancel.return_value = False
  325. mock_msgbox.askyesno.return_value = False
  326. # Trigger the expand event.
  327. retval = expandingbutton.expand(event=Mock())
  328. # Check that the event chain was broken and no text was inserted.
  329. self.assertEqual(retval, 'break')
  330. self.assertEqual(expandingbutton.text.get('1.0', 'end-1c'), '')
  331. # Patch the message box module to always return True.
  332. with patch('idlelib.squeezer.tkMessageBox') as mock_msgbox:
  333. mock_msgbox.askokcancel.return_value = True
  334. mock_msgbox.askyesno.return_value = True
  335. # Trigger the expand event.
  336. retval = expandingbutton.expand(event=Mock())
  337. # Check that the event chain wasn't broken and the text was inserted.
  338. self.assertEqual(retval, None)
  339. self.assertEqual(expandingbutton.text.get('1.0', 'end-1c'), text)
  340. def test_copy(self):
  341. """Test the copy event."""
  342. # Testing with the actual clipboard proved problematic, so this
  343. # test replaces the clipboard manipulation functions with mocks
  344. # and checks that they are called appropriately.
  345. squeezer = self.make_mock_squeezer()
  346. expandingbutton = ExpandingButton('TEXT', 'TAGS', 50, squeezer)
  347. expandingbutton.clipboard_clear = Mock()
  348. expandingbutton.clipboard_append = Mock()
  349. # Trigger the copy event.
  350. retval = expandingbutton.copy(event=Mock())
  351. self.assertEqual(retval, None)
  352. # Vheck that the expanding button called clipboard_clear() and
  353. # clipboard_append('TEXT') once each.
  354. self.assertEqual(expandingbutton.clipboard_clear.call_count, 1)
  355. self.assertEqual(expandingbutton.clipboard_append.call_count, 1)
  356. expandingbutton.clipboard_append.assert_called_with('TEXT')
  357. def test_view(self):
  358. """Test the view event."""
  359. squeezer = self.make_mock_squeezer()
  360. expandingbutton = ExpandingButton('TEXT', 'TAGS', 50, squeezer)
  361. expandingbutton.selection_own = Mock()
  362. with patch('idlelib.squeezer.view_text', autospec=view_text)\
  363. as mock_view_text:
  364. # Trigger the view event.
  365. expandingbutton.view(event=Mock())
  366. # Check that the expanding button called view_text.
  367. self.assertEqual(mock_view_text.call_count, 1)
  368. # Check that the proper text was passed.
  369. self.assertEqual(mock_view_text.call_args[0][2], 'TEXT')
  370. def test_rmenu(self):
  371. """Test the context menu."""
  372. squeezer = self.make_mock_squeezer()
  373. expandingbutton = ExpandingButton('TEXT', 'TAGS', 50, squeezer)
  374. with patch('tkinter.Menu') as mock_Menu:
  375. mock_menu = Mock()
  376. mock_Menu.return_value = mock_menu
  377. mock_event = Mock()
  378. mock_event.x = 10
  379. mock_event.y = 10
  380. expandingbutton.context_menu_event(event=mock_event)
  381. self.assertEqual(mock_menu.add_command.call_count,
  382. len(expandingbutton.rmenu_specs))
  383. for label, *data in expandingbutton.rmenu_specs:
  384. mock_menu.add_command.assert_any_call(label=label, command=ANY)
  385. if __name__ == '__main__':
  386. unittest.main(verbosity=2)