Debian Codegraph @

Lib/test/test_tkinter/test_simpledialog.py

raw
1 import unittest
2 import tkinter
3 from tkinter import messagebox
4 from test.support import requires, swap_attr
5 from test.test_tkinter.support import setUpModule # noqa: F401
6 from test.test_tkinter.support import AbstractDefaultRootTest, AbstractTkTest
7 from tkinter.simpledialog import (Dialog, SimpleDialog,
8 askinteger, askfloat, askstring,
9 _QueryInteger, _QueryFloat, _QueryString)
10
11 requires('gui')
12
13
14 class SimpleDialogTest(AbstractTkTest, unittest.TestCase):
15 # SimpleDialog's modal loop is in go(); its bindings are exercised here by
16 # generating events on the constructed dialog, without entering the loop.
17
18 def create(self, **kw):
19 kw.setdefault('text', 'Question?')
20 kw.setdefault('buttons', ['Yes', 'No'])
21 kw.setdefault('default', 0)
22 kw.setdefault('cancel', 1)
23 d = SimpleDialog(self.root, **kw)
24 self.addCleanup(lambda: d.root.winfo_exists() and d.root.destroy())
25 return d
26
27 def test_message(self):
28 # The text is shown in a message widget.
29 d = self.create(text='Hello?')
30 self.assertEqual(d.message.winfo_class(), 'Message')
31 self.assertEqual(str(d.message.cget('text')), 'Hello?')
32
33 def test_class_name(self):
34 # class_ sets the Tk class of the dialog window.
35 d = self.create(class_='MyDialog')
36 self.assertEqual(d.root.winfo_class(), 'MyDialog')
37
38 def test_button(self):
39 # Pressing a button records its index.
40 d = self.create(buttons=['Yes', 'No'])
41 d.frame.winfo_children()[1].invoke() # "No"
42 self.assertEqual(d.num, 1)
43
44 def test_default_button(self):
45 # The default button is drawn with a raised border.
46 d = self.create(buttons=['Yes', 'No'], default=0)
47 self.assertEqual(str(d.frame.winfo_children()[0].cget('relief')), 'ridge')
48
49 def test_return_activates_default(self):
50 # <Return> invokes the default button.
51 d = self.create() # default 0
52 self.require_mapped(d.root)
53 d.root.focus_force()
54 d.root.update()
55 d.root.event_generate('<Return>')
56 d.root.update()
57 self.assertEqual(d.num, 0)
58
59 def test_return_no_default(self):
60 # With no default button, <Return> rings the bell and leaves the dialog
61 # open instead of activating a button.
62 d = self.create(default=None)
63 self.require_mapped(d.root)
64 d.root.focus_force()
65 d.root.update()
66 bells = []
67 with swap_attr(d.root, 'bell', lambda *a, **k: bells.append(True)):
68 d.root.event_generate('<Return>')
69 d.root.update()
70 self.assertTrue(bells) # rang the bell
71 self.assertIsNone(d.num)
72 self.assertTrue(d.root.winfo_exists())
73
74 def test_wm_delete_cancels(self):
75 # Closing the window through the window manager records the cancel index.
76 d = self.create() # cancel 1
77 d.wm_delete_window()
78 self.assertEqual(d.num, 1)
79
80 def test_wm_delete_no_cancel(self):
81 # With no cancel index, closing the window through the window manager
82 # rings the bell and leaves the dialog open instead of recording an
83 # index.
84 d = self.create(default=None, cancel=None)
85 d.root.update()
86 bells = []
87 with swap_attr(d.root, 'bell', lambda *a, **k: bells.append(True)):
88 d.wm_delete_window()
89 d.root.update()
90 self.assertTrue(bells) # rang the bell
91 self.assertIsNone(d.num)
92 self.assertTrue(d.root.winfo_exists())
93
94 def test_go(self):
95 # go() runs the modal loop and returns the chosen button's index.
96 d = self.create()
97 d.root.after(1, lambda: d.done(0))
98 self.assertEqual(d.go(), 0)
99
100
101 class DialogTest(AbstractTkTest, unittest.TestCase):
102 # Dialog is a base class for custom dialogs; exercise it via _QueryInteger.
103
104 def open(self, **kw):
105 with swap_attr(Dialog, 'wait_window', staticmethod(lambda w: None)):
106 d = _QueryInteger('Title', 'Prompt', parent=self.root, **kw)
107 self.addCleanup(lambda: d.winfo_exists() and d.destroy())
108 return d
109
110 def buttons(self, d):
111 # Map the button box's buttons by their label.
112 return {str(b.cget('text')): b
113 for frame in d.winfo_children()
114 for b in frame.winfo_children()
115 if b.winfo_class() == 'Button'}
116
117 def test_background(self):
118 # The classic dialog keeps the default Toplevel background.
119 d = self.open()
120 ref = tkinter.Toplevel(self.root)
121 self.addCleanup(ref.destroy)
122 self.assertEqual(str(d.cget('background')), str(ref.cget('background')))
123
124 def test_buttons(self):
125 # The button box has OK (the default) and Cancel buttons.
126 buttons = self.buttons(self.open())
127 self.assertEqual(set(buttons), {'OK', 'Cancel'})
128 self.assertEqual(str(buttons['OK'].cget('default')), 'active')
129
130 def test_ok(self):
131 # The OK button validates the entry and stores the result.
132 d = self.open()
133 d.entry.insert(0, '42')
134 self.buttons(d)['OK'].invoke()
135 self.assertEqual(d.result, 42)
136 self.assertFalse(d.winfo_exists()) # The dialog closed.
137
138 def test_cancel(self):
139 # The Cancel button closes the dialog without a result.
140 d = self.open()
141 self.buttons(d)['Cancel'].invoke()
142 self.assertIsNone(d.result)
143 self.assertFalse(d.winfo_exists())
144
145
146 class DefaultRootTest(AbstractDefaultRootTest, unittest.TestCase):
147
148 def test_askinteger(self):
149 @staticmethod
150 def mock_wait_window(w):
151 nonlocal ismapped
152 ismapped = w.master.winfo_ismapped()
153 w.destroy()
154
155 with swap_attr(Dialog, 'wait_window', mock_wait_window):
156 ismapped = None
157 askinteger("Go To Line", "Line number")
158 self.assertEqual(ismapped, False)
159
160 root = tkinter.Tk()
161 ismapped = None
162 askinteger("Go To Line", "Line number")
163 self.assertEqual(ismapped, True)
164 root.destroy()
165
166 tkinter.NoDefaultRoot()
167 self.assertRaises(RuntimeError, askinteger, "Go To Line", "Line number")
168
169
170 class QueryDialogTest(AbstractTkTest, unittest.TestCase):
171 # The query dialogs are modal: their __init__ blocks in wait_window().
172 # Mock that out so the dialog stays alive and can be driven with generated
173 # events, exercising the <Return>/<Escape> bindings and the validation.
174
175 def open(self, query, **kw):
176 with swap_attr(Dialog, 'wait_window', staticmethod(lambda w: None)):
177 d = query("Title", "Prompt", parent=self.root, **kw)
178 self.addCleanup(lambda: d.winfo_exists() and d.destroy())
179 d.focus_force()
180 d.update()
181 return d
182
183 def enter(self, d, value, key='<Return>'):
184 d.entry.delete(0, 'end')
185 d.entry.insert(0, value)
186 d.event_generate(key)
187 d.update()
188
189 def test_initialvalue(self):
190 # The entry is pre-filled with the initial value, which is accepted.
191 d = self.open(_QueryInteger, initialvalue=42)
192 self.assertEqual(d.entry.get(), '42')
193 d.event_generate('<Return>')
194 d.update()
195 self.assertEqual(d.result, 42)
196
197 def test_show(self):
198 # _QueryString hides the entered text when show is given.
199 d = self.open(_QueryString, show='*')
200 self.assertEqual(str(d.entry.cget('show')), '*')
201
202 def test_return_accepts(self):
203 for query, value, expected in [
204 (_QueryInteger, '42', 42),
205 (_QueryFloat, '1.5', 1.5),
206 (_QueryString, 'spam', 'spam'),
207 ]:
208 with self.subTest(query=query.__name__):
209 d = self.open(query)
210 self.enter(d, value)
211 self.assertEqual(d.result, expected)
212 self.assertFalse(d.winfo_exists()) # The dialog closed.
213
214 def test_escape_cancels(self):
215 d = self.open(_QueryString)
216 self.enter(d, 'spam', '<Escape>')
217 self.assertIsNone(d.result)
218 self.assertFalse(d.winfo_exists())
219
220 def test_invalid_value(self):
221 warnings = []
222 d = self.open(_QueryInteger)
223 with swap_attr(messagebox, 'showwarning',
224 lambda *a, **k: warnings.append(a)):
225 self.enter(d, 'not a number')
226 self.assertIsNone(d.result)
227 self.assertTrue(d.winfo_exists()) # The dialog stays open.
228 self.assertTrue(warnings)
229
230 def test_out_of_range(self):
231 warnings = []
232 d = self.open(_QueryInteger, minvalue=10, maxvalue=20)
233 with swap_attr(messagebox, 'showwarning',
234 lambda *a, **k: warnings.append(a)):
235 self.enter(d, '5') # Below the minimum.
236 self.assertIsNone(d.result)
237 self.enter(d, '25') # Above the maximum.
238 self.assertIsNone(d.result)
239 self.assertTrue(d.winfo_exists())
240 self.assertEqual(len(warnings), 2)
241
242 def test_boundary_values_accepted(self):
243 # The min/max checks are inclusive: a value equal to a bound passes.
244 d = self.open(_QueryInteger, minvalue=10, maxvalue=20)
245 self.enter(d, '10') # Exactly the minimum.
246 self.assertEqual(d.result, 10)
247 self.assertFalse(d.winfo_exists())
248
249 d = self.open(_QueryInteger, minvalue=10, maxvalue=20)
250 self.enter(d, '20') # Exactly the maximum.
251 self.assertEqual(d.result, 20)
252 self.assertFalse(d.winfo_exists())
253
254 def run_ask(self, ask, value, **kw):
255 # Drive a modal ask* function: enter a value and accept it.
256 def accept(d):
257 d.entry.delete(0, 'end')
258 d.entry.insert(0, value)
259 d.ok()
260 with swap_attr(Dialog, 'wait_window', staticmethod(accept)):
261 return ask('Title', 'Prompt', parent=self.root, **kw)
262
263 def test_ask_functions(self):
264 self.assertEqual(self.run_ask(askinteger, '42'), 42)
265 self.assertEqual(self.run_ask(askfloat, '1.5'), 1.5)
266 self.assertEqual(self.run_ask(askstring, 'spam'), 'spam')
267
268 def test_ask_cancelled(self):
269 # A cancelled ask* returns None.
270 with swap_attr(Dialog, 'wait_window', staticmethod(lambda d: d.cancel())):
271 self.assertIsNone(askstring('Title', 'Prompt', parent=self.root))
272
273
274 if __name__ == "__main__":
275 unittest.main()