• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1"Test autocomplete, coverage 93%."
2
3import unittest
4from unittest.mock import Mock, patch
5from test.support import requires
6from tkinter import Tk, Text
7import os
8import __main__
9
10import idlelib.autocomplete as ac
11import idlelib.autocomplete_w as acw
12from idlelib.idle_test.mock_idle import Func
13from idlelib.idle_test.mock_tk import Event
14
15
16class DummyEditwin:
17    def __init__(self, root, text):
18        self.root = root
19        self.text = text
20        self.indentwidth = 8
21        self.tabwidth = 8
22        self.prompt_last_line = '>>>'  # Currently not used by autocomplete.
23
24
25class AutoCompleteTest(unittest.TestCase):
26
27    @classmethod
28    def setUpClass(cls):
29        requires('gui')
30        cls.root = Tk()
31        cls.root.withdraw()
32        cls.text = Text(cls.root)
33        cls.editor = DummyEditwin(cls.root, cls.text)
34
35    @classmethod
36    def tearDownClass(cls):
37        del cls.editor, cls.text
38        cls.root.update_idletasks()
39        cls.root.destroy()
40        del cls.root
41
42    def setUp(self):
43        self.text.delete('1.0', 'end')
44        self.autocomplete = ac.AutoComplete(self.editor)
45
46    def test_init(self):
47        self.assertEqual(self.autocomplete.editwin, self.editor)
48        self.assertEqual(self.autocomplete.text, self.text)
49
50    def test_make_autocomplete_window(self):
51        testwin = self.autocomplete._make_autocomplete_window()
52        self.assertIsInstance(testwin, acw.AutoCompleteWindow)
53
54    def test_remove_autocomplete_window(self):
55        acp = self.autocomplete
56        acp.autocompletewindow = m = Mock()
57        acp._remove_autocomplete_window()
58        m.hide_window.assert_called_once()
59        self.assertIsNone(acp.autocompletewindow)
60
61    def test_force_open_completions_event(self):
62        # Call _open_completions and break.
63        acp = self.autocomplete
64        open_c = Func()
65        acp.open_completions = open_c
66        self.assertEqual(acp.force_open_completions_event('event'), 'break')
67        self.assertEqual(open_c.args[0], ac.FORCE)
68
69    def test_autocomplete_event(self):
70        Equal = self.assertEqual
71        acp = self.autocomplete
72
73        # Result of autocomplete event: If modified tab, None.
74        ev = Event(mc_state=True)
75        self.assertIsNone(acp.autocomplete_event(ev))
76        del ev.mc_state
77
78        # If tab after whitespace, None.
79        self.text.insert('1.0', '        """Docstring.\n    ')
80        self.assertIsNone(acp.autocomplete_event(ev))
81        self.text.delete('1.0', 'end')
82
83        # If active autocomplete window, complete() and 'break'.
84        self.text.insert('1.0', 're.')
85        acp.autocompletewindow = mock = Mock()
86        mock.is_active = Mock(return_value=True)
87        Equal(acp.autocomplete_event(ev), 'break')
88        mock.complete.assert_called_once()
89        acp.autocompletewindow = None
90
91        # If no active autocomplete window, open_completions(), None/break.
92        open_c = Func(result=False)
93        acp.open_completions = open_c
94        Equal(acp.autocomplete_event(ev), None)
95        Equal(open_c.args[0], ac.TAB)
96        open_c.result = True
97        Equal(acp.autocomplete_event(ev), 'break')
98        Equal(open_c.args[0], ac.TAB)
99
100    def test_try_open_completions_event(self):
101        Equal = self.assertEqual
102        text = self.text
103        acp = self.autocomplete
104        trycompletions = acp.try_open_completions_event
105        after = Func(result='after1')
106        acp.text.after = after
107
108        # If no text or trigger, after not called.
109        trycompletions()
110        Equal(after.called, 0)
111        text.insert('1.0', 're')
112        trycompletions()
113        Equal(after.called, 0)
114
115        # Attribute needed, no existing callback.
116        text.insert('insert', ' re.')
117        acp._delayed_completion_id = None
118        trycompletions()
119        Equal(acp._delayed_completion_index, text.index('insert'))
120        Equal(after.args,
121              (acp.popupwait, acp._delayed_open_completions, ac.TRY_A))
122        cb1 = acp._delayed_completion_id
123        Equal(cb1, 'after1')
124
125        # File needed, existing callback cancelled.
126        text.insert('insert', ' "./Lib/')
127        after.result = 'after2'
128        cancel = Func()
129        acp.text.after_cancel = cancel
130        trycompletions()
131        Equal(acp._delayed_completion_index, text.index('insert'))
132        Equal(cancel.args, (cb1,))
133        Equal(after.args,
134              (acp.popupwait, acp._delayed_open_completions, ac.TRY_F))
135        Equal(acp._delayed_completion_id, 'after2')
136
137    def test_delayed_open_completions(self):
138        Equal = self.assertEqual
139        acp = self.autocomplete
140        open_c = Func()
141        acp.open_completions = open_c
142        self.text.insert('1.0', '"dict.')
143
144        # Set autocomplete._delayed_completion_id to None.
145        # Text index changed, don't call open_completions.
146        acp._delayed_completion_id = 'after'
147        acp._delayed_completion_index = self.text.index('insert+1c')
148        acp._delayed_open_completions('dummy')
149        self.assertIsNone(acp._delayed_completion_id)
150        Equal(open_c.called, 0)
151
152        # Text index unchanged, call open_completions.
153        acp._delayed_completion_index = self.text.index('insert')
154        acp._delayed_open_completions((1, 2, 3, ac.FILES))
155        self.assertEqual(open_c.args[0], (1, 2, 3, ac.FILES))
156
157    def test_oc_cancel_comment(self):
158        none = self.assertIsNone
159        acp = self.autocomplete
160
161        # Comment is in neither code or string.
162        acp._delayed_completion_id = 'after'
163        after = Func(result='after')
164        acp.text.after_cancel = after
165        self.text.insert(1.0, '# comment')
166        none(acp.open_completions(ac.TAB))  # From 'else' after 'elif'.
167        none(acp._delayed_completion_id)
168
169    def test_oc_no_list(self):
170        acp = self.autocomplete
171        fetch = Func(result=([],[]))
172        acp.fetch_completions = fetch
173        self.text.insert('1.0', 'object')
174        self.assertIsNone(acp.open_completions(ac.TAB))
175        self.text.insert('insert', '.')
176        self.assertIsNone(acp.open_completions(ac.TAB))
177        self.assertEqual(fetch.called, 2)
178
179
180    def test_open_completions_none(self):
181        # Test other two None returns.
182        none = self.assertIsNone
183        acp = self.autocomplete
184
185        # No object for attributes or need call not allowed.
186        self.text.insert(1.0, '.')
187        none(acp.open_completions(ac.TAB))
188        self.text.insert('insert', ' int().')
189        none(acp.open_completions(ac.TAB))
190
191        # Blank or quote trigger 'if complete ...'.
192        self.text.delete(1.0, 'end')
193        self.assertFalse(acp.open_completions(ac.TAB))
194        self.text.insert('1.0', '"')
195        self.assertFalse(acp.open_completions(ac.TAB))
196        self.text.delete('1.0', 'end')
197
198    class dummy_acw:
199        __init__ = Func()
200        show_window = Func(result=False)
201        hide_window = Func()
202
203    def test_open_completions(self):
204        # Test completions of files and attributes.
205        acp = self.autocomplete
206        fetch = Func(result=(['tem'],['tem', '_tem']))
207        acp.fetch_completions = fetch
208        def make_acw(): return self.dummy_acw()
209        acp._make_autocomplete_window = make_acw
210
211        self.text.insert('1.0', 'int.')
212        acp.open_completions(ac.TAB)
213        self.assertIsInstance(acp.autocompletewindow, self.dummy_acw)
214        self.text.delete('1.0', 'end')
215
216        # Test files.
217        self.text.insert('1.0', '"t')
218        self.assertTrue(acp.open_completions(ac.TAB))
219        self.text.delete('1.0', 'end')
220
221    def test_completion_kwds(self):
222        self.assertIn('and', ac.completion_kwds)
223        self.assertIn('case', ac.completion_kwds)
224        self.assertNotIn('None', ac.completion_kwds)
225
226    def test_fetch_completions(self):
227        # Test that fetch_completions returns 2 lists:
228        # For attribute completion, a large list containing all variables, and
229        # a small list containing non-private variables.
230        # For file completion, a large list containing all files in the path,
231        # and a small list containing files that do not start with '.'.
232        acp = self.autocomplete
233        small, large = acp.fetch_completions(
234                '', ac.ATTRS)
235        if hasattr(__main__, '__file__') and __main__.__file__ != ac.__file__:
236            self.assertNotIn('AutoComplete', small)  # See issue 36405.
237
238        # Test attributes
239        s, b = acp.fetch_completions('', ac.ATTRS)
240        self.assertLess(len(small), len(large))
241        self.assertTrue(all(filter(lambda x: x.startswith('_'), s)))
242        self.assertTrue(any(filter(lambda x: x.startswith('_'), b)))
243
244        # Test smalll should respect to __all__.
245        with patch.dict('__main__.__dict__', {'__all__': ['a', 'b']}):
246            s, b = acp.fetch_completions('', ac.ATTRS)
247            self.assertEqual(s, ['a', 'b'])
248            self.assertIn('__name__', b)  # From __main__.__dict__.
249            self.assertIn('sum', b)       # From __main__.__builtins__.__dict__.
250            self.assertIn('nonlocal', b)  # From keyword.kwlist.
251            pos = b.index('False')        # Test False not included twice.
252            self.assertNotEqual(b[pos+1], 'False')
253
254        # Test attributes with name entity.
255        mock = Mock()
256        mock._private = Mock()
257        with patch.dict('__main__.__dict__', {'foo': mock}):
258            s, b = acp.fetch_completions('foo', ac.ATTRS)
259            self.assertNotIn('_private', s)
260            self.assertIn('_private', b)
261            self.assertEqual(s, [i for i in sorted(dir(mock)) if i[:1] != '_'])
262            self.assertEqual(b, sorted(dir(mock)))
263
264        # Test files
265        def _listdir(path):
266            # This will be patch and used in fetch_completions.
267            if path == '.':
268                return ['foo', 'bar', '.hidden']
269            return ['monty', 'python', '.hidden']
270
271        with patch.object(os, 'listdir', _listdir):
272            s, b = acp.fetch_completions('', ac.FILES)
273            self.assertEqual(s, ['bar', 'foo'])
274            self.assertEqual(b, ['.hidden', 'bar', 'foo'])
275
276            s, b = acp.fetch_completions('~', ac.FILES)
277            self.assertEqual(s, ['monty', 'python'])
278            self.assertEqual(b, ['.hidden', 'monty', 'python'])
279
280    def test_get_entity(self):
281        # Test that a name is in the namespace of sys.modules and
282        # __main__.__dict__.
283        acp = self.autocomplete
284        Equal = self.assertEqual
285
286        Equal(acp.get_entity('int'), int)
287
288        # Test name from sys.modules.
289        mock = Mock()
290        with patch.dict('sys.modules', {'tempfile': mock}):
291            Equal(acp.get_entity('tempfile'), mock)
292
293        # Test name from __main__.__dict__.
294        di = {'foo': 10, 'bar': 20}
295        with patch.dict('__main__.__dict__', {'d': di}):
296            Equal(acp.get_entity('d'), di)
297
298        # Test name not in namespace.
299        with patch.dict('__main__.__dict__', {}):
300            with self.assertRaises(NameError):
301                acp.get_entity('not_exist')
302
303
304if __name__ == '__main__':
305    unittest.main(verbosity=2)
306