Debian Codegraph @

lib-python/3/idlelib/idle_test/test_calltip.py

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