Debian Codegraph @

Lib/idlelib/idle_test/test_squeezer.py

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