test_squeezer.py 19 KB

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