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

Python code coverage for Lib/idlelib/idle_test/mock_tk.py

#countcontent
1n/a"""Classes that replace tkinter gui objects used by an object being tested.
2n/a
3n/aA gui object is anything with a master or parent parameter, which is
4n/atypically required in spite of what the doc strings say.
5n/a"""
6n/a
7n/aclass Event:
8n/a '''Minimal mock with attributes for testing event handlers.
9n/a
10n/a This is not a gui object, but is used as an argument for callbacks
11n/a that access attributes of the event passed. If a callback ignores
12n/a the event, other than the fact that is happened, pass 'event'.
13n/a
14n/a Keyboard, mouse, window, and other sources generate Event instances.
15n/a Event instances have the following attributes: serial (number of
16n/a event), time (of event), type (of event as number), widget (in which
17n/a event occurred), and x,y (position of mouse). There are other
18n/a attributes for specific events, such as keycode for key events.
19n/a tkinter.Event.__doc__ has more but is still not complete.
20n/a '''
21n/a def __init__(self, **kwds):
22n/a "Create event with attributes needed for test"
23n/a self.__dict__.update(kwds)
24n/a
25n/aclass Var:
26n/a "Use for String/Int/BooleanVar: incomplete"
27n/a def __init__(self, master=None, value=None, name=None):
28n/a self.master = master
29n/a self.value = value
30n/a self.name = name
31n/a def set(self, value):
32n/a self.value = value
33n/a def get(self):
34n/a return self.value
35n/a
36n/aclass Mbox_func:
37n/a """Generic mock for messagebox functions, which all have the same signature.
38n/a
39n/a Instead of displaying a message box, the mock's call method saves the
40n/a arguments as instance attributes, which test functions can then examime.
41n/a The test can set the result returned to ask function
42n/a """
43n/a def __init__(self, result=None):
44n/a self.result = result # Return None for all show funcs
45n/a def __call__(self, title, message, *args, **kwds):
46n/a # Save all args for possible examination by tester
47n/a self.title = title
48n/a self.message = message
49n/a self.args = args
50n/a self.kwds = kwds
51n/a return self.result # Set by tester for ask functions
52n/a
53n/aclass Mbox:
54n/a """Mock for tkinter.messagebox with an Mbox_func for each function.
55n/a
56n/a This module was 'tkMessageBox' in 2.x; hence the 'import as' in 3.x.
57n/a Example usage in test_module.py for testing functions in module.py:
58n/a ---
59n/afrom idlelib.idle_test.mock_tk import Mbox
60n/aimport module
61n/a
62n/aorig_mbox = module.tkMessageBox
63n/ashowerror = Mbox.showerror # example, for attribute access in test methods
64n/a
65n/aclass Test(unittest.TestCase):
66n/a
67n/a @classmethod
68n/a def setUpClass(cls):
69n/a module.tkMessageBox = Mbox
70n/a
71n/a @classmethod
72n/a def tearDownClass(cls):
73n/a module.tkMessageBox = orig_mbox
74n/a ---
75n/a For 'ask' functions, set func.result return value before calling the method
76n/a that uses the message function. When tkMessageBox functions are the
77n/a only gui alls in a method, this replacement makes the method gui-free,
78n/a """
79n/a askokcancel = Mbox_func() # True or False
80n/a askquestion = Mbox_func() # 'yes' or 'no'
81n/a askretrycancel = Mbox_func() # True or False
82n/a askyesno = Mbox_func() # True or False
83n/a askyesnocancel = Mbox_func() # True, False, or None
84n/a showerror = Mbox_func() # None
85n/a showinfo = Mbox_func() # None
86n/a showwarning = Mbox_func() # None
87n/a
88n/afrom _tkinter import TclError
89n/a
90n/aclass Text:
91n/a """A semi-functional non-gui replacement for tkinter.Text text editors.
92n/a
93n/a The mock's data model is that a text is a list of \n-terminated lines.
94n/a The mock adds an empty string at the beginning of the list so that the
95n/a index of actual lines start at 1, as with Tk. The methods never see this.
96n/a Tk initializes files with a terminal \n that cannot be deleted. It is
97n/a invisible in the sense that one cannot move the cursor beyond it.
98n/a
99n/a This class is only tested (and valid) with strings of ascii chars.
100n/a For testing, we are not concerned with Tk Text's treatment of,
101n/a for instance, 0-width characters or character + accent.
102n/a """
103n/a def __init__(self, master=None, cnf={}, **kw):
104n/a '''Initialize mock, non-gui, text-only Text widget.
105n/a
106n/a At present, all args are ignored. Almost all affect visual behavior.
107n/a There are just a few Text-only options that affect text behavior.
108n/a '''
109n/a self.data = ['', '\n']
110n/a
111n/a def index(self, index):
112n/a "Return string version of index decoded according to current text."
113n/a return "%s.%s" % self._decode(index, endflag=1)
114n/a
115n/a def _decode(self, index, endflag=0):
116n/a """Return a (line, char) tuple of int indexes into self.data.
117n/a
118n/a This implements .index without converting the result back to a string.
119n/a The result is constrained by the number of lines and linelengths of
120n/a self.data. For many indexes, the result is initially (1, 0).
121n/a
122n/a The input index may have any of several possible forms:
123n/a * line.char float: converted to 'line.char' string;
124n/a * 'line.char' string, where line and char are decimal integers;
125n/a * 'line.char lineend', where lineend='lineend' (and char is ignored);
126n/a * 'line.end', where end='end' (same as above);
127n/a * 'insert', the positions before terminal \n;
128n/a * 'end', whose meaning depends on the endflag passed to ._endex.
129n/a * 'sel.first' or 'sel.last', where sel is a tag -- not implemented.
130n/a """
131n/a if isinstance(index, (float, bytes)):
132n/a index = str(index)
133n/a try:
134n/a index=index.lower()
135n/a except AttributeError:
136n/a raise TclError('bad text index "%s"' % index) from None
137n/a
138n/a lastline = len(self.data) - 1 # same as number of text lines
139n/a if index == 'insert':
140n/a return lastline, len(self.data[lastline]) - 1
141n/a elif index == 'end':
142n/a return self._endex(endflag)
143n/a
144n/a line, char = index.split('.')
145n/a line = int(line)
146n/a
147n/a # Out of bounds line becomes first or last ('end') index
148n/a if line < 1:
149n/a return 1, 0
150n/a elif line > lastline:
151n/a return self._endex(endflag)
152n/a
153n/a linelength = len(self.data[line]) -1 # position before/at \n
154n/a if char.endswith(' lineend') or char == 'end':
155n/a return line, linelength
156n/a # Tk requires that ignored chars before ' lineend' be valid int
157n/a
158n/a # Out of bounds char becomes first or last index of line
159n/a char = int(char)
160n/a if char < 0:
161n/a char = 0
162n/a elif char > linelength:
163n/a char = linelength
164n/a return line, char
165n/a
166n/a def _endex(self, endflag):
167n/a '''Return position for 'end' or line overflow corresponding to endflag.
168n/a
169n/a -1: position before terminal \n; for .insert(), .delete
170n/a 0: position after terminal \n; for .get, .delete index 1
171n/a 1: same viewed as beginning of non-existent next line (for .index)
172n/a '''
173n/a n = len(self.data)
174n/a if endflag == 1:
175n/a return n, 0
176n/a else:
177n/a n -= 1
178n/a return n, len(self.data[n]) + endflag
179n/a
180n/a
181n/a def insert(self, index, chars):
182n/a "Insert chars before the character at index."
183n/a
184n/a if not chars: # ''.splitlines() is [], not ['']
185n/a return
186n/a chars = chars.splitlines(True)
187n/a if chars[-1][-1] == '\n':
188n/a chars.append('')
189n/a line, char = self._decode(index, -1)
190n/a before = self.data[line][:char]
191n/a after = self.data[line][char:]
192n/a self.data[line] = before + chars[0]
193n/a self.data[line+1:line+1] = chars[1:]
194n/a self.data[line+len(chars)-1] += after
195n/a
196n/a
197n/a def get(self, index1, index2=None):
198n/a "Return slice from index1 to index2 (default is 'index1+1')."
199n/a
200n/a startline, startchar = self._decode(index1)
201n/a if index2 is None:
202n/a endline, endchar = startline, startchar+1
203n/a else:
204n/a endline, endchar = self._decode(index2)
205n/a
206n/a if startline == endline:
207n/a return self.data[startline][startchar:endchar]
208n/a else:
209n/a lines = [self.data[startline][startchar:]]
210n/a for i in range(startline+1, endline):
211n/a lines.append(self.data[i])
212n/a lines.append(self.data[endline][:endchar])
213n/a return ''.join(lines)
214n/a
215n/a
216n/a def delete(self, index1, index2=None):
217n/a '''Delete slice from index1 to index2 (default is 'index1+1').
218n/a
219n/a Adjust default index2 ('index+1) for line ends.
220n/a Do not delete the terminal \n at the very end of self.data ([-1][-1]).
221n/a '''
222n/a startline, startchar = self._decode(index1, -1)
223n/a if index2 is None:
224n/a if startchar < len(self.data[startline])-1:
225n/a # not deleting \n
226n/a endline, endchar = startline, startchar+1
227n/a elif startline < len(self.data) - 1:
228n/a # deleting non-terminal \n, convert 'index1+1 to start of next line
229n/a endline, endchar = startline+1, 0
230n/a else:
231n/a # do not delete terminal \n if index1 == 'insert'
232n/a return
233n/a else:
234n/a endline, endchar = self._decode(index2, -1)
235n/a # restricting end position to insert position excludes terminal \n
236n/a
237n/a if startline == endline and startchar < endchar:
238n/a self.data[startline] = self.data[startline][:startchar] + \
239n/a self.data[startline][endchar:]
240n/a elif startline < endline:
241n/a self.data[startline] = self.data[startline][:startchar] + \
242n/a self.data[endline][endchar:]
243n/a startline += 1
244n/a for i in range(startline, endline+1):
245n/a del self.data[startline]
246n/a
247n/a def compare(self, index1, op, index2):
248n/a line1, char1 = self._decode(index1)
249n/a line2, char2 = self._decode(index2)
250n/a if op == '<':
251n/a return line1 < line2 or line1 == line2 and char1 < char2
252n/a elif op == '<=':
253n/a return line1 < line2 or line1 == line2 and char1 <= char2
254n/a elif op == '>':
255n/a return line1 > line2 or line1 == line2 and char1 > char2
256n/a elif op == '>=':
257n/a return line1 > line2 or line1 == line2 and char1 >= char2
258n/a elif op == '==':
259n/a return line1 == line2 and char1 == char2
260n/a elif op == '!=':
261n/a return line1 != line2 or char1 != char2
262n/a else:
263n/a raise TclError('''bad comparison operator "%s":'''
264n/a '''must be <, <=, ==, >=, >, or !=''' % op)
265n/a
266n/a # The following Text methods normally do something and return None.
267n/a # Whether doing nothing is sufficient for a test will depend on the test.
268n/a
269n/a def mark_set(self, name, index):
270n/a "Set mark *name* before the character at index."
271n/a pass
272n/a
273n/a def mark_unset(self, *markNames):
274n/a "Delete all marks in markNames."
275n/a
276n/a def tag_remove(self, tagName, index1, index2=None):
277n/a "Remove tag tagName from all characters between index1 and index2."
278n/a pass
279n/a
280n/a # The following Text methods affect the graphics screen and return None.
281n/a # Doing nothing should always be sufficient for tests.
282n/a
283n/a def scan_dragto(self, x, y):
284n/a "Adjust the view of the text according to scan_mark"
285n/a
286n/a def scan_mark(self, x, y):
287n/a "Remember the current X, Y coordinates."
288n/a
289n/a def see(self, index):
290n/a "Scroll screen to make the character at INDEX is visible."
291n/a pass
292n/a
293n/a # The following is a Misc method inherited by Text.
294n/a # It should properly go in a Misc mock, but is included here for now.
295n/a
296n/a def bind(sequence=None, func=None, add=None):
297n/a "Bind to this widget at event sequence a call to function func."
298n/a pass
299n/a
300n/aclass Entry:
301n/a "Mock for tkinter.Entry."
302n/a def focus_set(self):
303n/a pass