Debian Codegraph @

Lib/idlelib/idle_test/test_calltip.py

raw
1 "Test calltip, coverage 76%"
2
3 from idlelib import calltip
4 import unittest
5 from unittest.mock import Mock
6 import textwrap
7 import types
8 import re
9 from idlelib.idle_test.mock_tk import Text
10 from test.support import MISSING_C_DOCSTRINGS
11
12
13 # Test Class TC is used in multiple get_argspec test methods
14 class TC:
15 'doc'
16 tip = "(ai=None, *b)"
17 def __init__(self, ai=None, *b): 'doc'
18 __init__.tip = "(self, ai=None, *b)"
19 def t1(self): 'doc'
20 t1.tip = "(self)"
21 def t2(self, ai, b=None): 'doc'
22 t2.tip = "(self, ai, b=None)"
23 def t3(self, ai, *args): 'doc'
24 t3.tip = "(self, ai, *args)"
25 def t4(self, *args): 'doc'
26 t4.tip = "(self, *args)"
27 def t5(self, ai, b=None, *args, **kw): 'doc'
28 t5.tip = "(self, ai, b=None, *args, **kw)"
29 def t6(no, self): 'doc'
30 t6.tip = "(no, self)"
31 def __call__(self, ci): 'doc'
32 __call__.tip = "(self, ci)"
33 def nd(self): pass # No doc.
34 # attaching .tip to wrapped methods does not work
35 @classmethod
36 def cm(cls, a): 'doc'
37 @staticmethod
38 def sm(b): 'doc'
39
40
41 tc = TC()
42 default_tip = calltip._default_callable_argspec
43 get_spec = calltip.get_argspec
44
45
46 class Get_argspecTest(unittest.TestCase):
47 # The get_spec function must return a string, even if blank.
48 # Test a variety of objects to be sure that none cause it to raise
49 # (quite aside from getting as correct an answer as possible).
50 # The tests of builtins may break if inspect or the docstrings change,
51 # but a red buildbot is better than a user crash (as has happened).
52 # For a simple mismatch, change the expected output to the actual.
53
54 @unittest.skipIf(MISSING_C_DOCSTRINGS,
55 "Signature information for builtins requires docstrings")
56 def test_builtins(self):
57
58 def tiptest(obj, out):
59 self.assertEqual(get_spec(obj), out)
60
61 # Python class that inherits builtin methods
62 class List(list): "List() doc"
63
64 # Simulate builtin with no docstring for default tip test
65 class SB: __call__ = None
66
67 if List.__doc__ is not None:
68 tiptest(List,
69 f'(iterable=(), /)'
70 f'\n{List.__doc__}')
71 tiptest(list.__new__,
72 '(*args, **kwargs)\n'
73 'Create and return a new object. '
74 'See help(type) for accurate signature.')
75 tiptest(list.__init__,
76 '(self, /, *args, **kwargs)\n'
77 'Initialize self. See help(type(self)) for accurate signature.')
78 append_doc = "\nAppend object to the end of the list."
79 tiptest(list.append, '(self, object, /)' + append_doc)
80 tiptest(List.append, '(self, object, /)' + append_doc)
81 tiptest([].append, '(object, /)' + append_doc)
82 # The use of 'object' above matches the signature text.
83
84 tiptest(types.MethodType,
85 '(function, instance, /)\n'
86 'Create a bound instance method object.')
87 tiptest(SB(), default_tip)
88
89 p = re.compile('')
90 tiptest(re.sub, '''\
91 (pattern, repl, string, count=0, flags=0)
92 Return the string obtained by replacing the leftmost
93 non-overlapping occurrences of the pattern in string by the
94 replacement repl. repl can be either a string or a callable;
95 if a string, backslash escapes in it are processed. If it is
96 a callable, it's passed the Match object and must return''')
97 tiptest(p.sub, '''\
98 (repl, string, count=0)
99 Return the string obtained by replacing the leftmost \
100 non-overlapping occurrences o...''')
101
102 def test_signature_wrap(self):
103 if textwrap.TextWrapper.__doc__ is not None:
104 self.assertEqual(get_spec(textwrap.TextWrapper), '''\
105 (width=70, initial_indent='', subsequent_indent='', expand_tabs=True,
106 replace_whitespace=True, fix_sentence_endings=False, break_long_words=True,
107 drop_whitespace=True, break_on_hyphens=True, tabsize=8, *, max_lines=None,
108 placeholder=' [...]')
109 Object for wrapping/filling text. The public interface consists of
110 the wrap() and fill() methods; the other methods are just there for
111 subclasses to override in order to tweak the default behaviour.
112 If you want to completely replace the main wrapping algorithm,
113 you\'ll probably have to override _wrap_chunks().''')
114
115 def test_properly_formatted(self):
116
117 def foo(s='a'*100):
118 pass
119
120 def bar(s='a'*100):
121 """Hello Guido"""
122 pass
123
124 def baz(s='a'*100, z='b'*100):
125 pass
126
127 indent = calltip._INDENT
128
129 sfoo = "(s='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"\
130 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + indent + "aaaaaaaaa"\
131 "aaaaaaaaaa')"
132 sbar = "(s='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"\
133 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + indent + "aaaaaaaaa"\
134 "aaaaaaaaaa')\nHello Guido"
135 sbaz = "(s='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"\
136 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + indent + "aaaaaaaaa"\
137 "aaaaaaaaaa', z='bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"\
138 "bbbbbbbbbbbbbbbbb\n" + indent + "bbbbbbbbbbbbbbbbbbbbbb"\
139 "bbbbbbbbbbbbbbbbbbbbbb')"
140
141 for func,doc in [(foo, sfoo), (bar, sbar), (baz, sbaz)]:
142 with self.subTest(func=func, doc=doc):
143 self.assertEqual(get_spec(func), doc)
144
145 def test_docline_truncation(self):
146 def f(): pass
147 f.__doc__ = 'a'*300
148 self.assertEqual(get_spec(f), f"()\n{'a'*(calltip._MAX_COLS-3) + '...'}")
149
150 @unittest.skipIf(MISSING_C_DOCSTRINGS,
151 "Signature information for builtins requires docstrings")
152 def test_multiline_docstring(self):
153 # Test fewer lines than max.
154 self.assertEqual(get_spec(range),
155 "range(stop) -> range object\n"
156 "range(start, stop[, step]) -> range object")
157
158 # Test max lines
159 self.assertEqual(get_spec(bytes), '''\
160 bytes(iterable_of_ints) -> bytes
161 bytes(string, encoding[, errors]) -> bytes
162 bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
163 bytes(int) -> bytes object of size given by the parameter initialized with null bytes
164 bytes() -> empty bytes object''')
165
166 def test_multiline_docstring_2(self):
167 # Test more than max lines
168 def f(): pass
169 f.__doc__ = 'a\n' * 15
170 self.assertEqual(get_spec(f), '()' + '\na' * calltip._MAX_LINES)
171
172 def test_functions(self):
173 def t1(): 'doc'
174 t1.tip = "()"
175 def t2(a, b=None): 'doc'
176 t2.tip = "(a, b=None)"
177 def t3(a, *args): 'doc'
178 t3.tip = "(a, *args)"
179 def t4(*args): 'doc'
180 t4.tip = "(*args)"
181 def t5(a, b=None, *args, **kw): 'doc'
182 t5.tip = "(a, b=None, *args, **kw)"
183
184 doc = '\ndoc' if t1.__doc__ is not None else ''
185 for func in (t1, t2, t3, t4, t5, TC):
186 with self.subTest(func=func):
187 self.assertEqual(get_spec(func), func.tip + doc)
188
189 def test_methods(self):
190 doc = '\ndoc' if TC.__doc__ is not None else ''
191 for meth in (TC.t1, TC.t2, TC.t3, TC.t4, TC.t5, TC.t6, TC.__call__):
192 with self.subTest(meth=meth):
193 self.assertEqual(get_spec(meth), meth.tip + doc)
194 self.assertEqual(get_spec(TC.cm), "(a)" + doc)
195 self.assertEqual(get_spec(TC.sm), "(b)" + doc)
196
197 def test_bound_methods(self):
198 # test that first parameter is correctly removed from argspec
199 doc = '\ndoc' if TC.__doc__ is not None else ''
200 for meth, mtip in ((tc.t1, "()"), (tc.t4, "(*args)"),
201 (tc.t6, "(self)"), (tc.__call__, '(ci)'),
202 (tc, '(ci)'), (TC.cm, "(a)"),):
203 with self.subTest(meth=meth, mtip=mtip):
204 self.assertEqual(get_spec(meth), mtip + doc)
205
206 def test_starred_parameter(self):
207 # test that starred first parameter is *not* removed from argspec
208 class C:
209 def m1(*args): pass
210 c = C()
211 for meth, mtip in ((C.m1, '(*args)'), (c.m1, "(*args)"),):
212 with self.subTest(meth=meth, mtip=mtip):
213 self.assertEqual(get_spec(meth), mtip)
214
215 def test_invalid_method_get_spec(self):
216 class C:
217 def m2(**kwargs): pass
218 class Test:
219 def __call__(*, a): pass
220
221 mtip = calltip._invalid_method
222 self.assertEqual(get_spec(C().m2), mtip)
223 self.assertEqual(get_spec(Test()), mtip)
224
225 def test_non_ascii_name(self):
226 # test that re works to delete a first parameter name that
227 # includes non-ascii chars, such as various forms of A.
228 uni = "(A\u0391\u0410\u05d0\u0627\u0905\u1e00\u3042, a)"
229 assert calltip._first_param.sub('', uni) == '(a)'
230
231 def test_no_docstring(self):
232 for meth, mtip in ((TC.nd, "(self)"), (tc.nd, "()")):
233 with self.subTest(meth=meth, mtip=mtip):
234 self.assertEqual(get_spec(meth), mtip)
235
236 def test_buggy_getattr_class(self):
237 class NoCall:
238 def __getattr__(self, name): # Not invoked for class attribute.
239 raise IndexError # Bug.
240 class CallA(NoCall):
241 def __call__(self, ci): # Bug does not matter.
242 pass
243 class CallB(NoCall):
244 def __call__(oui, a, b, c): # Non-standard 'self'.
245 pass
246
247 for meth, mtip in ((NoCall, default_tip), (CallA, default_tip),
248 (NoCall(), ''), (CallA(), '(ci)'),
249 (CallB(), '(a, b, c)')):
250 with self.subTest(meth=meth, mtip=mtip):
251 self.assertEqual(get_spec(meth), mtip)
252
253 def test_metaclass_class(self): # Failure case for issue 38689.
254 class Type(type): # Type() requires 3 type args, returns class.
255 __class__ = property({}.__getitem__, {}.__setitem__)
256 class Object(metaclass=Type):
257 __slots__ = '__class__'
258 for meth, mtip in ((Type, get_spec(type)), (Object, default_tip),
259 (Object(), '')):
260 with self.subTest(meth=meth, mtip=mtip):
261 self.assertEqual(get_spec(meth), mtip)
262
263 def test_non_callables(self):
264 for obj in (0, 0.0, '0', b'0', [], {}):
265 with self.subTest(obj=obj):
266 self.assertEqual(get_spec(obj), '')
267
268
269 class Get_entityTest(unittest.TestCase):
270 def test_bad_entity(self):
271 self.assertIsNone(calltip.get_entity('1/0'))
272 def test_good_entity(self):
273 self.assertIs(calltip.get_entity('int'), int)
274
275
276 # Test the 9 Calltip methods.
277 # open_calltip is about half the code; the others are fairly trivial.
278 # The default mocks are what are needed for open_calltip.
279
280 class mock_Shell:
281 "Return mock sufficient to pass to hyperparser."
282 def __init__(self, text):
283 text.tag_prevrange = Mock(return_value=None)
284 self.text = text
285 self.prompt_last_line = ">>> "
286 self.indentwidth = 4
287 self.tabwidth = 8
288
289
290 class mock_TipWindow:
291 def __init__(self):
292 pass
293
294 def showtip(self, text, parenleft, parenright):
295 self.args = parenleft, parenright
296 self.parenline, self.parencol = map(int, parenleft.split('.'))
297
298
299 class WrappedCalltip(calltip.Calltip):
300 def _make_tk_calltip_window(self):
301 return mock_TipWindow()
302
303 def remove_calltip_window(self, event=None):
304 if self.active_calltip: # Setup to None.
305 self.active_calltip = None
306 self.tips_removed += 1 # Setup to 0.
307
308 def fetch_tip(self, expression):
309 return 'tip'
310
311
312 class CalltipTest(unittest.TestCase):
313
314 @classmethod
315 def setUpClass(cls):
316 cls.text = Text()
317 cls.ct = WrappedCalltip(mock_Shell(cls.text))
318
319 def setUp(self):
320 self.text.delete('1.0', 'end') # Insert and call
321 self.ct.active_calltip = None
322 # Test .active_calltip, +args
323 self.ct.tips_removed = 0
324
325 def open_close(self, testfunc):
326 # Open-close template with testfunc called in between.
327 opentip = self.ct.open_calltip
328 self.text.insert(1.0, 'f(')
329 opentip(False)
330 self.tip = self.ct.active_calltip
331 testfunc(self) ###
332 self.text.insert('insert', ')')
333 opentip(False)
334 self.assertIsNone(self.ct.active_calltip, None)
335
336 def test_open_close(self):
337 def args(self):
338 self.assertEqual(self.tip.args, ('1.1', '1.end'))
339 self.open_close(args)
340
341 def test_repeated_force(self):
342 def force(self):
343 for char in 'abc':
344 self.text.insert('insert', 'a')
345 self.ct.open_calltip(True)
346 self.ct.open_calltip(True)
347 self.assertIs(self.ct.active_calltip, self.tip)
348 self.open_close(force)
349
350 def test_repeated_parens(self):
351 def parens(self):
352 for context in "a", "'":
353 with self.subTest(context=context):
354 self.text.insert('insert', context)
355 for char in '(()())':
356 self.text.insert('insert', char)
357 self.assertIs(self.ct.active_calltip, self.tip)
358 self.text.insert('insert', "'")
359 self.open_close(parens)
360
361 def test_comment_parens(self):
362 def comment(self):
363 self.text.insert('insert', "# ")
364 for char in '(()())':
365 self.text.insert('insert', char)
366 self.assertIs(self.ct.active_calltip, self.tip)
367 self.text.insert('insert', "\n")
368 self.open_close(comment)
369
370
371 if __name__ == '__main__':
372 unittest.main(verbosity=2)