ยปCore Development>Code coverage>Lib/idlelib/CallTips.py

Python code coverage for Lib/idlelib/CallTips.py

#countcontent
1n/a"""CallTips.py - An IDLE Extension to Jog Your Memory
2n/a
3n/aCall Tips are floating windows which display function, class, and method
4n/aparameter and docstring information when you type an opening parenthesis, and
5n/awhich disappear when you type a closing parenthesis.
6n/a
7n/a"""
8n/aimport re
9n/aimport sys
10n/aimport types
11n/aimport inspect
12n/a
13n/afrom idlelib import CallTipWindow
14n/afrom idlelib.HyperParser import HyperParser
15n/a
16n/aimport __main__
17n/a
18n/aclass CallTips:
19n/a
20n/a menudefs = [
21n/a ('edit', [
22n/a ("Show call tip", "<<force-open-calltip>>"),
23n/a ])
24n/a ]
25n/a
26n/a def __init__(self, editwin=None):
27n/a if editwin is None: # subprocess and test
28n/a self.editwin = None
29n/a else:
30n/a self.editwin = editwin
31n/a self.text = editwin.text
32n/a self.active_calltip = None
33n/a self._calltip_window = self._make_tk_calltip_window
34n/a
35n/a def close(self):
36n/a self._calltip_window = None
37n/a
38n/a def _make_tk_calltip_window(self):
39n/a # See __init__ for usage
40n/a return CallTipWindow.CallTip(self.text)
41n/a
42n/a def _remove_calltip_window(self, event=None):
43n/a if self.active_calltip:
44n/a self.active_calltip.hidetip()
45n/a self.active_calltip = None
46n/a
47n/a def force_open_calltip_event(self, event):
48n/a "The user selected the menu entry or hotkey, open the tip."
49n/a self.open_calltip(True)
50n/a
51n/a def try_open_calltip_event(self, event):
52n/a """Happens when it would be nice to open a CallTip, but not really
53n/a necessary, for example after an opening bracket, so function calls
54n/a won't be made.
55n/a """
56n/a self.open_calltip(False)
57n/a
58n/a def refresh_calltip_event(self, event):
59n/a if self.active_calltip and self.active_calltip.is_active():
60n/a self.open_calltip(False)
61n/a
62n/a def open_calltip(self, evalfuncs):
63n/a self._remove_calltip_window()
64n/a
65n/a hp = HyperParser(self.editwin, "insert")
66n/a sur_paren = hp.get_surrounding_brackets('(')
67n/a if not sur_paren:
68n/a return
69n/a hp.set_index(sur_paren[0])
70n/a expression = hp.get_expression()
71n/a if not expression:
72n/a return
73n/a if not evalfuncs and (expression.find('(') != -1):
74n/a return
75n/a argspec = self.fetch_tip(expression)
76n/a if not argspec:
77n/a return
78n/a self.active_calltip = self._calltip_window()
79n/a self.active_calltip.showtip(argspec, sur_paren[0], sur_paren[1])
80n/a
81n/a def fetch_tip(self, expression):
82n/a """Return the argument list and docstring of a function or class.
83n/a
84n/a If there is a Python subprocess, get the calltip there. Otherwise,
85n/a either this fetch_tip() is running in the subprocess or it was
86n/a called in an IDLE running without the subprocess.
87n/a
88n/a The subprocess environment is that of the most recently run script. If
89n/a two unrelated modules are being edited some calltips in the current
90n/a module may be inoperative if the module was not the last to run.
91n/a
92n/a To find methods, fetch_tip must be fed a fully qualified name.
93n/a
94n/a """
95n/a try:
96n/a rpcclt = self.editwin.flist.pyshell.interp.rpcclt
97n/a except AttributeError:
98n/a rpcclt = None
99n/a if rpcclt:
100n/a return rpcclt.remotecall("exec", "get_the_calltip",
101n/a (expression,), {})
102n/a else:
103n/a return get_argspec(get_entity(expression))
104n/a
105n/adef get_entity(expression):
106n/a """Return the object corresponding to expression evaluated
107n/a in a namespace spanning sys.modules and __main.dict__.
108n/a """
109n/a if expression:
110n/a namespace = sys.modules.copy()
111n/a namespace.update(__main__.__dict__)
112n/a try:
113n/a return eval(expression, namespace)
114n/a except BaseException:
115n/a # An uncaught exception closes idle, and eval can raise any
116n/a # exception, especially if user classes are involved.
117n/a return None
118n/a
119n/a# The following are used in both get_argspec and tests
120n/a_first_param = re.compile('(?<=\()\w*\,?\s*')
121n/a_default_callable_argspec = "No docstring, see docs."
122n/a
123n/adef get_argspec(ob):
124n/a '''Return a string describing the arguments and return of a callable object.
125n/a
126n/a For Python-coded functions and methods, the first line is introspected.
127n/a Delete 'self' parameter for classes (.__init__) and bound methods.
128n/a The last line is the first line of the doc string. For builtins, this typically
129n/a includes the arguments in addition to the return value.
130n/a
131n/a '''
132n/a argspec = ""
133n/a if hasattr(ob, '__call__'):
134n/a if isinstance(ob, type):
135n/a fob = getattr(ob, '__init__', None)
136n/a elif isinstance(ob.__call__, types.MethodType):
137n/a fob = ob.__call__
138n/a else:
139n/a fob = ob
140n/a if isinstance(fob, (types.FunctionType, types.MethodType)):
141n/a argspec = inspect.formatargspec(*inspect.getfullargspec(fob))
142n/a if (isinstance(ob, (type, types.MethodType)) or
143n/a isinstance(ob.__call__, types.MethodType)):
144n/a argspec = _first_param.sub("", argspec)
145n/a
146n/a if isinstance(ob.__call__, types.MethodType):
147n/a doc = ob.__call__.__doc__
148n/a else:
149n/a doc = getattr(ob, "__doc__", "")
150n/a if doc:
151n/a doc = doc.lstrip()
152n/a pos = doc.find("\n")
153n/a if pos < 0 or pos > 70:
154n/a pos = 70
155n/a if argspec:
156n/a argspec += "\n"
157n/a argspec += doc[:pos]
158n/a if not argspec:
159n/a argspec = _default_callable_argspec
160n/a return argspec
161n/a
162n/a#################################################
163n/a#
164n/a# Test code tests CallTips.fetch_tip, get_entity, and get_argspec
165n/a
166n/adef main():
167n/a # Putting expected in docstrings results in doubled tips for test
168n/a def t1(): "()"
169n/a def t2(a, b=None): "(a, b=None)"
170n/a def t3(a, *args): "(a, *args)"
171n/a def t4(*args): "(*args)"
172n/a def t5(a, b=None, *args, **kw): "(a, b=None, *args, **kw)"
173n/a
174n/a class TC(object):
175n/a "(ai=None, *b)"
176n/a def __init__(self, ai=None, *b): "(self, ai=None, *b)"
177n/a def t1(self): "(self)"
178n/a def t2(self, ai, b=None): "(self, ai, b=None)"
179n/a def t3(self, ai, *args): "(self, ai, *args)"
180n/a def t4(self, *args): "(self, *args)"
181n/a def t5(self, ai, b=None, *args, **kw): "(self, ai, b=None, *args, **kw)"
182n/a def t6(no, self): "(no, self)"
183n/a @classmethod
184n/a def cm(cls, a): "(cls, a)"
185n/a @staticmethod
186n/a def sm(b): "(b)"
187n/a def __call__(self, ci): "(self, ci)"
188n/a
189n/a tc = TC()
190n/a
191n/a # Python classes that inherit builtin methods
192n/a class Int(int): "Int(x[, base]) -> integer"
193n/a class List(list): "List() -> new empty list"
194n/a # Simulate builtin with no docstring for default argspec test
195n/a class SB: __call__ = None
196n/a
197n/a __main__.__dict__.update(locals()) # required for get_entity eval()
198n/a
199n/a num_tests = num_fail = 0
200n/a tip = CallTips().fetch_tip
201n/a
202n/a def test(expression, expected):
203n/a nonlocal num_tests, num_fail
204n/a num_tests += 1
205n/a argspec = tip(expression)
206n/a if argspec != expected:
207n/a num_fail += 1
208n/a fmt = "%s - expected\n%r\n - but got\n%r"
209n/a print(fmt % (expression, expected, argspec))
210n/a
211n/a def test_builtins():
212n/a # if first line of a possibly multiline compiled docstring changes,
213n/a # must change corresponding test string
214n/a test('int', "int(x=0) -> integer")
215n/a test('Int', Int.__doc__)
216n/a test('types.MethodType', "method(function, instance)")
217n/a test('list', "list() -> new empty list")
218n/a test('List', List.__doc__)
219n/a test('list.__new__',
220n/a 'T.__new__(S, ...) -> a new object with type S, a subtype of T')
221n/a test('list.__init__',
222n/a 'x.__init__(...) initializes x; see help(type(x)) for signature')
223n/a append_doc = "L.append(object) -> None -- append object to end"
224n/a test('list.append', append_doc)
225n/a test('[].append', append_doc)
226n/a test('List.append', append_doc)
227n/a test('SB()', _default_callable_argspec)
228n/a
229n/a def test_funcs():
230n/a for func in (t1, t2, t3, t4, t5, TC,):
231n/a fdoc = func.__doc__
232n/a test(func.__name__, fdoc + "\n" + fdoc)
233n/a for func in (TC.t1, TC.t2, TC.t3, TC.t4, TC.t5, TC.t6, TC.sm,
234n/a TC.__call__):
235n/a fdoc = func.__doc__
236n/a test('TC.'+func.__name__, fdoc + "\n" + fdoc)
237n/a fdoc = TC.cm.__func__.__doc__
238n/a test('TC.cm.__func__', fdoc + "\n" + fdoc)
239n/a
240n/a def test_methods():
241n/a # test that first parameter is correctly removed from argspec
242n/a # using _first_param re to calculate expected masks re errors
243n/a for meth, mdoc in ((tc.t1, "()"), (tc.t4, "(*args)"), (tc.t6, "(self)"),
244n/a (TC.cm, "(a)"),):
245n/a test('tc.'+meth.__name__, mdoc + "\n" + meth.__doc__)
246n/a test('tc', "(ci)" + "\n" + tc.__call__.__doc__)
247n/a # directly test that re works to delete unicode parameter name
248n/a uni = "(A\u0391\u0410\u05d0\u0627\u0905\u1e00\u3042, a)" # various As
249n/a assert _first_param.sub('', uni) == '(a)'
250n/a
251n/a def test_non_callables():
252n/a # expression evaluates, but not to a callable
253n/a for expr in ('0', '0.0' 'num_tests', b'num_tests', '[]', '{}'):
254n/a test(expr, '')
255n/a # expression does not evaluate, but raises an exception
256n/a for expr in ('1a', 'xyx', 'num_tests.xyz', '[int][1]', '{0:int}[1]'):
257n/a test(expr, '')
258n/a
259n/a test_builtins()
260n/a test_funcs()
261n/a test_non_callables()
262n/a test_methods()
263n/a
264n/a print("%d of %d tests failed" % (num_fail, num_tests))
265n/a
266n/aif __name__ == '__main__':
267n/a #main()
268n/a from unittest import main
269n/a main('idlelib.idle_test.test_calltips', verbosity=2, exit=False)