ZTWHHH commited on
Commit
268bae4
·
verified ·
1 Parent(s): 37b299c

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. llava/lib/python3.10/idlelib/idle_test/__pycache__/htest.cpython-310.pyc +0 -0
  2. llava/lib/python3.10/idlelib/idle_test/__pycache__/mock_tk.cpython-310.pyc +0 -0
  3. llava/lib/python3.10/idlelib/idle_test/__pycache__/test_delegator.cpython-310.pyc +0 -0
  4. llava/lib/python3.10/idlelib/idle_test/__pycache__/test_parenmatch.cpython-310.pyc +0 -0
  5. llava/lib/python3.10/idlelib/idle_test/__pycache__/test_percolator.cpython-310.pyc +0 -0
  6. llava/lib/python3.10/idlelib/idle_test/__pycache__/test_query.cpython-310.pyc +0 -0
  7. llava/lib/python3.10/idlelib/idle_test/__pycache__/test_replace.cpython-310.pyc +0 -0
  8. llava/lib/python3.10/idlelib/idle_test/__pycache__/test_scrolledlist.cpython-310.pyc +0 -0
  9. llava/lib/python3.10/idlelib/idle_test/__pycache__/test_searchbase.cpython-310.pyc +0 -0
  10. llava/lib/python3.10/idlelib/idle_test/__pycache__/test_squeezer.cpython-310.pyc +0 -0
  11. llava/lib/python3.10/idlelib/idle_test/__pycache__/test_tree.cpython-310.pyc +0 -0
  12. llava/lib/python3.10/idlelib/idle_test/__pycache__/test_zoomheight.cpython-310.pyc +0 -0
  13. llava/lib/python3.10/idlelib/idle_test/__pycache__/tkinter_testing_utils.cpython-310.pyc +0 -0
  14. llava/lib/python3.10/idlelib/idle_test/example_stub.pyi +2 -0
  15. llava/lib/python3.10/idlelib/idle_test/htest.py +445 -0
  16. llava/lib/python3.10/idlelib/idle_test/mock_idle.py +61 -0
  17. llava/lib/python3.10/idlelib/idle_test/template.py +30 -0
  18. llava/lib/python3.10/idlelib/idle_test/test_autocomplete.py +305 -0
  19. llava/lib/python3.10/idlelib/idle_test/test_autocomplete_w.py +32 -0
  20. llava/lib/python3.10/idlelib/idle_test/test_autoexpand.py +155 -0
  21. llava/lib/python3.10/idlelib/idle_test/test_calltip.py +363 -0
  22. llava/lib/python3.10/idlelib/idle_test/test_calltip_w.py +29 -0
  23. llava/lib/python3.10/idlelib/idle_test/test_codecontext.py +455 -0
  24. llava/lib/python3.10/idlelib/idle_test/test_config.py +805 -0
  25. llava/lib/python3.10/idlelib/idle_test/test_config_key.py +356 -0
  26. llava/lib/python3.10/idlelib/idle_test/test_configdialog.py +1583 -0
  27. llava/lib/python3.10/idlelib/idle_test/test_debugger.py +29 -0
  28. llava/lib/python3.10/idlelib/idle_test/test_debugobj.py +57 -0
  29. llava/lib/python3.10/idlelib/idle_test/test_debugobj_r.py +22 -0
  30. llava/lib/python3.10/idlelib/idle_test/test_delegator.py +44 -0
  31. llava/lib/python3.10/idlelib/idle_test/test_editmenu.py +74 -0
  32. llava/lib/python3.10/idlelib/idle_test/test_grep.py +156 -0
  33. llava/lib/python3.10/idlelib/idle_test/test_help.py +34 -0
  34. llava/lib/python3.10/idlelib/idle_test/test_help_about.py +182 -0
  35. llava/lib/python3.10/idlelib/idle_test/test_history.py +172 -0
  36. llava/lib/python3.10/idlelib/idle_test/test_macosx.py +113 -0
  37. llava/lib/python3.10/idlelib/idle_test/test_mainmenu.py +42 -0
  38. llava/lib/python3.10/idlelib/idle_test/test_multicall.py +48 -0
  39. llava/lib/python3.10/idlelib/idle_test/test_outwin.py +166 -0
  40. llava/lib/python3.10/idlelib/idle_test/test_parenmatch.py +112 -0
  41. llava/lib/python3.10/idlelib/idle_test/test_pathbrowser.py +86 -0
  42. llava/lib/python3.10/idlelib/idle_test/test_percolator.py +118 -0
  43. llava/lib/python3.10/idlelib/idle_test/test_pyparse.py +483 -0
  44. llava/lib/python3.10/idlelib/idle_test/test_rpc.py +29 -0
  45. llava/lib/python3.10/idlelib/idle_test/test_runscript.py +33 -0
  46. llava/lib/python3.10/idlelib/idle_test/test_scrolledlist.py +27 -0
  47. llava/lib/python3.10/idlelib/idle_test/test_search.py +80 -0
  48. llava/lib/python3.10/idlelib/idle_test/test_searchengine.py +332 -0
  49. llava/lib/python3.10/idlelib/idle_test/test_statusbar.py +41 -0
  50. llava/lib/python3.10/idlelib/idle_test/test_undo.py +135 -0
llava/lib/python3.10/idlelib/idle_test/__pycache__/htest.cpython-310.pyc ADDED
Binary file (14.2 kB). View file
 
llava/lib/python3.10/idlelib/idle_test/__pycache__/mock_tk.cpython-310.pyc ADDED
Binary file (11.1 kB). View file
 
llava/lib/python3.10/idlelib/idle_test/__pycache__/test_delegator.cpython-310.pyc ADDED
Binary file (1.34 kB). View file
 
llava/lib/python3.10/idlelib/idle_test/__pycache__/test_parenmatch.cpython-310.pyc ADDED
Binary file (4.13 kB). View file
 
llava/lib/python3.10/idlelib/idle_test/__pycache__/test_percolator.cpython-310.pyc ADDED
Binary file (4.85 kB). View file
 
llava/lib/python3.10/idlelib/idle_test/__pycache__/test_query.cpython-310.pyc ADDED
Binary file (18.7 kB). View file
 
llava/lib/python3.10/idlelib/idle_test/__pycache__/test_replace.cpython-310.pyc ADDED
Binary file (7.12 kB). View file
 
llava/lib/python3.10/idlelib/idle_test/__pycache__/test_scrolledlist.cpython-310.pyc ADDED
Binary file (1.1 kB). View file
 
llava/lib/python3.10/idlelib/idle_test/__pycache__/test_searchbase.cpython-310.pyc ADDED
Binary file (5.34 kB). View file
 
llava/lib/python3.10/idlelib/idle_test/__pycache__/test_squeezer.cpython-310.pyc ADDED
Binary file (16.2 kB). View file
 
llava/lib/python3.10/idlelib/idle_test/__pycache__/test_tree.cpython-310.pyc ADDED
Binary file (2.95 kB). View file
 
llava/lib/python3.10/idlelib/idle_test/__pycache__/test_zoomheight.cpython-310.pyc ADDED
Binary file (1.78 kB). View file
 
llava/lib/python3.10/idlelib/idle_test/__pycache__/tkinter_testing_utils.cpython-310.pyc ADDED
Binary file (2.18 kB). View file
 
llava/lib/python3.10/idlelib/idle_test/example_stub.pyi ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ class Example:
2
+ def method(self, argument1: str, argument2: list[int]) -> None: ...
llava/lib/python3.10/idlelib/idle_test/htest.py ADDED
@@ -0,0 +1,445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''Run human tests of Idle's window, dialog, and popup widgets.
2
+
3
+ run(*tests)
4
+ Create a master Tk window. Within that, run each callable in tests
5
+ after finding the matching test spec in this file. If tests is empty,
6
+ run an htest for each spec dict in this file after finding the matching
7
+ callable in the module named in the spec. Close the window to skip or
8
+ end the test.
9
+
10
+ In a tested module, let X be a global name bound to a callable (class
11
+ or function) whose .__name__ attribute is also X (the usual situation).
12
+ The first parameter of X must be 'parent'. When called, the parent
13
+ argument will be the root window. X must create a child Toplevel
14
+ window (or subclass thereof). The Toplevel may be a test widget or
15
+ dialog, in which case the callable is the corresponding class. Or the
16
+ Toplevel may contain the widget to be tested or set up a context in
17
+ which a test widget is invoked. In this latter case, the callable is a
18
+ wrapper function that sets up the Toplevel and other objects. Wrapper
19
+ function names, such as _editor_window', should start with '_'.
20
+
21
+
22
+ End the module with
23
+
24
+ if __name__ == '__main__':
25
+ <unittest, if there is one>
26
+ from idlelib.idle_test.htest import run
27
+ run(X)
28
+
29
+ To have wrapper functions and test invocation code ignored by coveragepy
30
+ reports, put '# htest #' on the def statement header line.
31
+
32
+ def _wrapper(parent): # htest #
33
+
34
+ Also make sure that the 'if __name__' line matches the above. Then have
35
+ make sure that .coveragerc includes the following.
36
+
37
+ [report]
38
+ exclude_lines =
39
+ .*# htest #
40
+ if __name__ == .__main__.:
41
+
42
+ (The "." instead of "'" is intentional and necessary.)
43
+
44
+
45
+ To run any X, this file must contain a matching instance of the
46
+ following template, with X.__name__ prepended to '_spec'.
47
+ When all tests are run, the prefix is use to get X.
48
+
49
+ _spec = {
50
+ 'file': '',
51
+ 'kwds': {'title': ''},
52
+ 'msg': ""
53
+ }
54
+
55
+ file (no .py): run() imports file.py.
56
+ kwds: augmented with {'parent':root} and passed to X as **kwds.
57
+ title: an example kwd; some widgets need this, delete if not.
58
+ msg: master window hints about testing the widget.
59
+
60
+
61
+ Modules and classes not being tested at the moment:
62
+ pyshell.PyShellEditorWindow
63
+ debugger.Debugger
64
+ autocomplete_w.AutoCompleteWindow
65
+ outwin.OutputWindow (indirectly being tested with grep test)
66
+ '''
67
+
68
+ import idlelib.pyshell # Set Windows DPI awareness before Tk().
69
+ from importlib import import_module
70
+ import textwrap
71
+ import tkinter as tk
72
+ from tkinter.ttk import Scrollbar
73
+ tk.NoDefaultRoot()
74
+
75
+ AboutDialog_spec = {
76
+ 'file': 'help_about',
77
+ 'kwds': {'title': 'help_about test',
78
+ '_htest': True,
79
+ },
80
+ 'msg': "Click on URL to open in default browser.\n"
81
+ "Verify x.y.z versions and test each button, including Close.\n "
82
+ }
83
+
84
+ # TODO implement ^\; adding '<Control-Key-\\>' to function does not work.
85
+ _calltip_window_spec = {
86
+ 'file': 'calltip_w',
87
+ 'kwds': {},
88
+ 'msg': "Typing '(' should display a calltip.\n"
89
+ "Typing ') should hide the calltip.\n"
90
+ "So should moving cursor out of argument area.\n"
91
+ "Force-open-calltip does not work here.\n"
92
+ }
93
+
94
+ _module_browser_spec = {
95
+ 'file': 'browser',
96
+ 'kwds': {},
97
+ 'msg': "Inspect names of module, class(with superclass if "
98
+ "applicable), methods and functions.\nToggle nested items.\n"
99
+ "Double clicking on items prints a traceback for an exception "
100
+ "that is ignored."
101
+ }
102
+
103
+ _color_delegator_spec = {
104
+ 'file': 'colorizer',
105
+ 'kwds': {},
106
+ 'msg': "The text is sample Python code.\n"
107
+ "Ensure components like comments, keywords, builtins,\n"
108
+ "string, definitions, and break are correctly colored.\n"
109
+ "The default color scheme is in idlelib/config-highlight.def"
110
+ }
111
+
112
+ CustomRun_spec = {
113
+ 'file': 'query',
114
+ 'kwds': {'title': 'Customize query.py Run',
115
+ '_htest': True},
116
+ 'msg': "Enter with <Return> or [Run]. Print valid entry to Shell\n"
117
+ "Arguments are parsed into a list\n"
118
+ "Mode is currently restart True or False\n"
119
+ "Close dialog with valid entry, <Escape>, [Cancel], [X]"
120
+ }
121
+
122
+ ConfigDialog_spec = {
123
+ 'file': 'configdialog',
124
+ 'kwds': {'title': 'ConfigDialogTest',
125
+ '_htest': True,},
126
+ 'msg': "IDLE preferences dialog.\n"
127
+ "In the 'Fonts/Tabs' tab, changing font face, should update the "
128
+ "font face of the text in the area below it.\nIn the "
129
+ "'Highlighting' tab, try different color schemes. Clicking "
130
+ "items in the sample program should update the choices above it."
131
+ "\nIn the 'Keys', 'General' and 'Extensions' tabs, test settings "
132
+ "of interest."
133
+ "\n[Ok] to close the dialog.[Apply] to apply the settings and "
134
+ "and [Cancel] to revert all changes.\nRe-run the test to ensure "
135
+ "changes made have persisted."
136
+ }
137
+
138
+ # TODO Improve message
139
+ _dyn_option_menu_spec = {
140
+ 'file': 'dynoption',
141
+ 'kwds': {},
142
+ 'msg': "Select one of the many options in the 'old option set'.\n"
143
+ "Click the button to change the option set.\n"
144
+ "Select one of the many options in the 'new option set'."
145
+ }
146
+
147
+ # TODO edit wrapper
148
+ _editor_window_spec = {
149
+ 'file': 'editor',
150
+ 'kwds': {},
151
+ 'msg': "Test editor functions of interest.\n"
152
+ "Best to close editor first."
153
+ }
154
+
155
+ GetKeysDialog_spec = {
156
+ 'file': 'config_key',
157
+ 'kwds': {'title': 'Test keybindings',
158
+ 'action': 'find-again',
159
+ 'current_key_sequences': [['<Control-Key-g>', '<Key-F3>', '<Control-Key-G>']],
160
+ '_htest': True,
161
+ },
162
+ 'msg': "Test for different key modifier sequences.\n"
163
+ "<nothing> is invalid.\n"
164
+ "No modifier key is invalid.\n"
165
+ "Shift key with [a-z],[0-9], function key, move key, tab, space "
166
+ "is invalid.\nNo validity checking if advanced key binding "
167
+ "entry is used."
168
+ }
169
+
170
+ _grep_dialog_spec = {
171
+ 'file': 'grep',
172
+ 'kwds': {},
173
+ 'msg': "Click the 'Show GrepDialog' button.\n"
174
+ "Test the various 'Find-in-files' functions.\n"
175
+ "The results should be displayed in a new '*Output*' window.\n"
176
+ "'Right-click'->'Go to file/line' anywhere in the search results "
177
+ "should open that file \nin a new EditorWindow."
178
+ }
179
+
180
+ HelpSource_spec = {
181
+ 'file': 'query',
182
+ 'kwds': {'title': 'Help name and source',
183
+ 'menuitem': 'test',
184
+ 'filepath': __file__,
185
+ 'used_names': {'abc'},
186
+ '_htest': True},
187
+ 'msg': "Enter menu item name and help file path\n"
188
+ "'', > than 30 chars, and 'abc' are invalid menu item names.\n"
189
+ "'' and file does not exist are invalid path items.\n"
190
+ "Any url ('www...', 'http...') is accepted.\n"
191
+ "Test Browse with and without path, as cannot unittest.\n"
192
+ "[Ok] or <Return> prints valid entry to shell\n"
193
+ "[Cancel] or <Escape> prints None to shell"
194
+ }
195
+
196
+ _io_binding_spec = {
197
+ 'file': 'iomenu',
198
+ 'kwds': {},
199
+ 'msg': "Test the following bindings.\n"
200
+ "<Control-o> to open file from dialog.\n"
201
+ "Edit the file.\n"
202
+ "<Control-p> to print the file.\n"
203
+ "<Control-s> to save the file.\n"
204
+ "<Alt-s> to save-as another file.\n"
205
+ "<Control-c> to save-copy-as another file.\n"
206
+ "Check that changes were saved by opening the file elsewhere."
207
+ }
208
+
209
+ _linenumbers_drag_scrolling_spec = {
210
+ 'file': 'sidebar',
211
+ 'kwds': {},
212
+ 'msg': textwrap.dedent("""\
213
+ 1. Click on the line numbers and drag down below the edge of the
214
+ window, moving the mouse a bit and then leaving it there for a while.
215
+ The text and line numbers should gradually scroll down, with the
216
+ selection updated continuously.
217
+
218
+ 2. With the lines still selected, click on a line number above the
219
+ selected lines. Only the line whose number was clicked should be
220
+ selected.
221
+
222
+ 3. Repeat step #1, dragging to above the window. The text and line
223
+ numbers should gradually scroll up, with the selection updated
224
+ continuously.
225
+
226
+ 4. Repeat step #2, clicking a line number below the selection."""),
227
+ }
228
+
229
+ _multi_call_spec = {
230
+ 'file': 'multicall',
231
+ 'kwds': {},
232
+ 'msg': "The following actions should trigger a print to console or IDLE"
233
+ " Shell.\nEntering and leaving the text area, key entry, "
234
+ "<Control-Key>,\n<Alt-Key-a>, <Control-Key-a>, "
235
+ "<Alt-Control-Key-a>, \n<Control-Button-1>, <Alt-Button-1> and "
236
+ "focusing out of the window\nare sequences to be tested."
237
+ }
238
+
239
+ _multistatus_bar_spec = {
240
+ 'file': 'statusbar',
241
+ 'kwds': {},
242
+ 'msg': "Ensure presence of multi-status bar below text area.\n"
243
+ "Click 'Update Status' to change the multi-status text"
244
+ }
245
+
246
+ _object_browser_spec = {
247
+ 'file': 'debugobj',
248
+ 'kwds': {},
249
+ 'msg': "Double click on items up to the lowest level.\n"
250
+ "Attributes of the objects and related information "
251
+ "will be displayed side-by-side at each level."
252
+ }
253
+
254
+ _path_browser_spec = {
255
+ 'file': 'pathbrowser',
256
+ 'kwds': {},
257
+ 'msg': "Test for correct display of all paths in sys.path.\n"
258
+ "Toggle nested items up to the lowest level.\n"
259
+ "Double clicking on an item prints a traceback\n"
260
+ "for an exception that is ignored."
261
+ }
262
+
263
+ _percolator_spec = {
264
+ 'file': 'percolator',
265
+ 'kwds': {},
266
+ 'msg': "There are two tracers which can be toggled using a checkbox.\n"
267
+ "Toggling a tracer 'on' by checking it should print tracer "
268
+ "output to the console or to the IDLE shell.\n"
269
+ "If both the tracers are 'on', the output from the tracer which "
270
+ "was switched 'on' later, should be printed first\n"
271
+ "Test for actions like text entry, and removal."
272
+ }
273
+
274
+ Query_spec = {
275
+ 'file': 'query',
276
+ 'kwds': {'title': 'Query',
277
+ 'message': 'Enter something',
278
+ 'text0': 'Go',
279
+ '_htest': True},
280
+ 'msg': "Enter with <Return> or [Ok]. Print valid entry to Shell\n"
281
+ "Blank line, after stripping, is ignored\n"
282
+ "Close dialog with valid entry, <Escape>, [Cancel], [X]"
283
+ }
284
+
285
+
286
+ _replace_dialog_spec = {
287
+ 'file': 'replace',
288
+ 'kwds': {},
289
+ 'msg': "Click the 'Replace' button.\n"
290
+ "Test various replace options in the 'Replace dialog'.\n"
291
+ "Click [Close] or [X] to close the 'Replace Dialog'."
292
+ }
293
+
294
+ _search_dialog_spec = {
295
+ 'file': 'search',
296
+ 'kwds': {},
297
+ 'msg': "Click the 'Search' button.\n"
298
+ "Test various search options in the 'Search dialog'.\n"
299
+ "Click [Close] or [X] to close the 'Search Dialog'."
300
+ }
301
+
302
+ _searchbase_spec = {
303
+ 'file': 'searchbase',
304
+ 'kwds': {},
305
+ 'msg': "Check the appearance of the base search dialog\n"
306
+ "Its only action is to close."
307
+ }
308
+
309
+ _scrolled_list_spec = {
310
+ 'file': 'scrolledlist',
311
+ 'kwds': {},
312
+ 'msg': "You should see a scrollable list of items\n"
313
+ "Selecting (clicking) or double clicking an item "
314
+ "prints the name to the console or Idle shell.\n"
315
+ "Right clicking an item will display a popup."
316
+ }
317
+
318
+ show_idlehelp_spec = {
319
+ 'file': 'help',
320
+ 'kwds': {},
321
+ 'msg': "If the help text displays, this works.\n"
322
+ "Text is selectable. Window is scrollable."
323
+ }
324
+
325
+ _stack_viewer_spec = {
326
+ 'file': 'stackviewer',
327
+ 'kwds': {},
328
+ 'msg': "A stacktrace for a NameError exception.\n"
329
+ "Expand 'idlelib ...' and '<locals>'.\n"
330
+ "Check that exc_value, exc_tb, and exc_type are correct.\n"
331
+ }
332
+
333
+ _tooltip_spec = {
334
+ 'file': 'tooltip',
335
+ 'kwds': {},
336
+ 'msg': "Place mouse cursor over both the buttons\n"
337
+ "A tooltip should appear with some text."
338
+ }
339
+
340
+ _tree_widget_spec = {
341
+ 'file': 'tree',
342
+ 'kwds': {},
343
+ 'msg': "The canvas is scrollable.\n"
344
+ "Click on folders up to to the lowest level."
345
+ }
346
+
347
+ _undo_delegator_spec = {
348
+ 'file': 'undo',
349
+ 'kwds': {},
350
+ 'msg': "Click [Undo] to undo any action.\n"
351
+ "Click [Redo] to redo any action.\n"
352
+ "Click [Dump] to dump the current state "
353
+ "by printing to the console or the IDLE shell.\n"
354
+ }
355
+
356
+ ViewWindow_spec = {
357
+ 'file': 'textview',
358
+ 'kwds': {'title': 'Test textview',
359
+ 'contents': 'The quick brown fox jumps over the lazy dog.\n'*35,
360
+ '_htest': True},
361
+ 'msg': "Test for read-only property of text.\n"
362
+ "Select text, scroll window, close"
363
+ }
364
+
365
+ _widget_redirector_spec = {
366
+ 'file': 'redirector',
367
+ 'kwds': {},
368
+ 'msg': "Every text insert should be printed to the console "
369
+ "or the IDLE shell."
370
+ }
371
+
372
+ def run(*tests):
373
+ root = tk.Tk()
374
+ root.title('IDLE htest')
375
+ root.resizable(0, 0)
376
+
377
+ # a scrollable Label like constant width text widget.
378
+ frameLabel = tk.Frame(root, padx=10)
379
+ frameLabel.pack()
380
+ text = tk.Text(frameLabel, wrap='word')
381
+ text.configure(bg=root.cget('bg'), relief='flat', height=4, width=70)
382
+ scrollbar = Scrollbar(frameLabel, command=text.yview)
383
+ text.config(yscrollcommand=scrollbar.set)
384
+ scrollbar.pack(side='right', fill='y', expand=False)
385
+ text.pack(side='left', fill='both', expand=True)
386
+
387
+ test_list = [] # List of tuples of the form (spec, callable widget)
388
+ if tests:
389
+ for test in tests:
390
+ test_spec = globals()[test.__name__ + '_spec']
391
+ test_spec['name'] = test.__name__
392
+ test_list.append((test_spec, test))
393
+ else:
394
+ for k, d in globals().items():
395
+ if k.endswith('_spec'):
396
+ test_name = k[:-5]
397
+ test_spec = d
398
+ test_spec['name'] = test_name
399
+ mod = import_module('idlelib.' + test_spec['file'])
400
+ test = getattr(mod, test_name)
401
+ test_list.append((test_spec, test))
402
+
403
+ test_name = tk.StringVar(root)
404
+ callable_object = None
405
+ test_kwds = None
406
+
407
+ def next_test():
408
+
409
+ nonlocal test_name, callable_object, test_kwds
410
+ if len(test_list) == 1:
411
+ next_button.pack_forget()
412
+ test_spec, callable_object = test_list.pop()
413
+ test_kwds = test_spec['kwds']
414
+ test_kwds['parent'] = root
415
+ test_name.set('Test ' + test_spec['name'])
416
+
417
+ text.configure(state='normal') # enable text editing
418
+ text.delete('1.0','end')
419
+ text.insert("1.0",test_spec['msg'])
420
+ text.configure(state='disabled') # preserve read-only property
421
+
422
+ def run_test(_=None):
423
+ widget = callable_object(**test_kwds)
424
+ try:
425
+ print(widget.result)
426
+ except AttributeError:
427
+ pass
428
+
429
+ def close(_=None):
430
+ root.destroy()
431
+
432
+ button = tk.Button(root, textvariable=test_name,
433
+ default='active', command=run_test)
434
+ next_button = tk.Button(root, text="Next", command=next_test)
435
+ button.pack()
436
+ next_button.pack()
437
+ next_button.focus_set()
438
+ root.bind('<Key-Return>', run_test)
439
+ root.bind('<Key-Escape>', close)
440
+
441
+ next_test()
442
+ root.mainloop()
443
+
444
+ if __name__ == '__main__':
445
+ run()
llava/lib/python3.10/idlelib/idle_test/mock_idle.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''Mock classes that imitate idlelib modules or classes.
2
+
3
+ Attributes and methods will be added as needed for tests.
4
+ '''
5
+
6
+ from idlelib.idle_test.mock_tk import Text
7
+
8
+ class Func:
9
+ '''Record call, capture args, return/raise result set by test.
10
+
11
+ When mock function is called, set or use attributes:
12
+ self.called - increment call number even if no args, kwds passed.
13
+ self.args - capture positional arguments.
14
+ self.kwds - capture keyword arguments.
15
+ self.result - return or raise value set in __init__.
16
+ self.return_self - return self instead, to mock query class return.
17
+
18
+ Most common use will probably be to mock instance methods.
19
+ Given class instance, can set and delete as instance attribute.
20
+ Mock_tk.Var and Mbox_func are special variants of this.
21
+ '''
22
+ def __init__(self, result=None, return_self=False):
23
+ self.called = 0
24
+ self.result = result
25
+ self.return_self = return_self
26
+ self.args = None
27
+ self.kwds = None
28
+ def __call__(self, *args, **kwds):
29
+ self.called += 1
30
+ self.args = args
31
+ self.kwds = kwds
32
+ if isinstance(self.result, BaseException):
33
+ raise self.result
34
+ elif self.return_self:
35
+ return self
36
+ else:
37
+ return self.result
38
+
39
+
40
+ class Editor:
41
+ '''Minimally imitate editor.EditorWindow class.
42
+ '''
43
+ def __init__(self, flist=None, filename=None, key=None, root=None,
44
+ text=None): # Allow real Text with mock Editor.
45
+ self.text = text or Text()
46
+ self.undo = UndoDelegator()
47
+
48
+ def get_selection_indices(self):
49
+ first = self.text.index('1.0')
50
+ last = self.text.index('end')
51
+ return first, last
52
+
53
+
54
+ class UndoDelegator:
55
+ '''Minimally imitate undo.UndoDelegator class.
56
+ '''
57
+ # A real undo block is only needed for user interaction.
58
+ def undo_block_start(*args):
59
+ pass
60
+ def undo_block_stop(*args):
61
+ pass
llava/lib/python3.10/idlelib/idle_test/template.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Test , coverage %."
2
+
3
+ from idlelib import zzdummy
4
+ import unittest
5
+ from test.support import requires
6
+ from tkinter import Tk
7
+
8
+
9
+ class Test(unittest.TestCase):
10
+
11
+ @classmethod
12
+ def setUpClass(cls):
13
+ requires('gui')
14
+ cls.root = Tk()
15
+ cls.root.withdraw()
16
+
17
+ @classmethod
18
+ def tearDownClass(cls):
19
+ cls.root.update_idletasks()
20
+ ## for id in cls.root.tk.call('after', 'info'):
21
+ ## cls.root.after_cancel(id) # Need for EditorWindow.
22
+ cls.root.destroy()
23
+ del cls.root
24
+
25
+ def test_init(self):
26
+ self.assertTrue(True)
27
+
28
+
29
+ if __name__ == '__main__':
30
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_autocomplete.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Test autocomplete, coverage 93%."
2
+
3
+ import unittest
4
+ from unittest.mock import Mock, patch
5
+ from test.support import requires
6
+ from tkinter import Tk, Text
7
+ import os
8
+ import __main__
9
+
10
+ import idlelib.autocomplete as ac
11
+ import idlelib.autocomplete_w as acw
12
+ from idlelib.idle_test.mock_idle import Func
13
+ from idlelib.idle_test.mock_tk import Event
14
+
15
+
16
+ class DummyEditwin:
17
+ def __init__(self, root, text):
18
+ self.root = root
19
+ self.text = text
20
+ self.indentwidth = 8
21
+ self.tabwidth = 8
22
+ self.prompt_last_line = '>>>' # Currently not used by autocomplete.
23
+
24
+
25
+ class AutoCompleteTest(unittest.TestCase):
26
+
27
+ @classmethod
28
+ def setUpClass(cls):
29
+ requires('gui')
30
+ cls.root = Tk()
31
+ cls.root.withdraw()
32
+ cls.text = Text(cls.root)
33
+ cls.editor = DummyEditwin(cls.root, cls.text)
34
+
35
+ @classmethod
36
+ def tearDownClass(cls):
37
+ del cls.editor, cls.text
38
+ cls.root.update_idletasks()
39
+ cls.root.destroy()
40
+ del cls.root
41
+
42
+ def setUp(self):
43
+ self.text.delete('1.0', 'end')
44
+ self.autocomplete = ac.AutoComplete(self.editor)
45
+
46
+ def test_init(self):
47
+ self.assertEqual(self.autocomplete.editwin, self.editor)
48
+ self.assertEqual(self.autocomplete.text, self.text)
49
+
50
+ def test_make_autocomplete_window(self):
51
+ testwin = self.autocomplete._make_autocomplete_window()
52
+ self.assertIsInstance(testwin, acw.AutoCompleteWindow)
53
+
54
+ def test_remove_autocomplete_window(self):
55
+ acp = self.autocomplete
56
+ acp.autocompletewindow = m = Mock()
57
+ acp._remove_autocomplete_window()
58
+ m.hide_window.assert_called_once()
59
+ self.assertIsNone(acp.autocompletewindow)
60
+
61
+ def test_force_open_completions_event(self):
62
+ # Call _open_completions and break.
63
+ acp = self.autocomplete
64
+ open_c = Func()
65
+ acp.open_completions = open_c
66
+ self.assertEqual(acp.force_open_completions_event('event'), 'break')
67
+ self.assertEqual(open_c.args[0], ac.FORCE)
68
+
69
+ def test_autocomplete_event(self):
70
+ Equal = self.assertEqual
71
+ acp = self.autocomplete
72
+
73
+ # Result of autocomplete event: If modified tab, None.
74
+ ev = Event(mc_state=True)
75
+ self.assertIsNone(acp.autocomplete_event(ev))
76
+ del ev.mc_state
77
+
78
+ # If tab after whitespace, None.
79
+ self.text.insert('1.0', ' """Docstring.\n ')
80
+ self.assertIsNone(acp.autocomplete_event(ev))
81
+ self.text.delete('1.0', 'end')
82
+
83
+ # If active autocomplete window, complete() and 'break'.
84
+ self.text.insert('1.0', 're.')
85
+ acp.autocompletewindow = mock = Mock()
86
+ mock.is_active = Mock(return_value=True)
87
+ Equal(acp.autocomplete_event(ev), 'break')
88
+ mock.complete.assert_called_once()
89
+ acp.autocompletewindow = None
90
+
91
+ # If no active autocomplete window, open_completions(), None/break.
92
+ open_c = Func(result=False)
93
+ acp.open_completions = open_c
94
+ Equal(acp.autocomplete_event(ev), None)
95
+ Equal(open_c.args[0], ac.TAB)
96
+ open_c.result = True
97
+ Equal(acp.autocomplete_event(ev), 'break')
98
+ Equal(open_c.args[0], ac.TAB)
99
+
100
+ def test_try_open_completions_event(self):
101
+ Equal = self.assertEqual
102
+ text = self.text
103
+ acp = self.autocomplete
104
+ trycompletions = acp.try_open_completions_event
105
+ after = Func(result='after1')
106
+ acp.text.after = after
107
+
108
+ # If no text or trigger, after not called.
109
+ trycompletions()
110
+ Equal(after.called, 0)
111
+ text.insert('1.0', 're')
112
+ trycompletions()
113
+ Equal(after.called, 0)
114
+
115
+ # Attribute needed, no existing callback.
116
+ text.insert('insert', ' re.')
117
+ acp._delayed_completion_id = None
118
+ trycompletions()
119
+ Equal(acp._delayed_completion_index, text.index('insert'))
120
+ Equal(after.args,
121
+ (acp.popupwait, acp._delayed_open_completions, ac.TRY_A))
122
+ cb1 = acp._delayed_completion_id
123
+ Equal(cb1, 'after1')
124
+
125
+ # File needed, existing callback cancelled.
126
+ text.insert('insert', ' "./Lib/')
127
+ after.result = 'after2'
128
+ cancel = Func()
129
+ acp.text.after_cancel = cancel
130
+ trycompletions()
131
+ Equal(acp._delayed_completion_index, text.index('insert'))
132
+ Equal(cancel.args, (cb1,))
133
+ Equal(after.args,
134
+ (acp.popupwait, acp._delayed_open_completions, ac.TRY_F))
135
+ Equal(acp._delayed_completion_id, 'after2')
136
+
137
+ def test_delayed_open_completions(self):
138
+ Equal = self.assertEqual
139
+ acp = self.autocomplete
140
+ open_c = Func()
141
+ acp.open_completions = open_c
142
+ self.text.insert('1.0', '"dict.')
143
+
144
+ # Set autocomplete._delayed_completion_id to None.
145
+ # Text index changed, don't call open_completions.
146
+ acp._delayed_completion_id = 'after'
147
+ acp._delayed_completion_index = self.text.index('insert+1c')
148
+ acp._delayed_open_completions('dummy')
149
+ self.assertIsNone(acp._delayed_completion_id)
150
+ Equal(open_c.called, 0)
151
+
152
+ # Text index unchanged, call open_completions.
153
+ acp._delayed_completion_index = self.text.index('insert')
154
+ acp._delayed_open_completions((1, 2, 3, ac.FILES))
155
+ self.assertEqual(open_c.args[0], (1, 2, 3, ac.FILES))
156
+
157
+ def test_oc_cancel_comment(self):
158
+ none = self.assertIsNone
159
+ acp = self.autocomplete
160
+
161
+ # Comment is in neither code or string.
162
+ acp._delayed_completion_id = 'after'
163
+ after = Func(result='after')
164
+ acp.text.after_cancel = after
165
+ self.text.insert(1.0, '# comment')
166
+ none(acp.open_completions(ac.TAB)) # From 'else' after 'elif'.
167
+ none(acp._delayed_completion_id)
168
+
169
+ def test_oc_no_list(self):
170
+ acp = self.autocomplete
171
+ fetch = Func(result=([],[]))
172
+ acp.fetch_completions = fetch
173
+ self.text.insert('1.0', 'object')
174
+ self.assertIsNone(acp.open_completions(ac.TAB))
175
+ self.text.insert('insert', '.')
176
+ self.assertIsNone(acp.open_completions(ac.TAB))
177
+ self.assertEqual(fetch.called, 2)
178
+
179
+
180
+ def test_open_completions_none(self):
181
+ # Test other two None returns.
182
+ none = self.assertIsNone
183
+ acp = self.autocomplete
184
+
185
+ # No object for attributes or need call not allowed.
186
+ self.text.insert(1.0, '.')
187
+ none(acp.open_completions(ac.TAB))
188
+ self.text.insert('insert', ' int().')
189
+ none(acp.open_completions(ac.TAB))
190
+
191
+ # Blank or quote trigger 'if complete ...'.
192
+ self.text.delete(1.0, 'end')
193
+ self.assertFalse(acp.open_completions(ac.TAB))
194
+ self.text.insert('1.0', '"')
195
+ self.assertFalse(acp.open_completions(ac.TAB))
196
+ self.text.delete('1.0', 'end')
197
+
198
+ class dummy_acw:
199
+ __init__ = Func()
200
+ show_window = Func(result=False)
201
+ hide_window = Func()
202
+
203
+ def test_open_completions(self):
204
+ # Test completions of files and attributes.
205
+ acp = self.autocomplete
206
+ fetch = Func(result=(['tem'],['tem', '_tem']))
207
+ acp.fetch_completions = fetch
208
+ def make_acw(): return self.dummy_acw()
209
+ acp._make_autocomplete_window = make_acw
210
+
211
+ self.text.insert('1.0', 'int.')
212
+ acp.open_completions(ac.TAB)
213
+ self.assertIsInstance(acp.autocompletewindow, self.dummy_acw)
214
+ self.text.delete('1.0', 'end')
215
+
216
+ # Test files.
217
+ self.text.insert('1.0', '"t')
218
+ self.assertTrue(acp.open_completions(ac.TAB))
219
+ self.text.delete('1.0', 'end')
220
+
221
+ def test_completion_kwds(self):
222
+ self.assertIn('and', ac.completion_kwds)
223
+ self.assertIn('case', ac.completion_kwds)
224
+ self.assertNotIn('None', ac.completion_kwds)
225
+
226
+ def test_fetch_completions(self):
227
+ # Test that fetch_completions returns 2 lists:
228
+ # For attribute completion, a large list containing all variables, and
229
+ # a small list containing non-private variables.
230
+ # For file completion, a large list containing all files in the path,
231
+ # and a small list containing files that do not start with '.'.
232
+ acp = self.autocomplete
233
+ small, large = acp.fetch_completions(
234
+ '', ac.ATTRS)
235
+ if hasattr(__main__, '__file__') and __main__.__file__ != ac.__file__:
236
+ self.assertNotIn('AutoComplete', small) # See issue 36405.
237
+
238
+ # Test attributes
239
+ s, b = acp.fetch_completions('', ac.ATTRS)
240
+ self.assertLess(len(small), len(large))
241
+ self.assertTrue(all(filter(lambda x: x.startswith('_'), s)))
242
+ self.assertTrue(any(filter(lambda x: x.startswith('_'), b)))
243
+
244
+ # Test smalll should respect to __all__.
245
+ with patch.dict('__main__.__dict__', {'__all__': ['a', 'b']}):
246
+ s, b = acp.fetch_completions('', ac.ATTRS)
247
+ self.assertEqual(s, ['a', 'b'])
248
+ self.assertIn('__name__', b) # From __main__.__dict__.
249
+ self.assertIn('sum', b) # From __main__.__builtins__.__dict__.
250
+ self.assertIn('nonlocal', b) # From keyword.kwlist.
251
+ pos = b.index('False') # Test False not included twice.
252
+ self.assertNotEqual(b[pos+1], 'False')
253
+
254
+ # Test attributes with name entity.
255
+ mock = Mock()
256
+ mock._private = Mock()
257
+ with patch.dict('__main__.__dict__', {'foo': mock}):
258
+ s, b = acp.fetch_completions('foo', ac.ATTRS)
259
+ self.assertNotIn('_private', s)
260
+ self.assertIn('_private', b)
261
+ self.assertEqual(s, [i for i in sorted(dir(mock)) if i[:1] != '_'])
262
+ self.assertEqual(b, sorted(dir(mock)))
263
+
264
+ # Test files
265
+ def _listdir(path):
266
+ # This will be patch and used in fetch_completions.
267
+ if path == '.':
268
+ return ['foo', 'bar', '.hidden']
269
+ return ['monty', 'python', '.hidden']
270
+
271
+ with patch.object(os, 'listdir', _listdir):
272
+ s, b = acp.fetch_completions('', ac.FILES)
273
+ self.assertEqual(s, ['bar', 'foo'])
274
+ self.assertEqual(b, ['.hidden', 'bar', 'foo'])
275
+
276
+ s, b = acp.fetch_completions('~', ac.FILES)
277
+ self.assertEqual(s, ['monty', 'python'])
278
+ self.assertEqual(b, ['.hidden', 'monty', 'python'])
279
+
280
+ def test_get_entity(self):
281
+ # Test that a name is in the namespace of sys.modules and
282
+ # __main__.__dict__.
283
+ acp = self.autocomplete
284
+ Equal = self.assertEqual
285
+
286
+ Equal(acp.get_entity('int'), int)
287
+
288
+ # Test name from sys.modules.
289
+ mock = Mock()
290
+ with patch.dict('sys.modules', {'tempfile': mock}):
291
+ Equal(acp.get_entity('tempfile'), mock)
292
+
293
+ # Test name from __main__.__dict__.
294
+ di = {'foo': 10, 'bar': 20}
295
+ with patch.dict('__main__.__dict__', {'d': di}):
296
+ Equal(acp.get_entity('d'), di)
297
+
298
+ # Test name not in namespace.
299
+ with patch.dict('__main__.__dict__', {}):
300
+ with self.assertRaises(NameError):
301
+ acp.get_entity('not_exist')
302
+
303
+
304
+ if __name__ == '__main__':
305
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_autocomplete_w.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Test autocomplete_w, coverage 11%."
2
+
3
+ import unittest
4
+ from test.support import requires
5
+ from tkinter import Tk, Text
6
+
7
+ import idlelib.autocomplete_w as acw
8
+
9
+
10
+ class AutoCompleteWindowTest(unittest.TestCase):
11
+
12
+ @classmethod
13
+ def setUpClass(cls):
14
+ requires('gui')
15
+ cls.root = Tk()
16
+ cls.root.withdraw()
17
+ cls.text = Text(cls.root)
18
+ cls.acw = acw.AutoCompleteWindow(cls.text, tags=None)
19
+
20
+ @classmethod
21
+ def tearDownClass(cls):
22
+ del cls.text, cls.acw
23
+ cls.root.update_idletasks()
24
+ cls.root.destroy()
25
+ del cls.root
26
+
27
+ def test_init(self):
28
+ self.assertEqual(self.acw.widget, self.text)
29
+
30
+
31
+ if __name__ == '__main__':
32
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_autoexpand.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Test autoexpand, coverage 100%."
2
+
3
+ from idlelib.autoexpand import AutoExpand
4
+ import unittest
5
+ from test.support import requires
6
+ from tkinter import Text, Tk
7
+
8
+
9
+ class DummyEditwin:
10
+ # AutoExpand.__init__ only needs .text
11
+ def __init__(self, text):
12
+ self.text = text
13
+
14
+ class AutoExpandTest(unittest.TestCase):
15
+
16
+ @classmethod
17
+ def setUpClass(cls):
18
+ requires('gui')
19
+ cls.tk = Tk()
20
+ cls.text = Text(cls.tk)
21
+ cls.auto_expand = AutoExpand(DummyEditwin(cls.text))
22
+ cls.auto_expand.bell = lambda: None
23
+
24
+ # If mock_tk.Text._decode understood indexes 'insert' with suffixed 'linestart',
25
+ # 'wordstart', and 'lineend', used by autoexpand, we could use the following
26
+ # to run these test on non-gui machines (but check bell).
27
+ ## try:
28
+ ## requires('gui')
29
+ ## #raise ResourceDenied() # Uncomment to test mock.
30
+ ## except ResourceDenied:
31
+ ## from idlelib.idle_test.mock_tk import Text
32
+ ## cls.text = Text()
33
+ ## cls.text.bell = lambda: None
34
+ ## else:
35
+ ## from tkinter import Tk, Text
36
+ ## cls.tk = Tk()
37
+ ## cls.text = Text(cls.tk)
38
+
39
+ @classmethod
40
+ def tearDownClass(cls):
41
+ del cls.text, cls.auto_expand
42
+ if hasattr(cls, 'tk'):
43
+ cls.tk.destroy()
44
+ del cls.tk
45
+
46
+ def tearDown(self):
47
+ self.text.delete('1.0', 'end')
48
+
49
+ def test_get_prevword(self):
50
+ text = self.text
51
+ previous = self.auto_expand.getprevword
52
+ equal = self.assertEqual
53
+
54
+ equal(previous(), '')
55
+
56
+ text.insert('insert', 't')
57
+ equal(previous(), 't')
58
+
59
+ text.insert('insert', 'his')
60
+ equal(previous(), 'this')
61
+
62
+ text.insert('insert', ' ')
63
+ equal(previous(), '')
64
+
65
+ text.insert('insert', 'is')
66
+ equal(previous(), 'is')
67
+
68
+ text.insert('insert', '\nsample\nstring')
69
+ equal(previous(), 'string')
70
+
71
+ text.delete('3.0', 'insert')
72
+ equal(previous(), '')
73
+
74
+ text.delete('1.0', 'end')
75
+ equal(previous(), '')
76
+
77
+ def test_before_only(self):
78
+ previous = self.auto_expand.getprevword
79
+ expand = self.auto_expand.expand_word_event
80
+ equal = self.assertEqual
81
+
82
+ self.text.insert('insert', 'ab ac bx ad ab a')
83
+ equal(self.auto_expand.getwords(), ['ab', 'ad', 'ac', 'a'])
84
+ expand('event')
85
+ equal(previous(), 'ab')
86
+ expand('event')
87
+ equal(previous(), 'ad')
88
+ expand('event')
89
+ equal(previous(), 'ac')
90
+ expand('event')
91
+ equal(previous(), 'a')
92
+
93
+ def test_after_only(self):
94
+ # Also add punctuation 'noise' that should be ignored.
95
+ text = self.text
96
+ previous = self.auto_expand.getprevword
97
+ expand = self.auto_expand.expand_word_event
98
+ equal = self.assertEqual
99
+
100
+ text.insert('insert', 'a, [ab] ac: () bx"" cd ac= ad ya')
101
+ text.mark_set('insert', '1.1')
102
+ equal(self.auto_expand.getwords(), ['ab', 'ac', 'ad', 'a'])
103
+ expand('event')
104
+ equal(previous(), 'ab')
105
+ expand('event')
106
+ equal(previous(), 'ac')
107
+ expand('event')
108
+ equal(previous(), 'ad')
109
+ expand('event')
110
+ equal(previous(), 'a')
111
+
112
+ def test_both_before_after(self):
113
+ text = self.text
114
+ previous = self.auto_expand.getprevword
115
+ expand = self.auto_expand.expand_word_event
116
+ equal = self.assertEqual
117
+
118
+ text.insert('insert', 'ab xy yz\n')
119
+ text.insert('insert', 'a ac by ac')
120
+
121
+ text.mark_set('insert', '2.1')
122
+ equal(self.auto_expand.getwords(), ['ab', 'ac', 'a'])
123
+ expand('event')
124
+ equal(previous(), 'ab')
125
+ expand('event')
126
+ equal(previous(), 'ac')
127
+ expand('event')
128
+ equal(previous(), 'a')
129
+
130
+ def test_other_expand_cases(self):
131
+ text = self.text
132
+ expand = self.auto_expand.expand_word_event
133
+ equal = self.assertEqual
134
+
135
+ # no expansion candidate found
136
+ equal(self.auto_expand.getwords(), [])
137
+ equal(expand('event'), 'break')
138
+
139
+ text.insert('insert', 'bx cy dz a')
140
+ equal(self.auto_expand.getwords(), [])
141
+
142
+ # reset state by successfully expanding once
143
+ # move cursor to another position and expand again
144
+ text.insert('insert', 'ac xy a ac ad a')
145
+ text.mark_set('insert', '1.7')
146
+ expand('event')
147
+ initial_state = self.auto_expand.state
148
+ text.mark_set('insert', '1.end')
149
+ expand('event')
150
+ new_state = self.auto_expand.state
151
+ self.assertNotEqual(initial_state, new_state)
152
+
153
+
154
+ if __name__ == '__main__':
155
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_calltip.py ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
11
+
12
+ # Test Class TC is used in multiple get_argspec test methods
13
+ class TC:
14
+ 'doc'
15
+ tip = "(ai=None, *b)"
16
+ def __init__(self, ai=None, *b): 'doc'
17
+ __init__.tip = "(self, ai=None, *b)"
18
+ def t1(self): 'doc'
19
+ t1.tip = "(self)"
20
+ def t2(self, ai, b=None): 'doc'
21
+ t2.tip = "(self, ai, b=None)"
22
+ def t3(self, ai, *args): 'doc'
23
+ t3.tip = "(self, ai, *args)"
24
+ def t4(self, *args): 'doc'
25
+ t4.tip = "(self, *args)"
26
+ def t5(self, ai, b=None, *args, **kw): 'doc'
27
+ t5.tip = "(self, ai, b=None, *args, **kw)"
28
+ def t6(no, self): 'doc'
29
+ t6.tip = "(no, self)"
30
+ def __call__(self, ci): 'doc'
31
+ __call__.tip = "(self, ci)"
32
+ def nd(self): pass # No doc.
33
+ # attaching .tip to wrapped methods does not work
34
+ @classmethod
35
+ def cm(cls, a): 'doc'
36
+ @staticmethod
37
+ def sm(b): 'doc'
38
+
39
+
40
+ tc = TC()
41
+ default_tip = calltip._default_callable_argspec
42
+ get_spec = calltip.get_argspec
43
+
44
+
45
+ class Get_argspecTest(unittest.TestCase):
46
+ # The get_spec function must return a string, even if blank.
47
+ # Test a variety of objects to be sure that none cause it to raise
48
+ # (quite aside from getting as correct an answer as possible).
49
+ # The tests of builtins may break if inspect or the docstrings change,
50
+ # but a red buildbot is better than a user crash (as has happened).
51
+ # For a simple mismatch, change the expected output to the actual.
52
+
53
+ def test_builtins(self):
54
+
55
+ def tiptest(obj, out):
56
+ self.assertEqual(get_spec(obj), out)
57
+
58
+ # Python class that inherits builtin methods
59
+ class List(list): "List() doc"
60
+
61
+ # Simulate builtin with no docstring for default tip test
62
+ class SB: __call__ = None
63
+
64
+ if List.__doc__ is not None:
65
+ tiptest(List,
66
+ f'(iterable=(), /)'
67
+ f'\n{List.__doc__}')
68
+ tiptest(list.__new__,
69
+ '(*args, **kwargs)\n'
70
+ 'Create and return a new object. '
71
+ 'See help(type) for accurate signature.')
72
+ tiptest(list.__init__,
73
+ '(self, /, *args, **kwargs)\n'
74
+ 'Initialize self. See help(type(self)) for accurate signature.')
75
+ append_doc = "\nAppend object to the end of the list."
76
+ tiptest(list.append, '(self, object, /)' + append_doc)
77
+ tiptest(List.append, '(self, object, /)' + append_doc)
78
+ tiptest([].append, '(object, /)' + append_doc)
79
+
80
+ tiptest(types.MethodType, "method(function, instance)")
81
+ tiptest(SB(), default_tip)
82
+
83
+ p = re.compile('')
84
+ tiptest(re.sub, '''\
85
+ (pattern, repl, string, count=0, flags=0)
86
+ Return the string obtained by replacing the leftmost
87
+ non-overlapping occurrences of the pattern in string by the
88
+ replacement repl. repl can be either a string or a callable;
89
+ if a string, backslash escapes in it are processed. If it is
90
+ a callable, it's passed the Match object and must return''')
91
+ tiptest(p.sub, '''\
92
+ (repl, string, count=0)
93
+ Return the string obtained by replacing the leftmost \
94
+ non-overlapping occurrences o...''')
95
+
96
+ def test_signature_wrap(self):
97
+ if textwrap.TextWrapper.__doc__ is not None:
98
+ self.assertEqual(get_spec(textwrap.TextWrapper), '''\
99
+ (width=70, initial_indent='', subsequent_indent='', expand_tabs=True,
100
+ replace_whitespace=True, fix_sentence_endings=False, break_long_words=True,
101
+ drop_whitespace=True, break_on_hyphens=True, tabsize=8, *, max_lines=None,
102
+ placeholder=' [...]')
103
+ Object for wrapping/filling text. The public interface consists of
104
+ the wrap() and fill() methods; the other methods are just there for
105
+ subclasses to override in order to tweak the default behaviour.
106
+ If you want to completely replace the main wrapping algorithm,
107
+ you\'ll probably have to override _wrap_chunks().''')
108
+
109
+ def test_properly_formatted(self):
110
+
111
+ def foo(s='a'*100):
112
+ pass
113
+
114
+ def bar(s='a'*100):
115
+ """Hello Guido"""
116
+ pass
117
+
118
+ def baz(s='a'*100, z='b'*100):
119
+ pass
120
+
121
+ indent = calltip._INDENT
122
+
123
+ sfoo = "(s='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"\
124
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + indent + "aaaaaaaaa"\
125
+ "aaaaaaaaaa')"
126
+ sbar = "(s='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"\
127
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + indent + "aaaaaaaaa"\
128
+ "aaaaaaaaaa')\nHello Guido"
129
+ sbaz = "(s='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"\
130
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + indent + "aaaaaaaaa"\
131
+ "aaaaaaaaaa', z='bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"\
132
+ "bbbbbbbbbbbbbbbbb\n" + indent + "bbbbbbbbbbbbbbbbbbbbbb"\
133
+ "bbbbbbbbbbbbbbbbbbbbbb')"
134
+
135
+ for func,doc in [(foo, sfoo), (bar, sbar), (baz, sbaz)]:
136
+ with self.subTest(func=func, doc=doc):
137
+ self.assertEqual(get_spec(func), doc)
138
+
139
+ def test_docline_truncation(self):
140
+ def f(): pass
141
+ f.__doc__ = 'a'*300
142
+ self.assertEqual(get_spec(f), f"()\n{'a'*(calltip._MAX_COLS-3) + '...'}")
143
+
144
+ def test_multiline_docstring(self):
145
+ # Test fewer lines than max.
146
+ self.assertEqual(get_spec(range),
147
+ "range(stop) -> range object\n"
148
+ "range(start, stop[, step]) -> range object")
149
+
150
+ # Test max lines
151
+ self.assertEqual(get_spec(bytes), '''\
152
+ bytes(iterable_of_ints) -> bytes
153
+ bytes(string, encoding[, errors]) -> bytes
154
+ bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
155
+ bytes(int) -> bytes object of size given by the parameter initialized with null bytes
156
+ bytes() -> empty bytes object''')
157
+
158
+ # Test more than max lines
159
+ def f(): pass
160
+ f.__doc__ = 'a\n' * 15
161
+ self.assertEqual(get_spec(f), '()' + '\na' * calltip._MAX_LINES)
162
+
163
+ def test_functions(self):
164
+ def t1(): 'doc'
165
+ t1.tip = "()"
166
+ def t2(a, b=None): 'doc'
167
+ t2.tip = "(a, b=None)"
168
+ def t3(a, *args): 'doc'
169
+ t3.tip = "(a, *args)"
170
+ def t4(*args): 'doc'
171
+ t4.tip = "(*args)"
172
+ def t5(a, b=None, *args, **kw): 'doc'
173
+ t5.tip = "(a, b=None, *args, **kw)"
174
+
175
+ doc = '\ndoc' if t1.__doc__ is not None else ''
176
+ for func in (t1, t2, t3, t4, t5, TC):
177
+ with self.subTest(func=func):
178
+ self.assertEqual(get_spec(func), func.tip + doc)
179
+
180
+ def test_methods(self):
181
+ doc = '\ndoc' if TC.__doc__ is not None else ''
182
+ for meth in (TC.t1, TC.t2, TC.t3, TC.t4, TC.t5, TC.t6, TC.__call__):
183
+ with self.subTest(meth=meth):
184
+ self.assertEqual(get_spec(meth), meth.tip + doc)
185
+ self.assertEqual(get_spec(TC.cm), "(a)" + doc)
186
+ self.assertEqual(get_spec(TC.sm), "(b)" + doc)
187
+
188
+ def test_bound_methods(self):
189
+ # test that first parameter is correctly removed from argspec
190
+ doc = '\ndoc' if TC.__doc__ is not None else ''
191
+ for meth, mtip in ((tc.t1, "()"), (tc.t4, "(*args)"),
192
+ (tc.t6, "(self)"), (tc.__call__, '(ci)'),
193
+ (tc, '(ci)'), (TC.cm, "(a)"),):
194
+ with self.subTest(meth=meth, mtip=mtip):
195
+ self.assertEqual(get_spec(meth), mtip + doc)
196
+
197
+ def test_starred_parameter(self):
198
+ # test that starred first parameter is *not* removed from argspec
199
+ class C:
200
+ def m1(*args): pass
201
+ c = C()
202
+ for meth, mtip in ((C.m1, '(*args)'), (c.m1, "(*args)"),):
203
+ with self.subTest(meth=meth, mtip=mtip):
204
+ self.assertEqual(get_spec(meth), mtip)
205
+
206
+ def test_invalid_method_get_spec(self):
207
+ class C:
208
+ def m2(**kwargs): pass
209
+ class Test:
210
+ def __call__(*, a): pass
211
+
212
+ mtip = calltip._invalid_method
213
+ self.assertEqual(get_spec(C().m2), mtip)
214
+ self.assertEqual(get_spec(Test()), mtip)
215
+
216
+ def test_non_ascii_name(self):
217
+ # test that re works to delete a first parameter name that
218
+ # includes non-ascii chars, such as various forms of A.
219
+ uni = "(A\u0391\u0410\u05d0\u0627\u0905\u1e00\u3042, a)"
220
+ assert calltip._first_param.sub('', uni) == '(a)'
221
+
222
+ def test_no_docstring(self):
223
+ for meth, mtip in ((TC.nd, "(self)"), (tc.nd, "()")):
224
+ with self.subTest(meth=meth, mtip=mtip):
225
+ self.assertEqual(get_spec(meth), mtip)
226
+
227
+ def test_buggy_getattr_class(self):
228
+ class NoCall:
229
+ def __getattr__(self, name): # Not invoked for class attribute.
230
+ raise IndexError # Bug.
231
+ class CallA(NoCall):
232
+ def __call__(self, ci): # Bug does not matter.
233
+ pass
234
+ class CallB(NoCall):
235
+ def __call__(oui, a, b, c): # Non-standard 'self'.
236
+ pass
237
+
238
+ for meth, mtip in ((NoCall, default_tip), (CallA, default_tip),
239
+ (NoCall(), ''), (CallA(), '(ci)'),
240
+ (CallB(), '(a, b, c)')):
241
+ with self.subTest(meth=meth, mtip=mtip):
242
+ self.assertEqual(get_spec(meth), mtip)
243
+
244
+ def test_metaclass_class(self): # Failure case for issue 38689.
245
+ class Type(type): # Type() requires 3 type args, returns class.
246
+ __class__ = property({}.__getitem__, {}.__setitem__)
247
+ class Object(metaclass=Type):
248
+ __slots__ = '__class__'
249
+ for meth, mtip in ((Type, get_spec(type)), (Object, default_tip),
250
+ (Object(), '')):
251
+ with self.subTest(meth=meth, mtip=mtip):
252
+ self.assertEqual(get_spec(meth), mtip)
253
+
254
+ def test_non_callables(self):
255
+ for obj in (0, 0.0, '0', b'0', [], {}):
256
+ with self.subTest(obj=obj):
257
+ self.assertEqual(get_spec(obj), '')
258
+
259
+
260
+ class Get_entityTest(unittest.TestCase):
261
+ def test_bad_entity(self):
262
+ self.assertIsNone(calltip.get_entity('1/0'))
263
+ def test_good_entity(self):
264
+ self.assertIs(calltip.get_entity('int'), int)
265
+
266
+
267
+ # Test the 9 Calltip methods.
268
+ # open_calltip is about half the code; the others are fairly trivial.
269
+ # The default mocks are what are needed for open_calltip.
270
+
271
+ class mock_Shell:
272
+ "Return mock sufficient to pass to hyperparser."
273
+ def __init__(self, text):
274
+ text.tag_prevrange = Mock(return_value=None)
275
+ self.text = text
276
+ self.prompt_last_line = ">>> "
277
+ self.indentwidth = 4
278
+ self.tabwidth = 8
279
+
280
+
281
+ class mock_TipWindow:
282
+ def __init__(self):
283
+ pass
284
+
285
+ def showtip(self, text, parenleft, parenright):
286
+ self.args = parenleft, parenright
287
+ self.parenline, self.parencol = map(int, parenleft.split('.'))
288
+
289
+
290
+ class WrappedCalltip(calltip.Calltip):
291
+ def _make_tk_calltip_window(self):
292
+ return mock_TipWindow()
293
+
294
+ def remove_calltip_window(self, event=None):
295
+ if self.active_calltip: # Setup to None.
296
+ self.active_calltip = None
297
+ self.tips_removed += 1 # Setup to 0.
298
+
299
+ def fetch_tip(self, expression):
300
+ return 'tip'
301
+
302
+
303
+ class CalltipTest(unittest.TestCase):
304
+
305
+ @classmethod
306
+ def setUpClass(cls):
307
+ cls.text = Text()
308
+ cls.ct = WrappedCalltip(mock_Shell(cls.text))
309
+
310
+ def setUp(self):
311
+ self.text.delete('1.0', 'end') # Insert and call
312
+ self.ct.active_calltip = None
313
+ # Test .active_calltip, +args
314
+ self.ct.tips_removed = 0
315
+
316
+ def open_close(self, testfunc):
317
+ # Open-close template with testfunc called in between.
318
+ opentip = self.ct.open_calltip
319
+ self.text.insert(1.0, 'f(')
320
+ opentip(False)
321
+ self.tip = self.ct.active_calltip
322
+ testfunc(self) ###
323
+ self.text.insert('insert', ')')
324
+ opentip(False)
325
+ self.assertIsNone(self.ct.active_calltip, None)
326
+
327
+ def test_open_close(self):
328
+ def args(self):
329
+ self.assertEqual(self.tip.args, ('1.1', '1.end'))
330
+ self.open_close(args)
331
+
332
+ def test_repeated_force(self):
333
+ def force(self):
334
+ for char in 'abc':
335
+ self.text.insert('insert', 'a')
336
+ self.ct.open_calltip(True)
337
+ self.ct.open_calltip(True)
338
+ self.assertIs(self.ct.active_calltip, self.tip)
339
+ self.open_close(force)
340
+
341
+ def test_repeated_parens(self):
342
+ def parens(self):
343
+ for context in "a", "'":
344
+ with self.subTest(context=context):
345
+ self.text.insert('insert', context)
346
+ for char in '(()())':
347
+ self.text.insert('insert', char)
348
+ self.assertIs(self.ct.active_calltip, self.tip)
349
+ self.text.insert('insert', "'")
350
+ self.open_close(parens)
351
+
352
+ def test_comment_parens(self):
353
+ def comment(self):
354
+ self.text.insert('insert', "# ")
355
+ for char in '(()())':
356
+ self.text.insert('insert', char)
357
+ self.assertIs(self.ct.active_calltip, self.tip)
358
+ self.text.insert('insert', "\n")
359
+ self.open_close(comment)
360
+
361
+
362
+ if __name__ == '__main__':
363
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_calltip_w.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Test calltip_w, coverage 18%."
2
+
3
+ from idlelib import calltip_w
4
+ import unittest
5
+ from test.support import requires
6
+ from tkinter import Tk, Text
7
+
8
+
9
+ class CallTipWindowTest(unittest.TestCase):
10
+
11
+ @classmethod
12
+ def setUpClass(cls):
13
+ requires('gui')
14
+ cls.root = Tk()
15
+ cls.root.withdraw()
16
+ cls.text = Text(cls.root)
17
+ cls.calltip = calltip_w.CalltipWindow(cls.text)
18
+
19
+ @classmethod
20
+ def tearDownClass(cls):
21
+ cls.root.update_idletasks()
22
+ cls.root.destroy()
23
+ del cls.text, cls.root
24
+
25
+ def test_init(self):
26
+ self.assertEqual(self.calltip.anchor_widget, self.text)
27
+
28
+ if __name__ == '__main__':
29
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_codecontext.py ADDED
@@ -0,0 +1,455 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Test codecontext, coverage 100%"
2
+
3
+ from idlelib import codecontext
4
+ import unittest
5
+ import unittest.mock
6
+ from test.support import requires
7
+ from tkinter import NSEW, Tk, Frame, Text, TclError
8
+
9
+ from unittest import mock
10
+ import re
11
+ from idlelib import config
12
+
13
+
14
+ usercfg = codecontext.idleConf.userCfg
15
+ testcfg = {
16
+ 'main': config.IdleUserConfParser(''),
17
+ 'highlight': config.IdleUserConfParser(''),
18
+ 'keys': config.IdleUserConfParser(''),
19
+ 'extensions': config.IdleUserConfParser(''),
20
+ }
21
+ code_sample = """\
22
+
23
+ class C1:
24
+ # Class comment.
25
+ def __init__(self, a, b):
26
+ self.a = a
27
+ self.b = b
28
+ def compare(self):
29
+ if a > b:
30
+ return a
31
+ elif a < b:
32
+ return b
33
+ else:
34
+ return None
35
+ """
36
+
37
+
38
+ class DummyEditwin:
39
+ def __init__(self, root, frame, text):
40
+ self.root = root
41
+ self.top = root
42
+ self.text_frame = frame
43
+ self.text = text
44
+ self.label = ''
45
+
46
+ def getlineno(self, index):
47
+ return int(float(self.text.index(index)))
48
+
49
+ def update_menu_label(self, **kwargs):
50
+ self.label = kwargs['label']
51
+
52
+
53
+ class CodeContextTest(unittest.TestCase):
54
+
55
+ @classmethod
56
+ def setUpClass(cls):
57
+ requires('gui')
58
+ root = cls.root = Tk()
59
+ root.withdraw()
60
+ frame = cls.frame = Frame(root)
61
+ text = cls.text = Text(frame)
62
+ text.insert('1.0', code_sample)
63
+ # Need to pack for creation of code context text widget.
64
+ frame.pack(side='left', fill='both', expand=1)
65
+ text.grid(row=1, column=1, sticky=NSEW)
66
+ cls.editor = DummyEditwin(root, frame, text)
67
+ codecontext.idleConf.userCfg = testcfg
68
+
69
+ @classmethod
70
+ def tearDownClass(cls):
71
+ codecontext.idleConf.userCfg = usercfg
72
+ cls.editor.text.delete('1.0', 'end')
73
+ del cls.editor, cls.frame, cls.text
74
+ cls.root.update_idletasks()
75
+ cls.root.destroy()
76
+ del cls.root
77
+
78
+ def setUp(self):
79
+ self.text.yview(0)
80
+ self.text['font'] = 'TkFixedFont'
81
+ self.cc = codecontext.CodeContext(self.editor)
82
+
83
+ self.highlight_cfg = {"background": '#abcdef',
84
+ "foreground": '#123456'}
85
+ orig_idleConf_GetHighlight = codecontext.idleConf.GetHighlight
86
+ def mock_idleconf_GetHighlight(theme, element):
87
+ if element == 'context':
88
+ return self.highlight_cfg
89
+ return orig_idleConf_GetHighlight(theme, element)
90
+ GetHighlight_patcher = unittest.mock.patch.object(
91
+ codecontext.idleConf, 'GetHighlight', mock_idleconf_GetHighlight)
92
+ GetHighlight_patcher.start()
93
+ self.addCleanup(GetHighlight_patcher.stop)
94
+
95
+ self.font_override = 'TkFixedFont'
96
+ def mock_idleconf_GetFont(root, configType, section):
97
+ return self.font_override
98
+ GetFont_patcher = unittest.mock.patch.object(
99
+ codecontext.idleConf, 'GetFont', mock_idleconf_GetFont)
100
+ GetFont_patcher.start()
101
+ self.addCleanup(GetFont_patcher.stop)
102
+
103
+ def tearDown(self):
104
+ if self.cc.context:
105
+ self.cc.context.destroy()
106
+ # Explicitly call __del__ to remove scheduled scripts.
107
+ self.cc.__del__()
108
+ del self.cc.context, self.cc
109
+
110
+ def test_init(self):
111
+ eq = self.assertEqual
112
+ ed = self.editor
113
+ cc = self.cc
114
+
115
+ eq(cc.editwin, ed)
116
+ eq(cc.text, ed.text)
117
+ eq(cc.text['font'], ed.text['font'])
118
+ self.assertIsNone(cc.context)
119
+ eq(cc.info, [(0, -1, '', False)])
120
+ eq(cc.topvisible, 1)
121
+ self.assertIsNone(self.cc.t1)
122
+
123
+ def test_del(self):
124
+ self.cc.__del__()
125
+
126
+ def test_del_with_timer(self):
127
+ timer = self.cc.t1 = self.text.after(10000, lambda: None)
128
+ self.cc.__del__()
129
+ with self.assertRaises(TclError) as cm:
130
+ self.root.tk.call('after', 'info', timer)
131
+ self.assertIn("doesn't exist", str(cm.exception))
132
+
133
+ def test_reload(self):
134
+ codecontext.CodeContext.reload()
135
+ self.assertEqual(self.cc.context_depth, 15)
136
+
137
+ def test_toggle_code_context_event(self):
138
+ eq = self.assertEqual
139
+ cc = self.cc
140
+ toggle = cc.toggle_code_context_event
141
+
142
+ # Make sure code context is off.
143
+ if cc.context:
144
+ toggle()
145
+
146
+ # Toggle on.
147
+ toggle()
148
+ self.assertIsNotNone(cc.context)
149
+ eq(cc.context['font'], self.text['font'])
150
+ eq(cc.context['fg'], self.highlight_cfg['foreground'])
151
+ eq(cc.context['bg'], self.highlight_cfg['background'])
152
+ eq(cc.context.get('1.0', 'end-1c'), '')
153
+ eq(cc.editwin.label, 'Hide Code Context')
154
+ eq(self.root.tk.call('after', 'info', self.cc.t1)[1], 'timer')
155
+
156
+ # Toggle off.
157
+ toggle()
158
+ self.assertIsNone(cc.context)
159
+ eq(cc.editwin.label, 'Show Code Context')
160
+ self.assertIsNone(self.cc.t1)
161
+
162
+ # Scroll down and toggle back on.
163
+ line11_context = '\n'.join(x[2] for x in cc.get_context(11)[0])
164
+ cc.text.yview(11)
165
+ toggle()
166
+ eq(cc.context.get('1.0', 'end-1c'), line11_context)
167
+
168
+ # Toggle off and on again.
169
+ toggle()
170
+ toggle()
171
+ eq(cc.context.get('1.0', 'end-1c'), line11_context)
172
+
173
+ def test_get_context(self):
174
+ eq = self.assertEqual
175
+ gc = self.cc.get_context
176
+
177
+ # stopline must be greater than 0.
178
+ with self.assertRaises(AssertionError):
179
+ gc(1, stopline=0)
180
+
181
+ eq(gc(3), ([(2, 0, 'class C1:', 'class')], 0))
182
+
183
+ # Don't return comment.
184
+ eq(gc(4), ([(2, 0, 'class C1:', 'class')], 0))
185
+
186
+ # Two indentation levels and no comment.
187
+ eq(gc(5), ([(2, 0, 'class C1:', 'class'),
188
+ (4, 4, ' def __init__(self, a, b):', 'def')], 0))
189
+
190
+ # Only one 'def' is returned, not both at the same indent level.
191
+ eq(gc(10), ([(2, 0, 'class C1:', 'class'),
192
+ (7, 4, ' def compare(self):', 'def'),
193
+ (8, 8, ' if a > b:', 'if')], 0))
194
+
195
+ # With 'elif', also show the 'if' even though it's at the same level.
196
+ eq(gc(11), ([(2, 0, 'class C1:', 'class'),
197
+ (7, 4, ' def compare(self):', 'def'),
198
+ (8, 8, ' if a > b:', 'if'),
199
+ (10, 8, ' elif a < b:', 'elif')], 0))
200
+
201
+ # Set stop_line to not go back to first line in source code.
202
+ # Return includes stop_line.
203
+ eq(gc(11, stopline=2), ([(2, 0, 'class C1:', 'class'),
204
+ (7, 4, ' def compare(self):', 'def'),
205
+ (8, 8, ' if a > b:', 'if'),
206
+ (10, 8, ' elif a < b:', 'elif')], 0))
207
+ eq(gc(11, stopline=3), ([(7, 4, ' def compare(self):', 'def'),
208
+ (8, 8, ' if a > b:', 'if'),
209
+ (10, 8, ' elif a < b:', 'elif')], 4))
210
+ eq(gc(11, stopline=8), ([(8, 8, ' if a > b:', 'if'),
211
+ (10, 8, ' elif a < b:', 'elif')], 8))
212
+
213
+ # Set stop_indent to test indent level to stop at.
214
+ eq(gc(11, stopindent=4), ([(7, 4, ' def compare(self):', 'def'),
215
+ (8, 8, ' if a > b:', 'if'),
216
+ (10, 8, ' elif a < b:', 'elif')], 4))
217
+ # Check that the 'if' is included.
218
+ eq(gc(11, stopindent=8), ([(8, 8, ' if a > b:', 'if'),
219
+ (10, 8, ' elif a < b:', 'elif')], 8))
220
+
221
+ def test_update_code_context(self):
222
+ eq = self.assertEqual
223
+ cc = self.cc
224
+ # Ensure code context is active.
225
+ if not cc.context:
226
+ cc.toggle_code_context_event()
227
+
228
+ # Invoke update_code_context without scrolling - nothing happens.
229
+ self.assertIsNone(cc.update_code_context())
230
+ eq(cc.info, [(0, -1, '', False)])
231
+ eq(cc.topvisible, 1)
232
+
233
+ # Scroll down to line 1.
234
+ cc.text.yview(1)
235
+ cc.update_code_context()
236
+ eq(cc.info, [(0, -1, '', False)])
237
+ eq(cc.topvisible, 2)
238
+ eq(cc.context.get('1.0', 'end-1c'), '')
239
+
240
+ # Scroll down to line 2.
241
+ cc.text.yview(2)
242
+ cc.update_code_context()
243
+ eq(cc.info, [(0, -1, '', False), (2, 0, 'class C1:', 'class')])
244
+ eq(cc.topvisible, 3)
245
+ eq(cc.context.get('1.0', 'end-1c'), 'class C1:')
246
+
247
+ # Scroll down to line 3. Since it's a comment, nothing changes.
248
+ cc.text.yview(3)
249
+ cc.update_code_context()
250
+ eq(cc.info, [(0, -1, '', False), (2, 0, 'class C1:', 'class')])
251
+ eq(cc.topvisible, 4)
252
+ eq(cc.context.get('1.0', 'end-1c'), 'class C1:')
253
+
254
+ # Scroll down to line 4.
255
+ cc.text.yview(4)
256
+ cc.update_code_context()
257
+ eq(cc.info, [(0, -1, '', False),
258
+ (2, 0, 'class C1:', 'class'),
259
+ (4, 4, ' def __init__(self, a, b):', 'def')])
260
+ eq(cc.topvisible, 5)
261
+ eq(cc.context.get('1.0', 'end-1c'), 'class C1:\n'
262
+ ' def __init__(self, a, b):')
263
+
264
+ # Scroll down to line 11. Last 'def' is removed.
265
+ cc.text.yview(11)
266
+ cc.update_code_context()
267
+ eq(cc.info, [(0, -1, '', False),
268
+ (2, 0, 'class C1:', 'class'),
269
+ (7, 4, ' def compare(self):', 'def'),
270
+ (8, 8, ' if a > b:', 'if'),
271
+ (10, 8, ' elif a < b:', 'elif')])
272
+ eq(cc.topvisible, 12)
273
+ eq(cc.context.get('1.0', 'end-1c'), 'class C1:\n'
274
+ ' def compare(self):\n'
275
+ ' if a > b:\n'
276
+ ' elif a < b:')
277
+
278
+ # No scroll. No update, even though context_depth changed.
279
+ cc.update_code_context()
280
+ cc.context_depth = 1
281
+ eq(cc.info, [(0, -1, '', False),
282
+ (2, 0, 'class C1:', 'class'),
283
+ (7, 4, ' def compare(self):', 'def'),
284
+ (8, 8, ' if a > b:', 'if'),
285
+ (10, 8, ' elif a < b:', 'elif')])
286
+ eq(cc.topvisible, 12)
287
+ eq(cc.context.get('1.0', 'end-1c'), 'class C1:\n'
288
+ ' def compare(self):\n'
289
+ ' if a > b:\n'
290
+ ' elif a < b:')
291
+
292
+ # Scroll up.
293
+ cc.text.yview(5)
294
+ cc.update_code_context()
295
+ eq(cc.info, [(0, -1, '', False),
296
+ (2, 0, 'class C1:', 'class'),
297
+ (4, 4, ' def __init__(self, a, b):', 'def')])
298
+ eq(cc.topvisible, 6)
299
+ # context_depth is 1.
300
+ eq(cc.context.get('1.0', 'end-1c'), ' def __init__(self, a, b):')
301
+
302
+ def test_jumptoline(self):
303
+ eq = self.assertEqual
304
+ cc = self.cc
305
+ jump = cc.jumptoline
306
+
307
+ if not cc.context:
308
+ cc.toggle_code_context_event()
309
+
310
+ # Empty context.
311
+ cc.text.yview('2.0')
312
+ cc.update_code_context()
313
+ eq(cc.topvisible, 2)
314
+ cc.context.mark_set('insert', '1.5')
315
+ jump()
316
+ eq(cc.topvisible, 1)
317
+
318
+ # 4 lines of context showing.
319
+ cc.text.yview('12.0')
320
+ cc.update_code_context()
321
+ eq(cc.topvisible, 12)
322
+ cc.context.mark_set('insert', '3.0')
323
+ jump()
324
+ eq(cc.topvisible, 8)
325
+
326
+ # More context lines than limit.
327
+ cc.context_depth = 2
328
+ cc.text.yview('12.0')
329
+ cc.update_code_context()
330
+ eq(cc.topvisible, 12)
331
+ cc.context.mark_set('insert', '1.0')
332
+ jump()
333
+ eq(cc.topvisible, 8)
334
+
335
+ # Context selection stops jump.
336
+ cc.text.yview('5.0')
337
+ cc.update_code_context()
338
+ cc.context.tag_add('sel', '1.0', '2.0')
339
+ cc.context.mark_set('insert', '1.0')
340
+ jump() # Without selection, to line 2.
341
+ eq(cc.topvisible, 5)
342
+
343
+ @mock.patch.object(codecontext.CodeContext, 'update_code_context')
344
+ def test_timer_event(self, mock_update):
345
+ # Ensure code context is not active.
346
+ if self.cc.context:
347
+ self.cc.toggle_code_context_event()
348
+ self.cc.timer_event()
349
+ mock_update.assert_not_called()
350
+
351
+ # Activate code context.
352
+ self.cc.toggle_code_context_event()
353
+ self.cc.timer_event()
354
+ mock_update.assert_called()
355
+
356
+ def test_font(self):
357
+ eq = self.assertEqual
358
+ cc = self.cc
359
+
360
+ orig_font = cc.text['font']
361
+ test_font = 'TkTextFont'
362
+ self.assertNotEqual(orig_font, test_font)
363
+
364
+ # Ensure code context is not active.
365
+ if cc.context is not None:
366
+ cc.toggle_code_context_event()
367
+
368
+ self.font_override = test_font
369
+ # Nothing breaks or changes with inactive code context.
370
+ cc.update_font()
371
+
372
+ # Activate code context, previous font change is immediately effective.
373
+ cc.toggle_code_context_event()
374
+ eq(cc.context['font'], test_font)
375
+
376
+ # Call the font update, change is picked up.
377
+ self.font_override = orig_font
378
+ cc.update_font()
379
+ eq(cc.context['font'], orig_font)
380
+
381
+ def test_highlight_colors(self):
382
+ eq = self.assertEqual
383
+ cc = self.cc
384
+
385
+ orig_colors = dict(self.highlight_cfg)
386
+ test_colors = {'background': '#222222', 'foreground': '#ffff00'}
387
+
388
+ def assert_colors_are_equal(colors):
389
+ eq(cc.context['background'], colors['background'])
390
+ eq(cc.context['foreground'], colors['foreground'])
391
+
392
+ # Ensure code context is not active.
393
+ if cc.context:
394
+ cc.toggle_code_context_event()
395
+
396
+ self.highlight_cfg = test_colors
397
+ # Nothing breaks with inactive code context.
398
+ cc.update_highlight_colors()
399
+
400
+ # Activate code context, previous colors change is immediately effective.
401
+ cc.toggle_code_context_event()
402
+ assert_colors_are_equal(test_colors)
403
+
404
+ # Call colors update with no change to the configured colors.
405
+ cc.update_highlight_colors()
406
+ assert_colors_are_equal(test_colors)
407
+
408
+ # Call the colors update with code context active, change is picked up.
409
+ self.highlight_cfg = orig_colors
410
+ cc.update_highlight_colors()
411
+ assert_colors_are_equal(orig_colors)
412
+
413
+
414
+ class HelperFunctionText(unittest.TestCase):
415
+
416
+ def test_get_spaces_firstword(self):
417
+ get = codecontext.get_spaces_firstword
418
+ test_lines = (
419
+ (' first word', (' ', 'first')),
420
+ ('\tfirst word', ('\t', 'first')),
421
+ (' \u19D4\u19D2: ', (' ', '\u19D4\u19D2')),
422
+ ('no spaces', ('', 'no')),
423
+ ('', ('', '')),
424
+ ('# TEST COMMENT', ('', '')),
425
+ (' (continuation)', (' ', ''))
426
+ )
427
+ for line, expected_output in test_lines:
428
+ self.assertEqual(get(line), expected_output)
429
+
430
+ # Send the pattern in the call.
431
+ self.assertEqual(get(' (continuation)',
432
+ c=re.compile(r'^(\s*)([^\s]*)')),
433
+ (' ', '(continuation)'))
434
+
435
+ def test_get_line_info(self):
436
+ eq = self.assertEqual
437
+ gli = codecontext.get_line_info
438
+ lines = code_sample.splitlines()
439
+
440
+ # Line 1 is not a BLOCKOPENER.
441
+ eq(gli(lines[0]), (codecontext.INFINITY, '', False))
442
+ # Line 2 is a BLOCKOPENER without an indent.
443
+ eq(gli(lines[1]), (0, 'class C1:', 'class'))
444
+ # Line 3 is not a BLOCKOPENER and does not return the indent level.
445
+ eq(gli(lines[2]), (codecontext.INFINITY, ' # Class comment.', False))
446
+ # Line 4 is a BLOCKOPENER and is indented.
447
+ eq(gli(lines[3]), (4, ' def __init__(self, a, b):', 'def'))
448
+ # Line 8 is a different BLOCKOPENER and is indented.
449
+ eq(gli(lines[7]), (8, ' if a > b:', 'if'))
450
+ # Test tab.
451
+ eq(gli('\tif a == b:'), (1, '\tif a == b:', 'if'))
452
+
453
+
454
+ if __name__ == '__main__':
455
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_config.py ADDED
@@ -0,0 +1,805 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test config, coverage 93%.
2
+ (100% for IdleConfParser, IdleUserConfParser*, ConfigChanges).
3
+ * Exception is OSError clause in Save method.
4
+ Much of IdleConf is also exercised by ConfigDialog and test_configdialog.
5
+ """
6
+ from idlelib import config
7
+ import sys
8
+ import os
9
+ import tempfile
10
+ from test.support import captured_stderr, findfile
11
+ import unittest
12
+ from unittest import mock
13
+ import idlelib
14
+ from idlelib.idle_test.mock_idle import Func
15
+
16
+ # Tests should not depend on fortuitous user configurations.
17
+ # They must not affect actual user .cfg files.
18
+ # Replace user parsers with empty parsers that cannot be saved
19
+ # due to getting '' as the filename when created.
20
+
21
+ idleConf = config.idleConf
22
+ usercfg = idleConf.userCfg
23
+ testcfg = {}
24
+ usermain = testcfg['main'] = config.IdleUserConfParser('')
25
+ userhigh = testcfg['highlight'] = config.IdleUserConfParser('')
26
+ userkeys = testcfg['keys'] = config.IdleUserConfParser('')
27
+ userextn = testcfg['extensions'] = config.IdleUserConfParser('')
28
+
29
+ def setUpModule():
30
+ idleConf.userCfg = testcfg
31
+ idlelib.testing = True
32
+
33
+ def tearDownModule():
34
+ idleConf.userCfg = usercfg
35
+ idlelib.testing = False
36
+
37
+
38
+ class IdleConfParserTest(unittest.TestCase):
39
+ """Test that IdleConfParser works"""
40
+
41
+ config = """
42
+ [one]
43
+ one = false
44
+ two = true
45
+ three = 10
46
+
47
+ [two]
48
+ one = a string
49
+ two = true
50
+ three = false
51
+ """
52
+
53
+ def test_get(self):
54
+ parser = config.IdleConfParser('')
55
+ parser.read_string(self.config)
56
+ eq = self.assertEqual
57
+
58
+ # Test with type argument.
59
+ self.assertIs(parser.Get('one', 'one', type='bool'), False)
60
+ self.assertIs(parser.Get('one', 'two', type='bool'), True)
61
+ eq(parser.Get('one', 'three', type='int'), 10)
62
+ eq(parser.Get('two', 'one'), 'a string')
63
+ self.assertIs(parser.Get('two', 'two', type='bool'), True)
64
+ self.assertIs(parser.Get('two', 'three', type='bool'), False)
65
+
66
+ # Test without type should fallback to string.
67
+ eq(parser.Get('two', 'two'), 'true')
68
+ eq(parser.Get('two', 'three'), 'false')
69
+
70
+ # If option not exist, should return None, or default.
71
+ self.assertIsNone(parser.Get('not', 'exist'))
72
+ eq(parser.Get('not', 'exist', default='DEFAULT'), 'DEFAULT')
73
+
74
+ def test_get_option_list(self):
75
+ parser = config.IdleConfParser('')
76
+ parser.read_string(self.config)
77
+ get_list = parser.GetOptionList
78
+ self.assertCountEqual(get_list('one'), ['one', 'two', 'three'])
79
+ self.assertCountEqual(get_list('two'), ['one', 'two', 'three'])
80
+ self.assertEqual(get_list('not exist'), [])
81
+
82
+ def test_load_nothing(self):
83
+ parser = config.IdleConfParser('')
84
+ parser.Load()
85
+ self.assertEqual(parser.sections(), [])
86
+
87
+ def test_load_file(self):
88
+ # Borrow test/cfgparser.1 from test_configparser.
89
+ config_path = findfile('cfgparser.1')
90
+ parser = config.IdleConfParser(config_path)
91
+ parser.Load()
92
+
93
+ self.assertEqual(parser.Get('Foo Bar', 'foo'), 'newbar')
94
+ self.assertEqual(parser.GetOptionList('Foo Bar'), ['foo'])
95
+
96
+
97
+ class IdleUserConfParserTest(unittest.TestCase):
98
+ """Test that IdleUserConfParser works"""
99
+
100
+ def new_parser(self, path=''):
101
+ return config.IdleUserConfParser(path)
102
+
103
+ def test_set_option(self):
104
+ parser = self.new_parser()
105
+ parser.add_section('Foo')
106
+ # Setting new option in existing section should return True.
107
+ self.assertTrue(parser.SetOption('Foo', 'bar', 'true'))
108
+ # Setting existing option with same value should return False.
109
+ self.assertFalse(parser.SetOption('Foo', 'bar', 'true'))
110
+ # Setting exiting option with new value should return True.
111
+ self.assertTrue(parser.SetOption('Foo', 'bar', 'false'))
112
+ self.assertEqual(parser.Get('Foo', 'bar'), 'false')
113
+
114
+ # Setting option in new section should create section and return True.
115
+ self.assertTrue(parser.SetOption('Bar', 'bar', 'true'))
116
+ self.assertCountEqual(parser.sections(), ['Bar', 'Foo'])
117
+ self.assertEqual(parser.Get('Bar', 'bar'), 'true')
118
+
119
+ def test_remove_option(self):
120
+ parser = self.new_parser()
121
+ parser.AddSection('Foo')
122
+ parser.SetOption('Foo', 'bar', 'true')
123
+
124
+ self.assertTrue(parser.RemoveOption('Foo', 'bar'))
125
+ self.assertFalse(parser.RemoveOption('Foo', 'bar'))
126
+ self.assertFalse(parser.RemoveOption('Not', 'Exist'))
127
+
128
+ def test_add_section(self):
129
+ parser = self.new_parser()
130
+ self.assertEqual(parser.sections(), [])
131
+
132
+ # Should not add duplicate section.
133
+ # Configparser raises DuplicateError, IdleParser not.
134
+ parser.AddSection('Foo')
135
+ parser.AddSection('Foo')
136
+ parser.AddSection('Bar')
137
+ self.assertCountEqual(parser.sections(), ['Bar', 'Foo'])
138
+
139
+ def test_remove_empty_sections(self):
140
+ parser = self.new_parser()
141
+
142
+ parser.AddSection('Foo')
143
+ parser.AddSection('Bar')
144
+ parser.SetOption('Idle', 'name', 'val')
145
+ self.assertCountEqual(parser.sections(), ['Bar', 'Foo', 'Idle'])
146
+ parser.RemoveEmptySections()
147
+ self.assertEqual(parser.sections(), ['Idle'])
148
+
149
+ def test_is_empty(self):
150
+ parser = self.new_parser()
151
+
152
+ parser.AddSection('Foo')
153
+ parser.AddSection('Bar')
154
+ self.assertTrue(parser.IsEmpty())
155
+ self.assertEqual(parser.sections(), [])
156
+
157
+ parser.SetOption('Foo', 'bar', 'false')
158
+ parser.AddSection('Bar')
159
+ self.assertFalse(parser.IsEmpty())
160
+ self.assertCountEqual(parser.sections(), ['Foo'])
161
+
162
+ def test_save(self):
163
+ with tempfile.TemporaryDirectory() as tdir:
164
+ path = os.path.join(tdir, 'test.cfg')
165
+ parser = self.new_parser(path)
166
+ parser.AddSection('Foo')
167
+ parser.SetOption('Foo', 'bar', 'true')
168
+
169
+ # Should save to path when config is not empty.
170
+ self.assertFalse(os.path.exists(path))
171
+ parser.Save()
172
+ self.assertTrue(os.path.exists(path))
173
+
174
+ # Should remove the file from disk when config is empty.
175
+ parser.remove_section('Foo')
176
+ parser.Save()
177
+ self.assertFalse(os.path.exists(path))
178
+
179
+
180
+ class IdleConfTest(unittest.TestCase):
181
+ """Test for idleConf"""
182
+
183
+ @classmethod
184
+ def setUpClass(cls):
185
+ cls.config_string = {}
186
+
187
+ conf = config.IdleConf(_utest=True)
188
+ if __name__ != '__main__':
189
+ idle_dir = os.path.dirname(__file__)
190
+ else:
191
+ idle_dir = os.path.abspath(sys.path[0])
192
+ for ctype in conf.config_types:
193
+ config_path = os.path.join(idle_dir, '../config-%s.def' % ctype)
194
+ with open(config_path, 'r') as f:
195
+ cls.config_string[ctype] = f.read()
196
+
197
+ cls.orig_warn = config._warn
198
+ config._warn = Func()
199
+
200
+ @classmethod
201
+ def tearDownClass(cls):
202
+ config._warn = cls.orig_warn
203
+
204
+ def new_config(self, _utest=False):
205
+ return config.IdleConf(_utest=_utest)
206
+
207
+ def mock_config(self):
208
+ """Return a mocked idleConf
209
+
210
+ Both default and user config used the same config-*.def
211
+ """
212
+ conf = config.IdleConf(_utest=True)
213
+ for ctype in conf.config_types:
214
+ conf.defaultCfg[ctype] = config.IdleConfParser('')
215
+ conf.defaultCfg[ctype].read_string(self.config_string[ctype])
216
+ conf.userCfg[ctype] = config.IdleUserConfParser('')
217
+ conf.userCfg[ctype].read_string(self.config_string[ctype])
218
+
219
+ return conf
220
+
221
+ @unittest.skipIf(sys.platform.startswith('win'), 'this is test for unix system')
222
+ def test_get_user_cfg_dir_unix(self):
223
+ # Test to get user config directory under unix.
224
+ conf = self.new_config(_utest=True)
225
+
226
+ # Check normal way should success
227
+ with mock.patch('os.path.expanduser', return_value='/home/foo'):
228
+ with mock.patch('os.path.exists', return_value=True):
229
+ self.assertEqual(conf.GetUserCfgDir(), '/home/foo/.idlerc')
230
+
231
+ # Check os.getcwd should success
232
+ with mock.patch('os.path.expanduser', return_value='~'):
233
+ with mock.patch('os.getcwd', return_value='/home/foo/cpython'):
234
+ with mock.patch('os.mkdir'):
235
+ self.assertEqual(conf.GetUserCfgDir(),
236
+ '/home/foo/cpython/.idlerc')
237
+
238
+ # Check user dir not exists and created failed should raise SystemExit
239
+ with mock.patch('os.path.join', return_value='/path/not/exists'):
240
+ with self.assertRaises(SystemExit):
241
+ with self.assertRaises(FileNotFoundError):
242
+ conf.GetUserCfgDir()
243
+
244
+ @unittest.skipIf(not sys.platform.startswith('win'), 'this is test for Windows system')
245
+ def test_get_user_cfg_dir_windows(self):
246
+ # Test to get user config directory under Windows.
247
+ conf = self.new_config(_utest=True)
248
+
249
+ # Check normal way should success
250
+ with mock.patch('os.path.expanduser', return_value='C:\\foo'):
251
+ with mock.patch('os.path.exists', return_value=True):
252
+ self.assertEqual(conf.GetUserCfgDir(), 'C:\\foo\\.idlerc')
253
+
254
+ # Check os.getcwd should success
255
+ with mock.patch('os.path.expanduser', return_value='~'):
256
+ with mock.patch('os.getcwd', return_value='C:\\foo\\cpython'):
257
+ with mock.patch('os.mkdir'):
258
+ self.assertEqual(conf.GetUserCfgDir(),
259
+ 'C:\\foo\\cpython\\.idlerc')
260
+
261
+ # Check user dir not exists and created failed should raise SystemExit
262
+ with mock.patch('os.path.join', return_value='/path/not/exists'):
263
+ with self.assertRaises(SystemExit):
264
+ with self.assertRaises(FileNotFoundError):
265
+ conf.GetUserCfgDir()
266
+
267
+ def test_create_config_handlers(self):
268
+ conf = self.new_config(_utest=True)
269
+
270
+ # Mock out idle_dir
271
+ idle_dir = '/home/foo'
272
+ with mock.patch.dict({'__name__': '__foo__'}):
273
+ with mock.patch('os.path.dirname', return_value=idle_dir):
274
+ conf.CreateConfigHandlers()
275
+
276
+ # Check keys are equal
277
+ self.assertCountEqual(conf.defaultCfg.keys(), conf.config_types)
278
+ self.assertCountEqual(conf.userCfg.keys(), conf.config_types)
279
+
280
+ # Check conf parser are correct type
281
+ for default_parser in conf.defaultCfg.values():
282
+ self.assertIsInstance(default_parser, config.IdleConfParser)
283
+ for user_parser in conf.userCfg.values():
284
+ self.assertIsInstance(user_parser, config.IdleUserConfParser)
285
+
286
+ # Check config path are correct
287
+ for cfg_type, parser in conf.defaultCfg.items():
288
+ self.assertEqual(parser.file,
289
+ os.path.join(idle_dir, f'config-{cfg_type}.def'))
290
+ for cfg_type, parser in conf.userCfg.items():
291
+ self.assertEqual(parser.file,
292
+ os.path.join(conf.userdir or '#', f'config-{cfg_type}.cfg'))
293
+
294
+ def test_load_cfg_files(self):
295
+ conf = self.new_config(_utest=True)
296
+
297
+ # Borrow test/cfgparser.1 from test_configparser.
298
+ config_path = findfile('cfgparser.1')
299
+ conf.defaultCfg['foo'] = config.IdleConfParser(config_path)
300
+ conf.userCfg['foo'] = config.IdleUserConfParser(config_path)
301
+
302
+ # Load all config from path
303
+ conf.LoadCfgFiles()
304
+
305
+ eq = self.assertEqual
306
+
307
+ # Check defaultCfg is loaded
308
+ eq(conf.defaultCfg['foo'].Get('Foo Bar', 'foo'), 'newbar')
309
+ eq(conf.defaultCfg['foo'].GetOptionList('Foo Bar'), ['foo'])
310
+
311
+ # Check userCfg is loaded
312
+ eq(conf.userCfg['foo'].Get('Foo Bar', 'foo'), 'newbar')
313
+ eq(conf.userCfg['foo'].GetOptionList('Foo Bar'), ['foo'])
314
+
315
+ def test_save_user_cfg_files(self):
316
+ conf = self.mock_config()
317
+
318
+ with mock.patch('idlelib.config.IdleUserConfParser.Save') as m:
319
+ conf.SaveUserCfgFiles()
320
+ self.assertEqual(m.call_count, len(conf.userCfg))
321
+
322
+ def test_get_option(self):
323
+ conf = self.mock_config()
324
+
325
+ eq = self.assertEqual
326
+ eq(conf.GetOption('main', 'EditorWindow', 'width'), '80')
327
+ eq(conf.GetOption('main', 'EditorWindow', 'width', type='int'), 80)
328
+ with mock.patch('idlelib.config._warn') as _warn:
329
+ eq(conf.GetOption('main', 'EditorWindow', 'font', type='int'), None)
330
+ eq(conf.GetOption('main', 'EditorWindow', 'NotExists'), None)
331
+ eq(conf.GetOption('main', 'EditorWindow', 'NotExists', default='NE'), 'NE')
332
+ eq(_warn.call_count, 4)
333
+
334
+ def test_set_option(self):
335
+ conf = self.mock_config()
336
+
337
+ conf.SetOption('main', 'Foo', 'bar', 'newbar')
338
+ self.assertEqual(conf.GetOption('main', 'Foo', 'bar'), 'newbar')
339
+
340
+ def test_get_section_list(self):
341
+ conf = self.mock_config()
342
+
343
+ self.assertCountEqual(
344
+ conf.GetSectionList('default', 'main'),
345
+ ['General', 'EditorWindow', 'PyShell', 'Indent', 'Theme',
346
+ 'Keys', 'History', 'HelpFiles'])
347
+ self.assertCountEqual(
348
+ conf.GetSectionList('user', 'main'),
349
+ ['General', 'EditorWindow', 'PyShell', 'Indent', 'Theme',
350
+ 'Keys', 'History', 'HelpFiles'])
351
+
352
+ with self.assertRaises(config.InvalidConfigSet):
353
+ conf.GetSectionList('foobar', 'main')
354
+ with self.assertRaises(config.InvalidConfigType):
355
+ conf.GetSectionList('default', 'notexists')
356
+
357
+ def test_get_highlight(self):
358
+ conf = self.mock_config()
359
+
360
+ eq = self.assertEqual
361
+ eq(conf.GetHighlight('IDLE Classic', 'normal'), {'foreground': '#000000',
362
+ 'background': '#ffffff'})
363
+
364
+ # Test cursor (this background should be normal-background)
365
+ eq(conf.GetHighlight('IDLE Classic', 'cursor'), {'foreground': 'black',
366
+ 'background': '#ffffff'})
367
+
368
+ # Test get user themes
369
+ conf.SetOption('highlight', 'Foobar', 'normal-foreground', '#747474')
370
+ conf.SetOption('highlight', 'Foobar', 'normal-background', '#171717')
371
+ with mock.patch('idlelib.config._warn'):
372
+ eq(conf.GetHighlight('Foobar', 'normal'), {'foreground': '#747474',
373
+ 'background': '#171717'})
374
+
375
+ def test_get_theme_dict(self):
376
+ # TODO: finish.
377
+ conf = self.mock_config()
378
+
379
+ # These two should be the same
380
+ self.assertEqual(
381
+ conf.GetThemeDict('default', 'IDLE Classic'),
382
+ conf.GetThemeDict('user', 'IDLE Classic'))
383
+
384
+ with self.assertRaises(config.InvalidTheme):
385
+ conf.GetThemeDict('bad', 'IDLE Classic')
386
+
387
+ def test_get_current_theme_and_keys(self):
388
+ conf = self.mock_config()
389
+
390
+ self.assertEqual(conf.CurrentTheme(), conf.current_colors_and_keys('Theme'))
391
+ self.assertEqual(conf.CurrentKeys(), conf.current_colors_and_keys('Keys'))
392
+
393
+ def test_current_colors_and_keys(self):
394
+ conf = self.mock_config()
395
+
396
+ self.assertEqual(conf.current_colors_and_keys('Theme'), 'IDLE Classic')
397
+
398
+ def test_default_keys(self):
399
+ current_platform = sys.platform
400
+ conf = self.new_config(_utest=True)
401
+
402
+ sys.platform = 'win32'
403
+ self.assertEqual(conf.default_keys(), 'IDLE Classic Windows')
404
+
405
+ sys.platform = 'darwin'
406
+ self.assertEqual(conf.default_keys(), 'IDLE Classic OSX')
407
+
408
+ sys.platform = 'some-linux'
409
+ self.assertEqual(conf.default_keys(), 'IDLE Modern Unix')
410
+
411
+ # Restore platform
412
+ sys.platform = current_platform
413
+
414
+ def test_get_extensions(self):
415
+ userextn.read_string('''
416
+ [ZzDummy]
417
+ enable = True
418
+ [DISABLE]
419
+ enable = False
420
+ ''')
421
+ eq = self.assertEqual
422
+ iGE = idleConf.GetExtensions
423
+ eq(iGE(shell_only=True), [])
424
+ eq(iGE(), ['ZzDummy'])
425
+ eq(iGE(editor_only=True), ['ZzDummy'])
426
+ eq(iGE(active_only=False), ['ZzDummy', 'DISABLE'])
427
+ eq(iGE(active_only=False, editor_only=True), ['ZzDummy', 'DISABLE'])
428
+ userextn.remove_section('ZzDummy')
429
+ userextn.remove_section('DISABLE')
430
+
431
+
432
+ def test_remove_key_bind_names(self):
433
+ conf = self.mock_config()
434
+
435
+ self.assertCountEqual(
436
+ conf.RemoveKeyBindNames(conf.GetSectionList('default', 'extensions')),
437
+ ['AutoComplete', 'CodeContext', 'FormatParagraph', 'ParenMatch', 'ZzDummy'])
438
+
439
+ def test_get_extn_name_for_event(self):
440
+ userextn.read_string('''
441
+ [ZzDummy]
442
+ enable = True
443
+ ''')
444
+ eq = self.assertEqual
445
+ eq(idleConf.GetExtnNameForEvent('z-in'), 'ZzDummy')
446
+ eq(idleConf.GetExtnNameForEvent('z-out'), None)
447
+ userextn.remove_section('ZzDummy')
448
+
449
+ def test_get_extension_keys(self):
450
+ userextn.read_string('''
451
+ [ZzDummy]
452
+ enable = True
453
+ ''')
454
+ self.assertEqual(idleConf.GetExtensionKeys('ZzDummy'),
455
+ {'<<z-in>>': ['<Control-Shift-KeyRelease-Insert>']})
456
+ userextn.remove_section('ZzDummy')
457
+ # need option key test
458
+ ## key = ['<Option-Key-2>'] if sys.platform == 'darwin' else ['<Alt-Key-2>']
459
+ ## eq(conf.GetExtensionKeys('ZoomHeight'), {'<<zoom-height>>': key})
460
+
461
+ def test_get_extension_bindings(self):
462
+ userextn.read_string('''
463
+ [ZzDummy]
464
+ enable = True
465
+ ''')
466
+ eq = self.assertEqual
467
+ iGEB = idleConf.GetExtensionBindings
468
+ eq(iGEB('NotExists'), {})
469
+ expect = {'<<z-in>>': ['<Control-Shift-KeyRelease-Insert>'],
470
+ '<<z-out>>': ['<Control-Shift-KeyRelease-Delete>']}
471
+ eq(iGEB('ZzDummy'), expect)
472
+ userextn.remove_section('ZzDummy')
473
+
474
+ def test_get_keybinding(self):
475
+ conf = self.mock_config()
476
+
477
+ eq = self.assertEqual
478
+ eq(conf.GetKeyBinding('IDLE Modern Unix', '<<copy>>'),
479
+ ['<Control-Shift-Key-C>', '<Control-Key-Insert>'])
480
+ eq(conf.GetKeyBinding('IDLE Classic Unix', '<<copy>>'),
481
+ ['<Alt-Key-w>', '<Meta-Key-w>'])
482
+ eq(conf.GetKeyBinding('IDLE Classic Windows', '<<copy>>'),
483
+ ['<Control-Key-c>', '<Control-Key-C>'])
484
+ eq(conf.GetKeyBinding('IDLE Classic Mac', '<<copy>>'), ['<Command-Key-c>'])
485
+ eq(conf.GetKeyBinding('IDLE Classic OSX', '<<copy>>'), ['<Command-Key-c>'])
486
+
487
+ # Test keybinding not exists
488
+ eq(conf.GetKeyBinding('NOT EXISTS', '<<copy>>'), [])
489
+ eq(conf.GetKeyBinding('IDLE Modern Unix', 'NOT EXISTS'), [])
490
+
491
+ def test_get_current_keyset(self):
492
+ current_platform = sys.platform
493
+ conf = self.mock_config()
494
+
495
+ # Ensure that platform isn't darwin
496
+ sys.platform = 'some-linux'
497
+ self.assertEqual(conf.GetCurrentKeySet(), conf.GetKeySet(conf.CurrentKeys()))
498
+
499
+ # This should not be the same, since replace <Alt- to <Option-.
500
+ # Above depended on config-extensions.def having Alt keys,
501
+ # which is no longer true.
502
+ # sys.platform = 'darwin'
503
+ # self.assertNotEqual(conf.GetCurrentKeySet(), conf.GetKeySet(conf.CurrentKeys()))
504
+
505
+ # Restore platform
506
+ sys.platform = current_platform
507
+
508
+ def test_get_keyset(self):
509
+ conf = self.mock_config()
510
+
511
+ # Conflict with key set, should be disable to ''
512
+ conf.defaultCfg['extensions'].add_section('Foobar')
513
+ conf.defaultCfg['extensions'].add_section('Foobar_cfgBindings')
514
+ conf.defaultCfg['extensions'].set('Foobar', 'enable', 'True')
515
+ conf.defaultCfg['extensions'].set('Foobar_cfgBindings', 'newfoo', '<Key-F3>')
516
+ self.assertEqual(conf.GetKeySet('IDLE Modern Unix')['<<newfoo>>'], '')
517
+
518
+ def test_is_core_binding(self):
519
+ # XXX: Should move out the core keys to config file or other place
520
+ conf = self.mock_config()
521
+
522
+ self.assertTrue(conf.IsCoreBinding('copy'))
523
+ self.assertTrue(conf.IsCoreBinding('cut'))
524
+ self.assertTrue(conf.IsCoreBinding('del-word-right'))
525
+ self.assertFalse(conf.IsCoreBinding('not-exists'))
526
+
527
+ def test_extra_help_source_list(self):
528
+ # Test GetExtraHelpSourceList and GetAllExtraHelpSourcesList in same
529
+ # place to prevent prepare input data twice.
530
+ conf = self.mock_config()
531
+
532
+ # Test default with no extra help source
533
+ self.assertEqual(conf.GetExtraHelpSourceList('default'), [])
534
+ self.assertEqual(conf.GetExtraHelpSourceList('user'), [])
535
+ with self.assertRaises(config.InvalidConfigSet):
536
+ self.assertEqual(conf.GetExtraHelpSourceList('bad'), [])
537
+ self.assertCountEqual(
538
+ conf.GetAllExtraHelpSourcesList(),
539
+ conf.GetExtraHelpSourceList('default') + conf.GetExtraHelpSourceList('user'))
540
+
541
+ # Add help source to user config
542
+ conf.userCfg['main'].SetOption('HelpFiles', '4', 'Python;https://python.org') # This is bad input
543
+ conf.userCfg['main'].SetOption('HelpFiles', '3', 'Python:https://python.org') # This is bad input
544
+ conf.userCfg['main'].SetOption('HelpFiles', '2', 'Pillow;https://pillow.readthedocs.io/en/latest/')
545
+ conf.userCfg['main'].SetOption('HelpFiles', '1', 'IDLE;C:/Programs/Python36/Lib/idlelib/help.html')
546
+ self.assertEqual(conf.GetExtraHelpSourceList('user'),
547
+ [('IDLE', 'C:/Programs/Python36/Lib/idlelib/help.html', '1'),
548
+ ('Pillow', 'https://pillow.readthedocs.io/en/latest/', '2'),
549
+ ('Python', 'https://python.org', '4')])
550
+ self.assertCountEqual(
551
+ conf.GetAllExtraHelpSourcesList(),
552
+ conf.GetExtraHelpSourceList('default') + conf.GetExtraHelpSourceList('user'))
553
+
554
+ def test_get_font(self):
555
+ from test.support import requires
556
+ from tkinter import Tk
557
+ from tkinter.font import Font
558
+ conf = self.mock_config()
559
+
560
+ requires('gui')
561
+ root = Tk()
562
+ root.withdraw()
563
+
564
+ f = Font.actual(Font(name='TkFixedFont', exists=True, root=root))
565
+ self.assertEqual(
566
+ conf.GetFont(root, 'main', 'EditorWindow'),
567
+ (f['family'], 10 if f['size'] <= 0 else f['size'], f['weight']))
568
+
569
+ # Cleanup root
570
+ root.destroy()
571
+ del root
572
+
573
+ def test_get_core_keys(self):
574
+ conf = self.mock_config()
575
+
576
+ eq = self.assertEqual
577
+ eq(conf.GetCoreKeys()['<<center-insert>>'], ['<Control-l>'])
578
+ eq(conf.GetCoreKeys()['<<copy>>'], ['<Control-c>', '<Control-C>'])
579
+ eq(conf.GetCoreKeys()['<<history-next>>'], ['<Alt-n>'])
580
+ eq(conf.GetCoreKeys('IDLE Classic Windows')['<<center-insert>>'],
581
+ ['<Control-Key-l>', '<Control-Key-L>'])
582
+ eq(conf.GetCoreKeys('IDLE Classic OSX')['<<copy>>'], ['<Command-Key-c>'])
583
+ eq(conf.GetCoreKeys('IDLE Classic Unix')['<<history-next>>'],
584
+ ['<Alt-Key-n>', '<Meta-Key-n>'])
585
+ eq(conf.GetCoreKeys('IDLE Modern Unix')['<<history-next>>'],
586
+ ['<Alt-Key-n>', '<Meta-Key-n>'])
587
+
588
+
589
+ class CurrentColorKeysTest(unittest.TestCase):
590
+ """ Test colorkeys function with user config [Theme] and [Keys] patterns.
591
+
592
+ colorkeys = config.IdleConf.current_colors_and_keys
593
+ Test all patterns written by IDLE and some errors
594
+ Item 'default' should really be 'builtin' (versus 'custom).
595
+ """
596
+ colorkeys = idleConf.current_colors_and_keys
597
+ default_theme = 'IDLE Classic'
598
+ default_keys = idleConf.default_keys()
599
+
600
+ def test_old_builtin_theme(self):
601
+ # On initial installation, user main is blank.
602
+ self.assertEqual(self.colorkeys('Theme'), self.default_theme)
603
+ # For old default, name2 must be blank.
604
+ usermain.read_string('''
605
+ [Theme]
606
+ default = True
607
+ ''')
608
+ # IDLE omits 'name' for default old builtin theme.
609
+ self.assertEqual(self.colorkeys('Theme'), self.default_theme)
610
+ # IDLE adds 'name' for non-default old builtin theme.
611
+ usermain['Theme']['name'] = 'IDLE New'
612
+ self.assertEqual(self.colorkeys('Theme'), 'IDLE New')
613
+ # Erroneous non-default old builtin reverts to default.
614
+ usermain['Theme']['name'] = 'non-existent'
615
+ self.assertEqual(self.colorkeys('Theme'), self.default_theme)
616
+ usermain.remove_section('Theme')
617
+
618
+ def test_new_builtin_theme(self):
619
+ # IDLE writes name2 for new builtins.
620
+ usermain.read_string('''
621
+ [Theme]
622
+ default = True
623
+ name2 = IDLE Dark
624
+ ''')
625
+ self.assertEqual(self.colorkeys('Theme'), 'IDLE Dark')
626
+ # Leftover 'name', not removed, is ignored.
627
+ usermain['Theme']['name'] = 'IDLE New'
628
+ self.assertEqual(self.colorkeys('Theme'), 'IDLE Dark')
629
+ # Erroneous non-default new builtin reverts to default.
630
+ usermain['Theme']['name2'] = 'non-existent'
631
+ self.assertEqual(self.colorkeys('Theme'), self.default_theme)
632
+ usermain.remove_section('Theme')
633
+
634
+ def test_user_override_theme(self):
635
+ # Erroneous custom name (no definition) reverts to default.
636
+ usermain.read_string('''
637
+ [Theme]
638
+ default = False
639
+ name = Custom Dark
640
+ ''')
641
+ self.assertEqual(self.colorkeys('Theme'), self.default_theme)
642
+ # Custom name is valid with matching Section name.
643
+ userhigh.read_string('[Custom Dark]\na=b')
644
+ self.assertEqual(self.colorkeys('Theme'), 'Custom Dark')
645
+ # Name2 is ignored.
646
+ usermain['Theme']['name2'] = 'non-existent'
647
+ self.assertEqual(self.colorkeys('Theme'), 'Custom Dark')
648
+ usermain.remove_section('Theme')
649
+ userhigh.remove_section('Custom Dark')
650
+
651
+ def test_old_builtin_keys(self):
652
+ # On initial installation, user main is blank.
653
+ self.assertEqual(self.colorkeys('Keys'), self.default_keys)
654
+ # For old default, name2 must be blank, name is always used.
655
+ usermain.read_string('''
656
+ [Keys]
657
+ default = True
658
+ name = IDLE Classic Unix
659
+ ''')
660
+ self.assertEqual(self.colorkeys('Keys'), 'IDLE Classic Unix')
661
+ # Erroneous non-default old builtin reverts to default.
662
+ usermain['Keys']['name'] = 'non-existent'
663
+ self.assertEqual(self.colorkeys('Keys'), self.default_keys)
664
+ usermain.remove_section('Keys')
665
+
666
+ def test_new_builtin_keys(self):
667
+ # IDLE writes name2 for new builtins.
668
+ usermain.read_string('''
669
+ [Keys]
670
+ default = True
671
+ name2 = IDLE Modern Unix
672
+ ''')
673
+ self.assertEqual(self.colorkeys('Keys'), 'IDLE Modern Unix')
674
+ # Leftover 'name', not removed, is ignored.
675
+ usermain['Keys']['name'] = 'IDLE Classic Unix'
676
+ self.assertEqual(self.colorkeys('Keys'), 'IDLE Modern Unix')
677
+ # Erroneous non-default new builtin reverts to default.
678
+ usermain['Keys']['name2'] = 'non-existent'
679
+ self.assertEqual(self.colorkeys('Keys'), self.default_keys)
680
+ usermain.remove_section('Keys')
681
+
682
+ def test_user_override_keys(self):
683
+ # Erroneous custom name (no definition) reverts to default.
684
+ usermain.read_string('''
685
+ [Keys]
686
+ default = False
687
+ name = Custom Keys
688
+ ''')
689
+ self.assertEqual(self.colorkeys('Keys'), self.default_keys)
690
+ # Custom name is valid with matching Section name.
691
+ userkeys.read_string('[Custom Keys]\na=b')
692
+ self.assertEqual(self.colorkeys('Keys'), 'Custom Keys')
693
+ # Name2 is ignored.
694
+ usermain['Keys']['name2'] = 'non-existent'
695
+ self.assertEqual(self.colorkeys('Keys'), 'Custom Keys')
696
+ usermain.remove_section('Keys')
697
+ userkeys.remove_section('Custom Keys')
698
+
699
+
700
+ class ChangesTest(unittest.TestCase):
701
+
702
+ empty = {'main':{}, 'highlight':{}, 'keys':{}, 'extensions':{}}
703
+
704
+ def load(self): # Test_add_option verifies that this works.
705
+ changes = self.changes
706
+ changes.add_option('main', 'Msec', 'mitem', 'mval')
707
+ changes.add_option('highlight', 'Hsec', 'hitem', 'hval')
708
+ changes.add_option('keys', 'Ksec', 'kitem', 'kval')
709
+ return changes
710
+
711
+ loaded = {'main': {'Msec': {'mitem': 'mval'}},
712
+ 'highlight': {'Hsec': {'hitem': 'hval'}},
713
+ 'keys': {'Ksec': {'kitem':'kval'}},
714
+ 'extensions': {}}
715
+
716
+ def setUp(self):
717
+ self.changes = config.ConfigChanges()
718
+
719
+ def test_init(self):
720
+ self.assertEqual(self.changes, self.empty)
721
+
722
+ def test_add_option(self):
723
+ changes = self.load()
724
+ self.assertEqual(changes, self.loaded)
725
+ changes.add_option('main', 'Msec', 'mitem', 'mval')
726
+ self.assertEqual(changes, self.loaded)
727
+
728
+ def test_save_option(self): # Static function does not touch changes.
729
+ save_option = self.changes.save_option
730
+ self.assertTrue(save_option('main', 'Indent', 'what', '0'))
731
+ self.assertFalse(save_option('main', 'Indent', 'what', '0'))
732
+ self.assertEqual(usermain['Indent']['what'], '0')
733
+
734
+ self.assertTrue(save_option('main', 'Indent', 'use-spaces', '0'))
735
+ self.assertEqual(usermain['Indent']['use-spaces'], '0')
736
+ self.assertTrue(save_option('main', 'Indent', 'use-spaces', '1'))
737
+ self.assertFalse(usermain.has_option('Indent', 'use-spaces'))
738
+ usermain.remove_section('Indent')
739
+
740
+ def test_save_added(self):
741
+ changes = self.load()
742
+ self.assertTrue(changes.save_all())
743
+ self.assertEqual(usermain['Msec']['mitem'], 'mval')
744
+ self.assertEqual(userhigh['Hsec']['hitem'], 'hval')
745
+ self.assertEqual(userkeys['Ksec']['kitem'], 'kval')
746
+ changes.add_option('main', 'Msec', 'mitem', 'mval')
747
+ self.assertFalse(changes.save_all())
748
+ usermain.remove_section('Msec')
749
+ userhigh.remove_section('Hsec')
750
+ userkeys.remove_section('Ksec')
751
+
752
+ def test_save_help(self):
753
+ # Any change to HelpFiles overwrites entire section.
754
+ changes = self.changes
755
+ changes.save_option('main', 'HelpFiles', 'IDLE', 'idledoc')
756
+ changes.add_option('main', 'HelpFiles', 'ELDI', 'codeldi')
757
+ changes.save_all()
758
+ self.assertFalse(usermain.has_option('HelpFiles', 'IDLE'))
759
+ self.assertTrue(usermain.has_option('HelpFiles', 'ELDI'))
760
+
761
+ def test_save_default(self): # Cover 2nd and 3rd false branches.
762
+ changes = self.changes
763
+ changes.add_option('main', 'Indent', 'use-spaces', '1')
764
+ # save_option returns False; cfg_type_changed remains False.
765
+
766
+ # TODO: test that save_all calls usercfg Saves.
767
+
768
+ def test_delete_section(self):
769
+ changes = self.load()
770
+ changes.delete_section('main', 'fake') # Test no exception.
771
+ self.assertEqual(changes, self.loaded) # Test nothing deleted.
772
+ for cfgtype, section in (('main', 'Msec'), ('keys', 'Ksec')):
773
+ testcfg[cfgtype].SetOption(section, 'name', 'value')
774
+ changes.delete_section(cfgtype, section)
775
+ with self.assertRaises(KeyError):
776
+ changes[cfgtype][section] # Test section gone from changes
777
+ testcfg[cfgtype][section] # and from mock userCfg.
778
+ # TODO test for save call.
779
+
780
+ def test_clear(self):
781
+ changes = self.load()
782
+ changes.clear()
783
+ self.assertEqual(changes, self.empty)
784
+
785
+
786
+ class WarningTest(unittest.TestCase):
787
+
788
+ def test_warn(self):
789
+ Equal = self.assertEqual
790
+ config._warned = set()
791
+ with captured_stderr() as stderr:
792
+ config._warn('warning', 'key')
793
+ Equal(config._warned, {('warning','key')})
794
+ Equal(stderr.getvalue(), 'warning'+'\n')
795
+ with captured_stderr() as stderr:
796
+ config._warn('warning', 'key')
797
+ Equal(stderr.getvalue(), '')
798
+ with captured_stderr() as stderr:
799
+ config._warn('warn2', 'yek')
800
+ Equal(config._warned, {('warning','key'), ('warn2','yek')})
801
+ Equal(stderr.getvalue(), 'warn2'+'\n')
802
+
803
+
804
+ if __name__ == '__main__':
805
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_config_key.py ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test config_key, coverage 98%.
2
+
3
+ Coverage is effectively 100%. Tkinter dialog is mocked, Mac-only line
4
+ may be skipped, and dummy function in bind test should not be called.
5
+ Not tested: exit with 'self.advanced or self.keys_ok(keys) ...' False.
6
+ """
7
+
8
+ from idlelib import config_key
9
+ from test.support import requires
10
+ import unittest
11
+ from unittest import mock
12
+ from tkinter import Tk, TclError
13
+ from idlelib.idle_test.mock_idle import Func
14
+ from idlelib.idle_test.mock_tk import Mbox_func
15
+
16
+
17
+ class ValidationTest(unittest.TestCase):
18
+ "Test validation methods: ok, keys_ok, bind_ok."
19
+
20
+ class Validator(config_key.GetKeysFrame):
21
+ def __init__(self, *args, **kwargs):
22
+ super().__init__(*args, **kwargs)
23
+ class list_keys_final:
24
+ get = Func()
25
+ self.list_keys_final = list_keys_final
26
+ get_modifiers = Func()
27
+ showerror = Mbox_func()
28
+
29
+ @classmethod
30
+ def setUpClass(cls):
31
+ requires('gui')
32
+ cls.root = Tk()
33
+ cls.root.withdraw()
34
+ keylist = [['<Key-F12>'], ['<Control-Key-x>', '<Control-Key-X>']]
35
+ cls.dialog = cls.Validator(cls.root, '<<Test>>', keylist)
36
+
37
+ @classmethod
38
+ def tearDownClass(cls):
39
+ del cls.dialog
40
+ cls.root.update_idletasks()
41
+ cls.root.destroy()
42
+ del cls.root
43
+
44
+ def setUp(self):
45
+ self.dialog.showerror.message = ''
46
+ # A test that needs a particular final key value should set it.
47
+ # A test that sets a non-blank modifier list should reset it to [].
48
+
49
+ def test_ok_empty(self):
50
+ self.dialog.key_string.set(' ')
51
+ self.dialog.ok()
52
+ self.assertEqual(self.dialog.result, '')
53
+ self.assertEqual(self.dialog.showerror.message, 'No key specified.')
54
+
55
+ def test_ok_good(self):
56
+ self.dialog.key_string.set('<Key-F11>')
57
+ self.dialog.list_keys_final.get.result = 'F11'
58
+ self.dialog.ok()
59
+ self.assertEqual(self.dialog.result, '<Key-F11>')
60
+ self.assertEqual(self.dialog.showerror.message, '')
61
+
62
+ def test_keys_no_ending(self):
63
+ self.assertFalse(self.dialog.keys_ok('<Control-Shift'))
64
+ self.assertIn('Missing the final', self.dialog.showerror.message)
65
+
66
+ def test_keys_no_modifier_bad(self):
67
+ self.dialog.list_keys_final.get.result = 'A'
68
+ self.assertFalse(self.dialog.keys_ok('<Key-A>'))
69
+ self.assertIn('No modifier', self.dialog.showerror.message)
70
+
71
+ def test_keys_no_modifier_ok(self):
72
+ self.dialog.list_keys_final.get.result = 'F11'
73
+ self.assertTrue(self.dialog.keys_ok('<Key-F11>'))
74
+ self.assertEqual(self.dialog.showerror.message, '')
75
+
76
+ def test_keys_shift_bad(self):
77
+ self.dialog.list_keys_final.get.result = 'a'
78
+ self.dialog.get_modifiers.result = ['Shift']
79
+ self.assertFalse(self.dialog.keys_ok('<a>'))
80
+ self.assertIn('shift modifier', self.dialog.showerror.message)
81
+ self.dialog.get_modifiers.result = []
82
+
83
+ def test_keys_dup(self):
84
+ for mods, final, seq in (([], 'F12', '<Key-F12>'),
85
+ (['Control'], 'x', '<Control-Key-x>'),
86
+ (['Control'], 'X', '<Control-Key-X>')):
87
+ with self.subTest(m=mods, f=final, s=seq):
88
+ self.dialog.list_keys_final.get.result = final
89
+ self.dialog.get_modifiers.result = mods
90
+ self.assertFalse(self.dialog.keys_ok(seq))
91
+ self.assertIn('already in use', self.dialog.showerror.message)
92
+ self.dialog.get_modifiers.result = []
93
+
94
+ def test_bind_ok(self):
95
+ self.assertTrue(self.dialog.bind_ok('<Control-Shift-Key-a>'))
96
+ self.assertEqual(self.dialog.showerror.message, '')
97
+
98
+ def test_bind_not_ok(self):
99
+ self.assertFalse(self.dialog.bind_ok('<Control-Shift>'))
100
+ self.assertIn('not accepted', self.dialog.showerror.message)
101
+
102
+
103
+ class ToggleLevelTest(unittest.TestCase):
104
+ "Test toggle between Basic and Advanced frames."
105
+
106
+ @classmethod
107
+ def setUpClass(cls):
108
+ requires('gui')
109
+ cls.root = Tk()
110
+ cls.root.withdraw()
111
+ cls.dialog = config_key.GetKeysFrame(cls.root, '<<Test>>', [])
112
+
113
+ @classmethod
114
+ def tearDownClass(cls):
115
+ del cls.dialog
116
+ cls.root.update_idletasks()
117
+ cls.root.destroy()
118
+ del cls.root
119
+
120
+ def test_toggle_level(self):
121
+ dialog = self.dialog
122
+
123
+ def stackorder():
124
+ """Get the stack order of the children of the frame.
125
+
126
+ winfo_children() stores the children in stack order, so
127
+ this can be used to check whether a frame is above or
128
+ below another one.
129
+ """
130
+ for index, child in enumerate(dialog.winfo_children()):
131
+ if child._name == 'keyseq_basic':
132
+ basic = index
133
+ if child._name == 'keyseq_advanced':
134
+ advanced = index
135
+ return basic, advanced
136
+
137
+ # New window starts at basic level.
138
+ self.assertFalse(dialog.advanced)
139
+ self.assertIn('Advanced', dialog.button_level['text'])
140
+ basic, advanced = stackorder()
141
+ self.assertGreater(basic, advanced)
142
+
143
+ # Toggle to advanced.
144
+ dialog.toggle_level()
145
+ self.assertTrue(dialog.advanced)
146
+ self.assertIn('Basic', dialog.button_level['text'])
147
+ basic, advanced = stackorder()
148
+ self.assertGreater(advanced, basic)
149
+
150
+ # Toggle to basic.
151
+ dialog.button_level.invoke()
152
+ self.assertFalse(dialog.advanced)
153
+ self.assertIn('Advanced', dialog.button_level['text'])
154
+ basic, advanced = stackorder()
155
+ self.assertGreater(basic, advanced)
156
+
157
+
158
+ class KeySelectionTest(unittest.TestCase):
159
+ "Test selecting key on Basic frames."
160
+
161
+ class Basic(config_key.GetKeysFrame):
162
+ def __init__(self, *args, **kwargs):
163
+ super().__init__(*args, **kwargs)
164
+ class list_keys_final:
165
+ get = Func()
166
+ select_clear = Func()
167
+ yview = Func()
168
+ self.list_keys_final = list_keys_final
169
+ def set_modifiers_for_platform(self):
170
+ self.modifiers = ['foo', 'bar', 'BAZ']
171
+ self.modifier_label = {'BAZ': 'ZZZ'}
172
+ showerror = Mbox_func()
173
+
174
+ @classmethod
175
+ def setUpClass(cls):
176
+ requires('gui')
177
+ cls.root = Tk()
178
+ cls.root.withdraw()
179
+ cls.dialog = cls.Basic(cls.root, '<<Test>>', [])
180
+
181
+ @classmethod
182
+ def tearDownClass(cls):
183
+ del cls.dialog
184
+ cls.root.update_idletasks()
185
+ cls.root.destroy()
186
+ del cls.root
187
+
188
+ def setUp(self):
189
+ self.dialog.clear_key_seq()
190
+
191
+ def test_get_modifiers(self):
192
+ dialog = self.dialog
193
+ gm = dialog.get_modifiers
194
+ eq = self.assertEqual
195
+
196
+ # Modifiers are set on/off by invoking the checkbutton.
197
+ dialog.modifier_checkbuttons['foo'].invoke()
198
+ eq(gm(), ['foo'])
199
+
200
+ dialog.modifier_checkbuttons['BAZ'].invoke()
201
+ eq(gm(), ['foo', 'BAZ'])
202
+
203
+ dialog.modifier_checkbuttons['foo'].invoke()
204
+ eq(gm(), ['BAZ'])
205
+
206
+ @mock.patch.object(config_key.GetKeysFrame, 'get_modifiers')
207
+ def test_build_key_string(self, mock_modifiers):
208
+ dialog = self.dialog
209
+ key = dialog.list_keys_final
210
+ string = dialog.key_string.get
211
+ eq = self.assertEqual
212
+
213
+ key.get.result = 'a'
214
+ mock_modifiers.return_value = []
215
+ dialog.build_key_string()
216
+ eq(string(), '<Key-a>')
217
+
218
+ mock_modifiers.return_value = ['mymod']
219
+ dialog.build_key_string()
220
+ eq(string(), '<mymod-Key-a>')
221
+
222
+ key.get.result = ''
223
+ mock_modifiers.return_value = ['mymod', 'test']
224
+ dialog.build_key_string()
225
+ eq(string(), '<mymod-test>')
226
+
227
+ @mock.patch.object(config_key.GetKeysFrame, 'get_modifiers')
228
+ def test_final_key_selected(self, mock_modifiers):
229
+ dialog = self.dialog
230
+ key = dialog.list_keys_final
231
+ string = dialog.key_string.get
232
+ eq = self.assertEqual
233
+
234
+ mock_modifiers.return_value = ['Shift']
235
+ key.get.result = '{'
236
+ dialog.final_key_selected()
237
+ eq(string(), '<Shift-Key-braceleft>')
238
+
239
+
240
+ class CancelWindowTest(unittest.TestCase):
241
+ "Simulate user clicking [Cancel] button."
242
+
243
+ @classmethod
244
+ def setUpClass(cls):
245
+ requires('gui')
246
+ cls.root = Tk()
247
+ cls.root.withdraw()
248
+ cls.dialog = config_key.GetKeysWindow(
249
+ cls.root, 'Title', '<<Test>>', [], _utest=True)
250
+
251
+ @classmethod
252
+ def tearDownClass(cls):
253
+ cls.dialog.cancel()
254
+ del cls.dialog
255
+ cls.root.update_idletasks()
256
+ cls.root.destroy()
257
+ del cls.root
258
+
259
+ @mock.patch.object(config_key.GetKeysFrame, 'ok')
260
+ def test_cancel(self, mock_frame_ok):
261
+ self.assertEqual(self.dialog.winfo_class(), 'Toplevel')
262
+ self.dialog.button_cancel.invoke()
263
+ with self.assertRaises(TclError):
264
+ self.dialog.winfo_class()
265
+ self.assertEqual(self.dialog.result, '')
266
+ mock_frame_ok.assert_not_called()
267
+
268
+
269
+ class OKWindowTest(unittest.TestCase):
270
+ "Simulate user clicking [OK] button."
271
+
272
+ @classmethod
273
+ def setUpClass(cls):
274
+ requires('gui')
275
+ cls.root = Tk()
276
+ cls.root.withdraw()
277
+ cls.dialog = config_key.GetKeysWindow(
278
+ cls.root, 'Title', '<<Test>>', [], _utest=True)
279
+
280
+ @classmethod
281
+ def tearDownClass(cls):
282
+ cls.dialog.cancel()
283
+ del cls.dialog
284
+ cls.root.update_idletasks()
285
+ cls.root.destroy()
286
+ del cls.root
287
+
288
+ @mock.patch.object(config_key.GetKeysFrame, 'ok')
289
+ def test_ok(self, mock_frame_ok):
290
+ self.assertEqual(self.dialog.winfo_class(), 'Toplevel')
291
+ self.dialog.button_ok.invoke()
292
+ with self.assertRaises(TclError):
293
+ self.dialog.winfo_class()
294
+ mock_frame_ok.assert_called()
295
+
296
+
297
+ class WindowResultTest(unittest.TestCase):
298
+ "Test window result get and set."
299
+
300
+ @classmethod
301
+ def setUpClass(cls):
302
+ requires('gui')
303
+ cls.root = Tk()
304
+ cls.root.withdraw()
305
+ cls.dialog = config_key.GetKeysWindow(
306
+ cls.root, 'Title', '<<Test>>', [], _utest=True)
307
+
308
+ @classmethod
309
+ def tearDownClass(cls):
310
+ cls.dialog.cancel()
311
+ del cls.dialog
312
+ cls.root.update_idletasks()
313
+ cls.root.destroy()
314
+ del cls.root
315
+
316
+ def test_result(self):
317
+ dialog = self.dialog
318
+ eq = self.assertEqual
319
+
320
+ dialog.result = ''
321
+ eq(dialog.result, '')
322
+ eq(dialog.frame.result,'')
323
+
324
+ dialog.result = 'bar'
325
+ eq(dialog.result,'bar')
326
+ eq(dialog.frame.result,'bar')
327
+
328
+ dialog.frame.result = 'foo'
329
+ eq(dialog.result, 'foo')
330
+ eq(dialog.frame.result,'foo')
331
+
332
+
333
+ class HelperTest(unittest.TestCase):
334
+ "Test module level helper functions."
335
+
336
+ def test_translate_key(self):
337
+ tr = config_key.translate_key
338
+ eq = self.assertEqual
339
+
340
+ # Letters return unchanged with no 'Shift'.
341
+ eq(tr('q', []), 'Key-q')
342
+ eq(tr('q', ['Control', 'Alt']), 'Key-q')
343
+
344
+ # 'Shift' uppercases single lowercase letters.
345
+ eq(tr('q', ['Shift']), 'Key-Q')
346
+ eq(tr('q', ['Control', 'Shift']), 'Key-Q')
347
+ eq(tr('q', ['Control', 'Alt', 'Shift']), 'Key-Q')
348
+
349
+ # Convert key name to keysym.
350
+ eq(tr('Page Up', []), 'Key-Prior')
351
+ # 'Shift' doesn't change case when it's not a single char.
352
+ eq(tr('*', ['Shift']), 'Key-asterisk')
353
+
354
+
355
+ if __name__ == '__main__':
356
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_configdialog.py ADDED
@@ -0,0 +1,1583 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test configdialog, coverage 94%.
2
+
3
+ Half the class creates dialog, half works with user customizations.
4
+ """
5
+ from idlelib import configdialog
6
+ from test.support import requires
7
+ requires('gui')
8
+ import unittest
9
+ from unittest import mock
10
+ from idlelib.idle_test.mock_idle import Func
11
+ from tkinter import (Tk, StringVar, IntVar, BooleanVar, DISABLED, NORMAL)
12
+ from idlelib import config
13
+ from idlelib.configdialog import idleConf, changes, tracers
14
+
15
+ # Tests should not depend on fortuitous user configurations.
16
+ # They must not affect actual user .cfg files.
17
+ # Use solution from test_config: empty parsers with no filename.
18
+ usercfg = idleConf.userCfg
19
+ testcfg = {
20
+ 'main': config.IdleUserConfParser(''),
21
+ 'highlight': config.IdleUserConfParser(''),
22
+ 'keys': config.IdleUserConfParser(''),
23
+ 'extensions': config.IdleUserConfParser(''),
24
+ }
25
+
26
+ root = None
27
+ dialog = None
28
+ mainpage = changes['main']
29
+ highpage = changes['highlight']
30
+ keyspage = changes['keys']
31
+ extpage = changes['extensions']
32
+
33
+
34
+ def setUpModule():
35
+ global root, dialog
36
+ idleConf.userCfg = testcfg
37
+ root = Tk()
38
+ # root.withdraw() # Comment out, see issue 30870
39
+ dialog = configdialog.ConfigDialog(root, 'Test', _utest=True)
40
+
41
+
42
+ def tearDownModule():
43
+ global root, dialog
44
+ idleConf.userCfg = usercfg
45
+ tracers.detach()
46
+ tracers.clear()
47
+ changes.clear()
48
+ root.update_idletasks()
49
+ root.destroy()
50
+ root = dialog = None
51
+
52
+
53
+ class ConfigDialogTest(unittest.TestCase):
54
+
55
+ def test_deactivate_current_config(self):
56
+ pass
57
+
58
+ def activate_config_changes(self):
59
+ pass
60
+
61
+
62
+ class ButtonTest(unittest.TestCase):
63
+
64
+ def test_click_ok(self):
65
+ d = dialog
66
+ apply = d.apply = mock.Mock()
67
+ destroy = d.destroy = mock.Mock()
68
+ d.buttons['Ok'].invoke()
69
+ apply.assert_called_once()
70
+ destroy.assert_called_once()
71
+ del d.destroy, d.apply
72
+
73
+ def test_click_apply(self):
74
+ d = dialog
75
+ deactivate = d.deactivate_current_config = mock.Mock()
76
+ save_ext = d.extpage.save_all_changed_extensions = mock.Mock()
77
+ activate = d.activate_config_changes = mock.Mock()
78
+ d.buttons['Apply'].invoke()
79
+ deactivate.assert_called_once()
80
+ save_ext.assert_called_once()
81
+ activate.assert_called_once()
82
+ del d.extpage.save_all_changed_extensions
83
+ del d.activate_config_changes, d.deactivate_current_config
84
+
85
+ def test_click_cancel(self):
86
+ d = dialog
87
+ d.destroy = Func()
88
+ changes['main']['something'] = 1
89
+ d.buttons['Cancel'].invoke()
90
+ self.assertEqual(changes['main'], {})
91
+ self.assertEqual(d.destroy.called, 1)
92
+ del d.destroy
93
+
94
+ def test_click_help(self):
95
+ dialog.note.select(dialog.keyspage)
96
+ with mock.patch.object(configdialog, 'view_text',
97
+ new_callable=Func) as view:
98
+ dialog.buttons['Help'].invoke()
99
+ title, contents = view.kwds['title'], view.kwds['contents']
100
+ self.assertEqual(title, 'Help for IDLE preferences')
101
+ self.assertTrue(contents.startswith('When you click') and
102
+ contents.endswith('a different name.\n'))
103
+
104
+
105
+ class FontPageTest(unittest.TestCase):
106
+ """Test that font widgets enable users to make font changes.
107
+
108
+ Test that widget actions set vars, that var changes add three
109
+ options to changes and call set_samples, and that set_samples
110
+ changes the font of both sample boxes.
111
+ """
112
+ @classmethod
113
+ def setUpClass(cls):
114
+ page = cls.page = dialog.fontpage
115
+ dialog.note.select(page)
116
+ page.set_samples = Func() # Mask instance method.
117
+ page.update()
118
+
119
+ @classmethod
120
+ def tearDownClass(cls):
121
+ del cls.page.set_samples # Unmask instance method.
122
+
123
+ def setUp(self):
124
+ changes.clear()
125
+
126
+ def test_load_font_cfg(self):
127
+ # Leave widget load test to human visual check.
128
+ # TODO Improve checks when add IdleConf.get_font_values.
129
+ tracers.detach()
130
+ d = self.page
131
+ d.font_name.set('Fake')
132
+ d.font_size.set('1')
133
+ d.font_bold.set(True)
134
+ d.set_samples.called = 0
135
+ d.load_font_cfg()
136
+ self.assertNotEqual(d.font_name.get(), 'Fake')
137
+ self.assertNotEqual(d.font_size.get(), '1')
138
+ self.assertFalse(d.font_bold.get())
139
+ self.assertEqual(d.set_samples.called, 1)
140
+ tracers.attach()
141
+
142
+ def test_fontlist_key(self):
143
+ # Up and Down keys should select a new font.
144
+ d = self.page
145
+ if d.fontlist.size() < 2:
146
+ self.skipTest('need at least 2 fonts')
147
+ fontlist = d.fontlist
148
+ fontlist.activate(0)
149
+ font = d.fontlist.get('active')
150
+
151
+ # Test Down key.
152
+ fontlist.focus_force()
153
+ fontlist.update()
154
+ fontlist.event_generate('<Key-Down>')
155
+ fontlist.event_generate('<KeyRelease-Down>')
156
+
157
+ down_font = fontlist.get('active')
158
+ self.assertNotEqual(down_font, font)
159
+ self.assertIn(d.font_name.get(), down_font.lower())
160
+
161
+ # Test Up key.
162
+ fontlist.focus_force()
163
+ fontlist.update()
164
+ fontlist.event_generate('<Key-Up>')
165
+ fontlist.event_generate('<KeyRelease-Up>')
166
+
167
+ up_font = fontlist.get('active')
168
+ self.assertEqual(up_font, font)
169
+ self.assertIn(d.font_name.get(), up_font.lower())
170
+
171
+ def test_fontlist_mouse(self):
172
+ # Click on item should select that item.
173
+ d = self.page
174
+ if d.fontlist.size() < 2:
175
+ self.skipTest('need at least 2 fonts')
176
+ fontlist = d.fontlist
177
+ fontlist.activate(0)
178
+
179
+ # Select next item in listbox
180
+ fontlist.focus_force()
181
+ fontlist.see(1)
182
+ fontlist.update()
183
+ x, y, dx, dy = fontlist.bbox(1)
184
+ x += dx // 2
185
+ y += dy // 2
186
+ fontlist.event_generate('<Button-1>', x=x, y=y)
187
+ fontlist.event_generate('<ButtonRelease-1>', x=x, y=y)
188
+
189
+ font1 = fontlist.get(1)
190
+ select_font = fontlist.get('anchor')
191
+ self.assertEqual(select_font, font1)
192
+ self.assertIn(d.font_name.get(), font1.lower())
193
+
194
+ def test_sizelist(self):
195
+ # Click on number should select that number
196
+ d = self.page
197
+ d.sizelist.variable.set(40)
198
+ self.assertEqual(d.font_size.get(), '40')
199
+
200
+ def test_bold_toggle(self):
201
+ # Click on checkbutton should invert it.
202
+ d = self.page
203
+ d.font_bold.set(False)
204
+ d.bold_toggle.invoke()
205
+ self.assertTrue(d.font_bold.get())
206
+ d.bold_toggle.invoke()
207
+ self.assertFalse(d.font_bold.get())
208
+
209
+ def test_font_set(self):
210
+ # Test that setting a font Variable results in 3 provisional
211
+ # change entries and a call to set_samples. Use values sure to
212
+ # not be defaults.
213
+
214
+ default_font = idleConf.GetFont(root, 'main', 'EditorWindow')
215
+ default_size = str(default_font[1])
216
+ default_bold = default_font[2] == 'bold'
217
+ d = self.page
218
+ d.font_size.set(default_size)
219
+ d.font_bold.set(default_bold)
220
+ d.set_samples.called = 0
221
+
222
+ d.font_name.set('Test Font')
223
+ expected = {'EditorWindow': {'font': 'Test Font',
224
+ 'font-size': default_size,
225
+ 'font-bold': str(default_bold)}}
226
+ self.assertEqual(mainpage, expected)
227
+ self.assertEqual(d.set_samples.called, 1)
228
+ changes.clear()
229
+
230
+ d.font_size.set('20')
231
+ expected = {'EditorWindow': {'font': 'Test Font',
232
+ 'font-size': '20',
233
+ 'font-bold': str(default_bold)}}
234
+ self.assertEqual(mainpage, expected)
235
+ self.assertEqual(d.set_samples.called, 2)
236
+ changes.clear()
237
+
238
+ d.font_bold.set(not default_bold)
239
+ expected = {'EditorWindow': {'font': 'Test Font',
240
+ 'font-size': '20',
241
+ 'font-bold': str(not default_bold)}}
242
+ self.assertEqual(mainpage, expected)
243
+ self.assertEqual(d.set_samples.called, 3)
244
+
245
+ def test_set_samples(self):
246
+ d = self.page
247
+ del d.set_samples # Unmask method for test
248
+ orig_samples = d.font_sample, d.highlight_sample
249
+ d.font_sample, d.highlight_sample = {}, {}
250
+ d.font_name.set('test')
251
+ d.font_size.set('5')
252
+ d.font_bold.set(1)
253
+ expected = {'font': ('test', '5', 'bold')}
254
+
255
+ # Test set_samples.
256
+ d.set_samples()
257
+ self.assertTrue(d.font_sample == d.highlight_sample == expected)
258
+
259
+ d.font_sample, d.highlight_sample = orig_samples
260
+ d.set_samples = Func() # Re-mask for other tests.
261
+
262
+
263
+ class HighPageTest(unittest.TestCase):
264
+ """Test that highlight tab widgets enable users to make changes.
265
+
266
+ Test that widget actions set vars, that var changes add
267
+ options to changes and that themes work correctly.
268
+ """
269
+
270
+ @classmethod
271
+ def setUpClass(cls):
272
+ page = cls.page = dialog.highpage
273
+ dialog.note.select(page)
274
+ page.set_theme_type = Func()
275
+ page.paint_theme_sample = Func()
276
+ page.set_highlight_target = Func()
277
+ page.set_color_sample = Func()
278
+ page.update()
279
+
280
+ @classmethod
281
+ def tearDownClass(cls):
282
+ d = cls.page
283
+ del d.set_theme_type, d.paint_theme_sample
284
+ del d.set_highlight_target, d.set_color_sample
285
+
286
+ def setUp(self):
287
+ d = self.page
288
+ # The following is needed for test_load_key_cfg, _delete_custom_keys.
289
+ # This may indicate a defect in some test or function.
290
+ for section in idleConf.GetSectionList('user', 'highlight'):
291
+ idleConf.userCfg['highlight'].remove_section(section)
292
+ changes.clear()
293
+ d.set_theme_type.called = 0
294
+ d.paint_theme_sample.called = 0
295
+ d.set_highlight_target.called = 0
296
+ d.set_color_sample.called = 0
297
+
298
+ def test_load_theme_cfg(self):
299
+ tracers.detach()
300
+ d = self.page
301
+ eq = self.assertEqual
302
+
303
+ # Use builtin theme with no user themes created.
304
+ idleConf.CurrentTheme = mock.Mock(return_value='IDLE Classic')
305
+ d.load_theme_cfg()
306
+ self.assertTrue(d.theme_source.get())
307
+ # builtinlist sets variable builtin_name to the CurrentTheme default.
308
+ eq(d.builtin_name.get(), 'IDLE Classic')
309
+ eq(d.custom_name.get(), '- no custom themes -')
310
+ eq(d.custom_theme_on.state(), ('disabled',))
311
+ eq(d.set_theme_type.called, 1)
312
+ eq(d.paint_theme_sample.called, 1)
313
+ eq(d.set_highlight_target.called, 1)
314
+
315
+ # Builtin theme with non-empty user theme list.
316
+ idleConf.SetOption('highlight', 'test1', 'option', 'value')
317
+ idleConf.SetOption('highlight', 'test2', 'option2', 'value2')
318
+ d.load_theme_cfg()
319
+ eq(d.builtin_name.get(), 'IDLE Classic')
320
+ eq(d.custom_name.get(), 'test1')
321
+ eq(d.set_theme_type.called, 2)
322
+ eq(d.paint_theme_sample.called, 2)
323
+ eq(d.set_highlight_target.called, 2)
324
+
325
+ # Use custom theme.
326
+ idleConf.CurrentTheme = mock.Mock(return_value='test2')
327
+ idleConf.SetOption('main', 'Theme', 'default', '0')
328
+ d.load_theme_cfg()
329
+ self.assertFalse(d.theme_source.get())
330
+ eq(d.builtin_name.get(), 'IDLE Classic')
331
+ eq(d.custom_name.get(), 'test2')
332
+ eq(d.set_theme_type.called, 3)
333
+ eq(d.paint_theme_sample.called, 3)
334
+ eq(d.set_highlight_target.called, 3)
335
+
336
+ del idleConf.CurrentTheme
337
+ tracers.attach()
338
+
339
+ def test_theme_source(self):
340
+ eq = self.assertEqual
341
+ d = self.page
342
+ # Test these separately.
343
+ d.var_changed_builtin_name = Func()
344
+ d.var_changed_custom_name = Func()
345
+ # Builtin selected.
346
+ d.builtin_theme_on.invoke()
347
+ eq(mainpage, {'Theme': {'default': 'True'}})
348
+ eq(d.var_changed_builtin_name.called, 1)
349
+ eq(d.var_changed_custom_name.called, 0)
350
+ changes.clear()
351
+
352
+ # Custom selected.
353
+ d.custom_theme_on.state(('!disabled',))
354
+ d.custom_theme_on.invoke()
355
+ self.assertEqual(mainpage, {'Theme': {'default': 'False'}})
356
+ eq(d.var_changed_builtin_name.called, 1)
357
+ eq(d.var_changed_custom_name.called, 1)
358
+ del d.var_changed_builtin_name, d.var_changed_custom_name
359
+
360
+ def test_builtin_name(self):
361
+ eq = self.assertEqual
362
+ d = self.page
363
+ item_list = ['IDLE Classic', 'IDLE Dark', 'IDLE New']
364
+
365
+ # Not in old_themes, defaults name to first item.
366
+ idleConf.SetOption('main', 'Theme', 'name', 'spam')
367
+ d.builtinlist.SetMenu(item_list, 'IDLE Dark')
368
+ eq(mainpage, {'Theme': {'name': 'IDLE Classic',
369
+ 'name2': 'IDLE Dark'}})
370
+ eq(d.theme_message['text'], 'New theme, see Help')
371
+ eq(d.paint_theme_sample.called, 1)
372
+
373
+ # Not in old themes - uses name2.
374
+ changes.clear()
375
+ idleConf.SetOption('main', 'Theme', 'name', 'IDLE New')
376
+ d.builtinlist.SetMenu(item_list, 'IDLE Dark')
377
+ eq(mainpage, {'Theme': {'name2': 'IDLE Dark'}})
378
+ eq(d.theme_message['text'], 'New theme, see Help')
379
+ eq(d.paint_theme_sample.called, 2)
380
+
381
+ # Builtin name in old_themes.
382
+ changes.clear()
383
+ d.builtinlist.SetMenu(item_list, 'IDLE Classic')
384
+ eq(mainpage, {'Theme': {'name': 'IDLE Classic', 'name2': ''}})
385
+ eq(d.theme_message['text'], '')
386
+ eq(d.paint_theme_sample.called, 3)
387
+
388
+ def test_custom_name(self):
389
+ d = self.page
390
+
391
+ # If no selections, doesn't get added.
392
+ d.customlist.SetMenu([], '- no custom themes -')
393
+ self.assertNotIn('Theme', mainpage)
394
+ self.assertEqual(d.paint_theme_sample.called, 0)
395
+
396
+ # Custom name selected.
397
+ changes.clear()
398
+ d.customlist.SetMenu(['a', 'b', 'c'], 'c')
399
+ self.assertEqual(mainpage, {'Theme': {'name': 'c'}})
400
+ self.assertEqual(d.paint_theme_sample.called, 1)
401
+
402
+ def test_color(self):
403
+ d = self.page
404
+ d.on_new_color_set = Func()
405
+ # self.color is only set in get_color through colorchooser.
406
+ d.color.set('green')
407
+ self.assertEqual(d.on_new_color_set.called, 1)
408
+ del d.on_new_color_set
409
+
410
+ def test_highlight_target_list_mouse(self):
411
+ # Set highlight_target through targetlist.
412
+ eq = self.assertEqual
413
+ d = self.page
414
+
415
+ d.targetlist.SetMenu(['a', 'b', 'c'], 'c')
416
+ eq(d.highlight_target.get(), 'c')
417
+ eq(d.set_highlight_target.called, 1)
418
+
419
+ def test_highlight_target_text_mouse(self):
420
+ # Set highlight_target through clicking highlight_sample.
421
+ eq = self.assertEqual
422
+ d = self.page
423
+
424
+ elem = {}
425
+ count = 0
426
+ hs = d.highlight_sample
427
+ hs.focus_force()
428
+ hs.see(1.0)
429
+ hs.update_idletasks()
430
+
431
+ def tag_to_element(elem):
432
+ for element, tag in d.theme_elements.items():
433
+ elem[tag[0]] = element
434
+
435
+ def click_it(start):
436
+ x, y, dx, dy = hs.bbox(start)
437
+ x += dx // 2
438
+ y += dy // 2
439
+ hs.event_generate('<Enter>', x=0, y=0)
440
+ hs.event_generate('<Motion>', x=x, y=y)
441
+ hs.event_generate('<ButtonPress-1>', x=x, y=y)
442
+ hs.event_generate('<ButtonRelease-1>', x=x, y=y)
443
+
444
+ # Flip theme_elements to make the tag the key.
445
+ tag_to_element(elem)
446
+
447
+ # If highlight_sample has a tag that isn't in theme_elements, there
448
+ # will be a KeyError in the test run.
449
+ for tag in hs.tag_names():
450
+ for start_index in hs.tag_ranges(tag)[0::2]:
451
+ count += 1
452
+ click_it(start_index)
453
+ eq(d.highlight_target.get(), elem[tag])
454
+ eq(d.set_highlight_target.called, count)
455
+
456
+ def test_highlight_sample_double_click(self):
457
+ # Test double click on highlight_sample.
458
+ eq = self.assertEqual
459
+ d = self.page
460
+
461
+ hs = d.highlight_sample
462
+ hs.focus_force()
463
+ hs.see(1.0)
464
+ hs.update_idletasks()
465
+
466
+ # Test binding from configdialog.
467
+ hs.event_generate('<Enter>', x=0, y=0)
468
+ hs.event_generate('<Motion>', x=0, y=0)
469
+ # Double click is a sequence of two clicks in a row.
470
+ for _ in range(2):
471
+ hs.event_generate('<ButtonPress-1>', x=0, y=0)
472
+ hs.event_generate('<ButtonRelease-1>', x=0, y=0)
473
+
474
+ eq(hs.tag_ranges('sel'), ())
475
+
476
+ def test_highlight_sample_b1_motion(self):
477
+ # Test button motion on highlight_sample.
478
+ eq = self.assertEqual
479
+ d = self.page
480
+
481
+ hs = d.highlight_sample
482
+ hs.focus_force()
483
+ hs.see(1.0)
484
+ hs.update_idletasks()
485
+
486
+ x, y, dx, dy, offset = hs.dlineinfo('1.0')
487
+
488
+ # Test binding from configdialog.
489
+ hs.event_generate('<Leave>')
490
+ hs.event_generate('<Enter>')
491
+ hs.event_generate('<Motion>', x=x, y=y)
492
+ hs.event_generate('<ButtonPress-1>', x=x, y=y)
493
+ hs.event_generate('<B1-Motion>', x=dx, y=dy)
494
+ hs.event_generate('<ButtonRelease-1>', x=dx, y=dy)
495
+
496
+ eq(hs.tag_ranges('sel'), ())
497
+
498
+ def test_set_theme_type(self):
499
+ eq = self.assertEqual
500
+ d = self.page
501
+ del d.set_theme_type
502
+
503
+ # Builtin theme selected.
504
+ d.theme_source.set(True)
505
+ d.set_theme_type()
506
+ eq(d.builtinlist['state'], NORMAL)
507
+ eq(d.customlist['state'], DISABLED)
508
+ eq(d.button_delete_custom.state(), ('disabled',))
509
+
510
+ # Custom theme selected.
511
+ d.theme_source.set(False)
512
+ d.set_theme_type()
513
+ eq(d.builtinlist['state'], DISABLED)
514
+ eq(d.custom_theme_on.state(), ('selected',))
515
+ eq(d.customlist['state'], NORMAL)
516
+ eq(d.button_delete_custom.state(), ())
517
+ d.set_theme_type = Func()
518
+
519
+ def test_get_color(self):
520
+ eq = self.assertEqual
521
+ d = self.page
522
+ orig_chooser = configdialog.colorchooser.askcolor
523
+ chooser = configdialog.colorchooser.askcolor = Func()
524
+ gntn = d.get_new_theme_name = Func()
525
+
526
+ d.highlight_target.set('Editor Breakpoint')
527
+ d.color.set('#ffffff')
528
+
529
+ # Nothing selected.
530
+ chooser.result = (None, None)
531
+ d.button_set_color.invoke()
532
+ eq(d.color.get(), '#ffffff')
533
+
534
+ # Selection same as previous color.
535
+ chooser.result = ('', d.style.lookup(d.frame_color_set['style'], 'background'))
536
+ d.button_set_color.invoke()
537
+ eq(d.color.get(), '#ffffff')
538
+
539
+ # Select different color.
540
+ chooser.result = ((222.8671875, 0.0, 0.0), '#de0000')
541
+
542
+ # Default theme.
543
+ d.color.set('#ffffff')
544
+ d.theme_source.set(True)
545
+
546
+ # No theme name selected therefore color not saved.
547
+ gntn.result = ''
548
+ d.button_set_color.invoke()
549
+ eq(gntn.called, 1)
550
+ eq(d.color.get(), '#ffffff')
551
+ # Theme name selected.
552
+ gntn.result = 'My New Theme'
553
+ d.button_set_color.invoke()
554
+ eq(d.custom_name.get(), gntn.result)
555
+ eq(d.color.get(), '#de0000')
556
+
557
+ # Custom theme.
558
+ d.color.set('#ffffff')
559
+ d.theme_source.set(False)
560
+ d.button_set_color.invoke()
561
+ eq(d.color.get(), '#de0000')
562
+
563
+ del d.get_new_theme_name
564
+ configdialog.colorchooser.askcolor = orig_chooser
565
+
566
+ def test_on_new_color_set(self):
567
+ d = self.page
568
+ color = '#3f7cae'
569
+ d.custom_name.set('Python')
570
+ d.highlight_target.set('Selected Text')
571
+ d.fg_bg_toggle.set(True)
572
+
573
+ d.color.set(color)
574
+ self.assertEqual(d.style.lookup(d.frame_color_set['style'], 'background'), color)
575
+ self.assertEqual(d.highlight_sample.tag_cget('hilite', 'foreground'), color)
576
+ self.assertEqual(highpage,
577
+ {'Python': {'hilite-foreground': color}})
578
+
579
+ def test_get_new_theme_name(self):
580
+ orig_sectionname = configdialog.SectionName
581
+ sn = configdialog.SectionName = Func(return_self=True)
582
+ d = self.page
583
+
584
+ sn.result = 'New Theme'
585
+ self.assertEqual(d.get_new_theme_name(''), 'New Theme')
586
+
587
+ configdialog.SectionName = orig_sectionname
588
+
589
+ def test_save_as_new_theme(self):
590
+ d = self.page
591
+ gntn = d.get_new_theme_name = Func()
592
+ d.theme_source.set(True)
593
+
594
+ # No name entered.
595
+ gntn.result = ''
596
+ d.button_save_custom.invoke()
597
+ self.assertNotIn(gntn.result, idleConf.userCfg['highlight'])
598
+
599
+ # Name entered.
600
+ gntn.result = 'my new theme'
601
+ gntn.called = 0
602
+ self.assertNotIn(gntn.result, idleConf.userCfg['highlight'])
603
+ d.button_save_custom.invoke()
604
+ self.assertIn(gntn.result, idleConf.userCfg['highlight'])
605
+
606
+ del d.get_new_theme_name
607
+
608
+ def test_create_new_and_save_new(self):
609
+ eq = self.assertEqual
610
+ d = self.page
611
+
612
+ # Use default as previously active theme.
613
+ d.theme_source.set(True)
614
+ d.builtin_name.set('IDLE Classic')
615
+ first_new = 'my new custom theme'
616
+ second_new = 'my second custom theme'
617
+
618
+ # No changes, so themes are an exact copy.
619
+ self.assertNotIn(first_new, idleConf.userCfg)
620
+ d.create_new(first_new)
621
+ eq(idleConf.GetSectionList('user', 'highlight'), [first_new])
622
+ eq(idleConf.GetThemeDict('default', 'IDLE Classic'),
623
+ idleConf.GetThemeDict('user', first_new))
624
+ eq(d.custom_name.get(), first_new)
625
+ self.assertFalse(d.theme_source.get()) # Use custom set.
626
+ eq(d.set_theme_type.called, 1)
627
+
628
+ # Test that changed targets are in new theme.
629
+ changes.add_option('highlight', first_new, 'hit-background', 'yellow')
630
+ self.assertNotIn(second_new, idleConf.userCfg)
631
+ d.create_new(second_new)
632
+ eq(idleConf.GetSectionList('user', 'highlight'), [first_new, second_new])
633
+ self.assertNotEqual(idleConf.GetThemeDict('user', first_new),
634
+ idleConf.GetThemeDict('user', second_new))
635
+ # Check that difference in themes was in `hit-background` from `changes`.
636
+ idleConf.SetOption('highlight', first_new, 'hit-background', 'yellow')
637
+ eq(idleConf.GetThemeDict('user', first_new),
638
+ idleConf.GetThemeDict('user', second_new))
639
+
640
+ def test_set_highlight_target(self):
641
+ eq = self.assertEqual
642
+ d = self.page
643
+ del d.set_highlight_target
644
+
645
+ # Target is cursor.
646
+ d.highlight_target.set('Cursor')
647
+ eq(d.fg_on.state(), ('disabled', 'selected'))
648
+ eq(d.bg_on.state(), ('disabled',))
649
+ self.assertTrue(d.fg_bg_toggle)
650
+ eq(d.set_color_sample.called, 1)
651
+
652
+ # Target is not cursor.
653
+ d.highlight_target.set('Comment')
654
+ eq(d.fg_on.state(), ('selected',))
655
+ eq(d.bg_on.state(), ())
656
+ self.assertTrue(d.fg_bg_toggle)
657
+ eq(d.set_color_sample.called, 2)
658
+
659
+ d.set_highlight_target = Func()
660
+
661
+ def test_set_color_sample_binding(self):
662
+ d = self.page
663
+ scs = d.set_color_sample
664
+
665
+ d.fg_on.invoke()
666
+ self.assertEqual(scs.called, 1)
667
+
668
+ d.bg_on.invoke()
669
+ self.assertEqual(scs.called, 2)
670
+
671
+ def test_set_color_sample(self):
672
+ d = self.page
673
+ del d.set_color_sample
674
+ d.highlight_target.set('Selected Text')
675
+ d.fg_bg_toggle.set(True)
676
+ d.set_color_sample()
677
+ self.assertEqual(
678
+ d.style.lookup(d.frame_color_set['style'], 'background'),
679
+ d.highlight_sample.tag_cget('hilite', 'foreground'))
680
+ d.set_color_sample = Func()
681
+
682
+ def test_paint_theme_sample(self):
683
+ eq = self.assertEqual
684
+ page = self.page
685
+ del page.paint_theme_sample # Delete masking mock.
686
+ hs_tag = page.highlight_sample.tag_cget
687
+ gh = idleConf.GetHighlight
688
+
689
+ # Create custom theme based on IDLE Dark.
690
+ page.theme_source.set(True)
691
+ page.builtin_name.set('IDLE Dark')
692
+ theme = 'IDLE Test'
693
+ page.create_new(theme)
694
+ page.set_color_sample.called = 0
695
+
696
+ # Base theme with nothing in `changes`.
697
+ page.paint_theme_sample()
698
+ new_console = {'foreground': 'blue',
699
+ 'background': 'yellow',}
700
+ for key, value in new_console.items():
701
+ self.assertNotEqual(hs_tag('console', key), value)
702
+ eq(page.set_color_sample.called, 1)
703
+
704
+ # Apply changes.
705
+ for key, value in new_console.items():
706
+ changes.add_option('highlight', theme, 'console-'+key, value)
707
+ page.paint_theme_sample()
708
+ for key, value in new_console.items():
709
+ eq(hs_tag('console', key), value)
710
+ eq(page.set_color_sample.called, 2)
711
+
712
+ page.paint_theme_sample = Func()
713
+
714
+ def test_delete_custom(self):
715
+ eq = self.assertEqual
716
+ d = self.page
717
+ d.button_delete_custom.state(('!disabled',))
718
+ yesno = d.askyesno = Func()
719
+ dialog.deactivate_current_config = Func()
720
+ dialog.activate_config_changes = Func()
721
+
722
+ theme_name = 'spam theme'
723
+ idleConf.userCfg['highlight'].SetOption(theme_name, 'name', 'value')
724
+ highpage[theme_name] = {'option': 'True'}
725
+
726
+ theme_name2 = 'other theme'
727
+ idleConf.userCfg['highlight'].SetOption(theme_name2, 'name', 'value')
728
+ highpage[theme_name2] = {'option': 'False'}
729
+
730
+ # Force custom theme.
731
+ d.custom_theme_on.state(('!disabled',))
732
+ d.custom_theme_on.invoke()
733
+ d.custom_name.set(theme_name)
734
+
735
+ # Cancel deletion.
736
+ yesno.result = False
737
+ d.button_delete_custom.invoke()
738
+ eq(yesno.called, 1)
739
+ eq(highpage[theme_name], {'option': 'True'})
740
+ eq(idleConf.GetSectionList('user', 'highlight'), [theme_name, theme_name2])
741
+ eq(dialog.deactivate_current_config.called, 0)
742
+ eq(dialog.activate_config_changes.called, 0)
743
+ eq(d.set_theme_type.called, 0)
744
+
745
+ # Confirm deletion.
746
+ yesno.result = True
747
+ d.button_delete_custom.invoke()
748
+ eq(yesno.called, 2)
749
+ self.assertNotIn(theme_name, highpage)
750
+ eq(idleConf.GetSectionList('user', 'highlight'), [theme_name2])
751
+ eq(d.custom_theme_on.state(), ())
752
+ eq(d.custom_name.get(), theme_name2)
753
+ eq(dialog.deactivate_current_config.called, 1)
754
+ eq(dialog.activate_config_changes.called, 1)
755
+ eq(d.set_theme_type.called, 1)
756
+
757
+ # Confirm deletion of second theme - empties list.
758
+ d.custom_name.set(theme_name2)
759
+ yesno.result = True
760
+ d.button_delete_custom.invoke()
761
+ eq(yesno.called, 3)
762
+ self.assertNotIn(theme_name, highpage)
763
+ eq(idleConf.GetSectionList('user', 'highlight'), [])
764
+ eq(d.custom_theme_on.state(), ('disabled',))
765
+ eq(d.custom_name.get(), '- no custom themes -')
766
+ eq(dialog.deactivate_current_config.called, 2)
767
+ eq(dialog.activate_config_changes.called, 2)
768
+ eq(d.set_theme_type.called, 2)
769
+
770
+ del dialog.activate_config_changes, dialog.deactivate_current_config
771
+ del d.askyesno
772
+
773
+
774
+ class KeysPageTest(unittest.TestCase):
775
+ """Test that keys tab widgets enable users to make changes.
776
+
777
+ Test that widget actions set vars, that var changes add
778
+ options to changes and that key sets works correctly.
779
+ """
780
+
781
+ @classmethod
782
+ def setUpClass(cls):
783
+ page = cls.page = dialog.keyspage
784
+ dialog.note.select(page)
785
+ page.set_keys_type = Func()
786
+ page.load_keys_list = Func()
787
+
788
+ @classmethod
789
+ def tearDownClass(cls):
790
+ page = cls.page
791
+ del page.set_keys_type, page.load_keys_list
792
+
793
+ def setUp(self):
794
+ d = self.page
795
+ # The following is needed for test_load_key_cfg, _delete_custom_keys.
796
+ # This may indicate a defect in some test or function.
797
+ for section in idleConf.GetSectionList('user', 'keys'):
798
+ idleConf.userCfg['keys'].remove_section(section)
799
+ changes.clear()
800
+ d.set_keys_type.called = 0
801
+ d.load_keys_list.called = 0
802
+
803
+ def test_load_key_cfg(self):
804
+ tracers.detach()
805
+ d = self.page
806
+ eq = self.assertEqual
807
+
808
+ # Use builtin keyset with no user keysets created.
809
+ idleConf.CurrentKeys = mock.Mock(return_value='IDLE Classic OSX')
810
+ d.load_key_cfg()
811
+ self.assertTrue(d.keyset_source.get())
812
+ # builtinlist sets variable builtin_name to the CurrentKeys default.
813
+ eq(d.builtin_name.get(), 'IDLE Classic OSX')
814
+ eq(d.custom_name.get(), '- no custom keys -')
815
+ eq(d.custom_keyset_on.state(), ('disabled',))
816
+ eq(d.set_keys_type.called, 1)
817
+ eq(d.load_keys_list.called, 1)
818
+ eq(d.load_keys_list.args, ('IDLE Classic OSX', ))
819
+
820
+ # Builtin keyset with non-empty user keyset list.
821
+ idleConf.SetOption('keys', 'test1', 'option', 'value')
822
+ idleConf.SetOption('keys', 'test2', 'option2', 'value2')
823
+ d.load_key_cfg()
824
+ eq(d.builtin_name.get(), 'IDLE Classic OSX')
825
+ eq(d.custom_name.get(), 'test1')
826
+ eq(d.set_keys_type.called, 2)
827
+ eq(d.load_keys_list.called, 2)
828
+ eq(d.load_keys_list.args, ('IDLE Classic OSX', ))
829
+
830
+ # Use custom keyset.
831
+ idleConf.CurrentKeys = mock.Mock(return_value='test2')
832
+ idleConf.default_keys = mock.Mock(return_value='IDLE Modern Unix')
833
+ idleConf.SetOption('main', 'Keys', 'default', '0')
834
+ d.load_key_cfg()
835
+ self.assertFalse(d.keyset_source.get())
836
+ eq(d.builtin_name.get(), 'IDLE Modern Unix')
837
+ eq(d.custom_name.get(), 'test2')
838
+ eq(d.set_keys_type.called, 3)
839
+ eq(d.load_keys_list.called, 3)
840
+ eq(d.load_keys_list.args, ('test2', ))
841
+
842
+ del idleConf.CurrentKeys, idleConf.default_keys
843
+ tracers.attach()
844
+
845
+ def test_keyset_source(self):
846
+ eq = self.assertEqual
847
+ d = self.page
848
+ # Test these separately.
849
+ d.var_changed_builtin_name = Func()
850
+ d.var_changed_custom_name = Func()
851
+ # Builtin selected.
852
+ d.builtin_keyset_on.invoke()
853
+ eq(mainpage, {'Keys': {'default': 'True'}})
854
+ eq(d.var_changed_builtin_name.called, 1)
855
+ eq(d.var_changed_custom_name.called, 0)
856
+ changes.clear()
857
+
858
+ # Custom selected.
859
+ d.custom_keyset_on.state(('!disabled',))
860
+ d.custom_keyset_on.invoke()
861
+ self.assertEqual(mainpage, {'Keys': {'default': 'False'}})
862
+ eq(d.var_changed_builtin_name.called, 1)
863
+ eq(d.var_changed_custom_name.called, 1)
864
+ del d.var_changed_builtin_name, d.var_changed_custom_name
865
+
866
+ def test_builtin_name(self):
867
+ eq = self.assertEqual
868
+ d = self.page
869
+ idleConf.userCfg['main'].remove_section('Keys')
870
+ item_list = ['IDLE Classic Windows', 'IDLE Classic OSX',
871
+ 'IDLE Modern UNIX']
872
+
873
+ # Not in old_keys, defaults name to first item.
874
+ d.builtinlist.SetMenu(item_list, 'IDLE Modern UNIX')
875
+ eq(mainpage, {'Keys': {'name': 'IDLE Classic Windows',
876
+ 'name2': 'IDLE Modern UNIX'}})
877
+ eq(d.keys_message['text'], 'New key set, see Help')
878
+ eq(d.load_keys_list.called, 1)
879
+ eq(d.load_keys_list.args, ('IDLE Modern UNIX', ))
880
+
881
+ # Not in old keys - uses name2.
882
+ changes.clear()
883
+ idleConf.SetOption('main', 'Keys', 'name', 'IDLE Classic Unix')
884
+ d.builtinlist.SetMenu(item_list, 'IDLE Modern UNIX')
885
+ eq(mainpage, {'Keys': {'name2': 'IDLE Modern UNIX'}})
886
+ eq(d.keys_message['text'], 'New key set, see Help')
887
+ eq(d.load_keys_list.called, 2)
888
+ eq(d.load_keys_list.args, ('IDLE Modern UNIX', ))
889
+
890
+ # Builtin name in old_keys.
891
+ changes.clear()
892
+ d.builtinlist.SetMenu(item_list, 'IDLE Classic OSX')
893
+ eq(mainpage, {'Keys': {'name': 'IDLE Classic OSX', 'name2': ''}})
894
+ eq(d.keys_message['text'], '')
895
+ eq(d.load_keys_list.called, 3)
896
+ eq(d.load_keys_list.args, ('IDLE Classic OSX', ))
897
+
898
+ def test_custom_name(self):
899
+ d = self.page
900
+
901
+ # If no selections, doesn't get added.
902
+ d.customlist.SetMenu([], '- no custom keys -')
903
+ self.assertNotIn('Keys', mainpage)
904
+ self.assertEqual(d.load_keys_list.called, 0)
905
+
906
+ # Custom name selected.
907
+ changes.clear()
908
+ d.customlist.SetMenu(['a', 'b', 'c'], 'c')
909
+ self.assertEqual(mainpage, {'Keys': {'name': 'c'}})
910
+ self.assertEqual(d.load_keys_list.called, 1)
911
+
912
+ def test_keybinding(self):
913
+ idleConf.SetOption('extensions', 'ZzDummy', 'enable', 'True')
914
+ d = self.page
915
+ d.custom_name.set('my custom keys')
916
+ d.bindingslist.delete(0, 'end')
917
+ d.bindingslist.insert(0, 'copy')
918
+ d.bindingslist.insert(1, 'z-in')
919
+ d.bindingslist.selection_set(0)
920
+ d.bindingslist.selection_anchor(0)
921
+ # Core binding - adds to keys.
922
+ d.keybinding.set('<Key-F11>')
923
+ self.assertEqual(keyspage,
924
+ {'my custom keys': {'copy': '<Key-F11>'}})
925
+
926
+ # Not a core binding - adds to extensions.
927
+ d.bindingslist.selection_set(1)
928
+ d.bindingslist.selection_anchor(1)
929
+ d.keybinding.set('<Key-F11>')
930
+ self.assertEqual(extpage,
931
+ {'ZzDummy_cfgBindings': {'z-in': '<Key-F11>'}})
932
+
933
+ def test_set_keys_type(self):
934
+ eq = self.assertEqual
935
+ d = self.page
936
+ del d.set_keys_type
937
+
938
+ # Builtin keyset selected.
939
+ d.keyset_source.set(True)
940
+ d.set_keys_type()
941
+ eq(d.builtinlist['state'], NORMAL)
942
+ eq(d.customlist['state'], DISABLED)
943
+ eq(d.button_delete_custom_keys.state(), ('disabled',))
944
+
945
+ # Custom keyset selected.
946
+ d.keyset_source.set(False)
947
+ d.set_keys_type()
948
+ eq(d.builtinlist['state'], DISABLED)
949
+ eq(d.custom_keyset_on.state(), ('selected',))
950
+ eq(d.customlist['state'], NORMAL)
951
+ eq(d.button_delete_custom_keys.state(), ())
952
+ d.set_keys_type = Func()
953
+
954
+ def test_get_new_keys(self):
955
+ eq = self.assertEqual
956
+ d = self.page
957
+ orig_getkeysdialog = configdialog.GetKeysWindow
958
+ gkd = configdialog.GetKeysWindow = Func(return_self=True)
959
+ gnkn = d.get_new_keys_name = Func()
960
+
961
+ d.button_new_keys.state(('!disabled',))
962
+ d.bindingslist.delete(0, 'end')
963
+ d.bindingslist.insert(0, 'copy - <Control-Shift-Key-C>')
964
+ d.bindingslist.selection_set(0)
965
+ d.bindingslist.selection_anchor(0)
966
+ d.keybinding.set('Key-a')
967
+ d.keyset_source.set(True) # Default keyset.
968
+
969
+ # Default keyset; no change to binding.
970
+ gkd.result = ''
971
+ d.button_new_keys.invoke()
972
+ eq(d.bindingslist.get('anchor'), 'copy - <Control-Shift-Key-C>')
973
+ # Keybinding isn't changed when there isn't a change entered.
974
+ eq(d.keybinding.get(), 'Key-a')
975
+
976
+ # Default keyset; binding changed.
977
+ gkd.result = '<Key-F11>'
978
+ # No keyset name selected therefore binding not saved.
979
+ gnkn.result = ''
980
+ d.button_new_keys.invoke()
981
+ eq(gnkn.called, 1)
982
+ eq(d.bindingslist.get('anchor'), 'copy - <Control-Shift-Key-C>')
983
+ # Keyset name selected.
984
+ gnkn.result = 'My New Key Set'
985
+ d.button_new_keys.invoke()
986
+ eq(d.custom_name.get(), gnkn.result)
987
+ eq(d.bindingslist.get('anchor'), 'copy - <Key-F11>')
988
+ eq(d.keybinding.get(), '<Key-F11>')
989
+
990
+ # User keyset; binding changed.
991
+ d.keyset_source.set(False) # Custom keyset.
992
+ gnkn.called = 0
993
+ gkd.result = '<Key-p>'
994
+ d.button_new_keys.invoke()
995
+ eq(gnkn.called, 0)
996
+ eq(d.bindingslist.get('anchor'), 'copy - <Key-p>')
997
+ eq(d.keybinding.get(), '<Key-p>')
998
+
999
+ del d.get_new_keys_name
1000
+ configdialog.GetKeysWindow = orig_getkeysdialog
1001
+
1002
+ def test_get_new_keys_name(self):
1003
+ orig_sectionname = configdialog.SectionName
1004
+ sn = configdialog.SectionName = Func(return_self=True)
1005
+ d = self.page
1006
+
1007
+ sn.result = 'New Keys'
1008
+ self.assertEqual(d.get_new_keys_name(''), 'New Keys')
1009
+
1010
+ configdialog.SectionName = orig_sectionname
1011
+
1012
+ def test_save_as_new_key_set(self):
1013
+ d = self.page
1014
+ gnkn = d.get_new_keys_name = Func()
1015
+ d.keyset_source.set(True)
1016
+
1017
+ # No name entered.
1018
+ gnkn.result = ''
1019
+ d.button_save_custom_keys.invoke()
1020
+
1021
+ # Name entered.
1022
+ gnkn.result = 'my new key set'
1023
+ gnkn.called = 0
1024
+ self.assertNotIn(gnkn.result, idleConf.userCfg['keys'])
1025
+ d.button_save_custom_keys.invoke()
1026
+ self.assertIn(gnkn.result, idleConf.userCfg['keys'])
1027
+
1028
+ del d.get_new_keys_name
1029
+
1030
+ def test_on_bindingslist_select(self):
1031
+ d = self.page
1032
+ b = d.bindingslist
1033
+ b.delete(0, 'end')
1034
+ b.insert(0, 'copy')
1035
+ b.insert(1, 'find')
1036
+ b.activate(0)
1037
+
1038
+ b.focus_force()
1039
+ b.see(1)
1040
+ b.update()
1041
+ x, y, dx, dy = b.bbox(1)
1042
+ x += dx // 2
1043
+ y += dy // 2
1044
+ b.event_generate('<Enter>', x=0, y=0)
1045
+ b.event_generate('<Motion>', x=x, y=y)
1046
+ b.event_generate('<Button-1>', x=x, y=y)
1047
+ b.event_generate('<ButtonRelease-1>', x=x, y=y)
1048
+ self.assertEqual(b.get('anchor'), 'find')
1049
+ self.assertEqual(d.button_new_keys.state(), ())
1050
+
1051
+ def test_create_new_key_set_and_save_new_key_set(self):
1052
+ eq = self.assertEqual
1053
+ d = self.page
1054
+
1055
+ # Use default as previously active keyset.
1056
+ d.keyset_source.set(True)
1057
+ d.builtin_name.set('IDLE Classic Windows')
1058
+ first_new = 'my new custom key set'
1059
+ second_new = 'my second custom keyset'
1060
+
1061
+ # No changes, so keysets are an exact copy.
1062
+ self.assertNotIn(first_new, idleConf.userCfg)
1063
+ d.create_new_key_set(first_new)
1064
+ eq(idleConf.GetSectionList('user', 'keys'), [first_new])
1065
+ eq(idleConf.GetKeySet('IDLE Classic Windows'),
1066
+ idleConf.GetKeySet(first_new))
1067
+ eq(d.custom_name.get(), first_new)
1068
+ self.assertFalse(d.keyset_source.get()) # Use custom set.
1069
+ eq(d.set_keys_type.called, 1)
1070
+
1071
+ # Test that changed keybindings are in new keyset.
1072
+ changes.add_option('keys', first_new, 'copy', '<Key-F11>')
1073
+ self.assertNotIn(second_new, idleConf.userCfg)
1074
+ d.create_new_key_set(second_new)
1075
+ eq(idleConf.GetSectionList('user', 'keys'), [first_new, second_new])
1076
+ self.assertNotEqual(idleConf.GetKeySet(first_new),
1077
+ idleConf.GetKeySet(second_new))
1078
+ # Check that difference in keysets was in option `copy` from `changes`.
1079
+ idleConf.SetOption('keys', first_new, 'copy', '<Key-F11>')
1080
+ eq(idleConf.GetKeySet(first_new), idleConf.GetKeySet(second_new))
1081
+
1082
+ def test_load_keys_list(self):
1083
+ eq = self.assertEqual
1084
+ d = self.page
1085
+ gks = idleConf.GetKeySet = Func()
1086
+ del d.load_keys_list
1087
+ b = d.bindingslist
1088
+
1089
+ b.delete(0, 'end')
1090
+ b.insert(0, '<<find>>')
1091
+ b.insert(1, '<<help>>')
1092
+ gks.result = {'<<copy>>': ['<Control-Key-c>', '<Control-Key-C>'],
1093
+ '<<force-open-completions>>': ['<Control-Key-space>'],
1094
+ '<<spam>>': ['<Key-F11>']}
1095
+ changes.add_option('keys', 'my keys', 'spam', '<Shift-Key-a>')
1096
+ expected = ('copy - <Control-Key-c> <Control-Key-C>',
1097
+ 'force-open-completions - <Control-Key-space>',
1098
+ 'spam - <Shift-Key-a>')
1099
+
1100
+ # No current selection.
1101
+ d.load_keys_list('my keys')
1102
+ eq(b.get(0, 'end'), expected)
1103
+ eq(b.get('anchor'), '')
1104
+ eq(b.curselection(), ())
1105
+
1106
+ # Check selection.
1107
+ b.selection_set(1)
1108
+ b.selection_anchor(1)
1109
+ d.load_keys_list('my keys')
1110
+ eq(b.get(0, 'end'), expected)
1111
+ eq(b.get('anchor'), 'force-open-completions - <Control-Key-space>')
1112
+ eq(b.curselection(), (1, ))
1113
+
1114
+ # Change selection.
1115
+ b.selection_set(2)
1116
+ b.selection_anchor(2)
1117
+ d.load_keys_list('my keys')
1118
+ eq(b.get(0, 'end'), expected)
1119
+ eq(b.get('anchor'), 'spam - <Shift-Key-a>')
1120
+ eq(b.curselection(), (2, ))
1121
+ d.load_keys_list = Func()
1122
+
1123
+ del idleConf.GetKeySet
1124
+
1125
+ def test_delete_custom_keys(self):
1126
+ eq = self.assertEqual
1127
+ d = self.page
1128
+ d.button_delete_custom_keys.state(('!disabled',))
1129
+ yesno = d.askyesno = Func()
1130
+ dialog.deactivate_current_config = Func()
1131
+ dialog.activate_config_changes = Func()
1132
+
1133
+ keyset_name = 'spam key set'
1134
+ idleConf.userCfg['keys'].SetOption(keyset_name, 'name', 'value')
1135
+ keyspage[keyset_name] = {'option': 'True'}
1136
+
1137
+ keyset_name2 = 'other key set'
1138
+ idleConf.userCfg['keys'].SetOption(keyset_name2, 'name', 'value')
1139
+ keyspage[keyset_name2] = {'option': 'False'}
1140
+
1141
+ # Force custom keyset.
1142
+ d.custom_keyset_on.state(('!disabled',))
1143
+ d.custom_keyset_on.invoke()
1144
+ d.custom_name.set(keyset_name)
1145
+
1146
+ # Cancel deletion.
1147
+ yesno.result = False
1148
+ d.button_delete_custom_keys.invoke()
1149
+ eq(yesno.called, 1)
1150
+ eq(keyspage[keyset_name], {'option': 'True'})
1151
+ eq(idleConf.GetSectionList('user', 'keys'), [keyset_name, keyset_name2])
1152
+ eq(dialog.deactivate_current_config.called, 0)
1153
+ eq(dialog.activate_config_changes.called, 0)
1154
+ eq(d.set_keys_type.called, 0)
1155
+
1156
+ # Confirm deletion.
1157
+ yesno.result = True
1158
+ d.button_delete_custom_keys.invoke()
1159
+ eq(yesno.called, 2)
1160
+ self.assertNotIn(keyset_name, keyspage)
1161
+ eq(idleConf.GetSectionList('user', 'keys'), [keyset_name2])
1162
+ eq(d.custom_keyset_on.state(), ())
1163
+ eq(d.custom_name.get(), keyset_name2)
1164
+ eq(dialog.deactivate_current_config.called, 1)
1165
+ eq(dialog.activate_config_changes.called, 1)
1166
+ eq(d.set_keys_type.called, 1)
1167
+
1168
+ # Confirm deletion of second keyset - empties list.
1169
+ d.custom_name.set(keyset_name2)
1170
+ yesno.result = True
1171
+ d.button_delete_custom_keys.invoke()
1172
+ eq(yesno.called, 3)
1173
+ self.assertNotIn(keyset_name, keyspage)
1174
+ eq(idleConf.GetSectionList('user', 'keys'), [])
1175
+ eq(d.custom_keyset_on.state(), ('disabled',))
1176
+ eq(d.custom_name.get(), '- no custom keys -')
1177
+ eq(dialog.deactivate_current_config.called, 2)
1178
+ eq(dialog.activate_config_changes.called, 2)
1179
+ eq(d.set_keys_type.called, 2)
1180
+
1181
+ del dialog.activate_config_changes, dialog.deactivate_current_config
1182
+ del d.askyesno
1183
+
1184
+
1185
+ class WinPageTest(unittest.TestCase):
1186
+ """Test that general tab widgets enable users to make changes.
1187
+
1188
+ Test that widget actions set vars, that var changes add
1189
+ options to changes.
1190
+ """
1191
+ @classmethod
1192
+ def setUpClass(cls):
1193
+ page = cls.page = dialog.winpage
1194
+ dialog.note.select(page)
1195
+ page.update()
1196
+
1197
+ def setUp(self):
1198
+ changes.clear()
1199
+
1200
+ def test_load_windows_cfg(self):
1201
+ # Set to wrong values, load, check right values.
1202
+ eq = self.assertEqual
1203
+ d = self.page
1204
+ d.startup_edit.set(1)
1205
+ d.win_width.set(1)
1206
+ d.win_height.set(1)
1207
+ d.load_windows_cfg()
1208
+ eq(d.startup_edit.get(), 0)
1209
+ eq(d.win_width.get(), '80')
1210
+ eq(d.win_height.get(), '40')
1211
+
1212
+ def test_startup(self):
1213
+ d = self.page
1214
+ d.startup_editor_on.invoke()
1215
+ self.assertEqual(mainpage,
1216
+ {'General': {'editor-on-startup': '1'}})
1217
+ changes.clear()
1218
+ d.startup_shell_on.invoke()
1219
+ self.assertEqual(mainpage,
1220
+ {'General': {'editor-on-startup': '0'}})
1221
+
1222
+ def test_editor_size(self):
1223
+ d = self.page
1224
+ d.win_height_int.delete(0, 'end')
1225
+ d.win_height_int.insert(0, '11')
1226
+ self.assertEqual(mainpage, {'EditorWindow': {'height': '11'}})
1227
+ changes.clear()
1228
+ d.win_width_int.delete(0, 'end')
1229
+ d.win_width_int.insert(0, '11')
1230
+ self.assertEqual(mainpage, {'EditorWindow': {'width': '11'}})
1231
+
1232
+ def test_indent_spaces(self):
1233
+ d = self.page
1234
+ d.indent_chooser.set(6)
1235
+ self.assertEqual(d.indent_spaces.get(), '6')
1236
+ self.assertEqual(mainpage, {'Indent': {'num-spaces': '6'}})
1237
+
1238
+ def test_cursor_blink(self):
1239
+ self.page.cursor_blink_bool.invoke()
1240
+ self.assertEqual(mainpage, {'EditorWindow': {'cursor-blink': 'False'}})
1241
+
1242
+ def test_autocomplete_wait(self):
1243
+ self.page.auto_wait_int.delete(0, 'end')
1244
+ self.page.auto_wait_int.insert(0, '11')
1245
+ self.assertEqual(extpage, {'AutoComplete': {'popupwait': '11'}})
1246
+
1247
+ def test_parenmatch(self):
1248
+ d = self.page
1249
+ eq = self.assertEqual
1250
+ d.paren_style_type['menu'].invoke(0)
1251
+ eq(extpage, {'ParenMatch': {'style': 'opener'}})
1252
+ changes.clear()
1253
+ d.paren_flash_time.delete(0, 'end')
1254
+ d.paren_flash_time.insert(0, '11')
1255
+ eq(extpage, {'ParenMatch': {'flash-delay': '11'}})
1256
+ changes.clear()
1257
+ d.bell_on.invoke()
1258
+ eq(extpage, {'ParenMatch': {'bell': 'False'}})
1259
+
1260
+ def test_paragraph(self):
1261
+ self.page.format_width_int.delete(0, 'end')
1262
+ self.page.format_width_int.insert(0, '11')
1263
+ self.assertEqual(extpage, {'FormatParagraph': {'max-width': '11'}})
1264
+
1265
+
1266
+ class ShedPageTest(unittest.TestCase):
1267
+ """Test that shed tab widgets enable users to make changes.
1268
+
1269
+ Test that widget actions set vars, that var changes add
1270
+ options to changes.
1271
+ """
1272
+ @classmethod
1273
+ def setUpClass(cls):
1274
+ page = cls.page = dialog.shedpage
1275
+ dialog.note.select(page)
1276
+ page.update()
1277
+
1278
+ def setUp(self):
1279
+ changes.clear()
1280
+
1281
+ def test_load_shelled_cfg(self):
1282
+ # Set to wrong values, load, check right values.
1283
+ eq = self.assertEqual
1284
+ d = self.page
1285
+ d.autosave.set(1)
1286
+ d.load_shelled_cfg()
1287
+ eq(d.autosave.get(), 0)
1288
+
1289
+ def test_autosave(self):
1290
+ d = self.page
1291
+ d.save_auto_on.invoke()
1292
+ self.assertEqual(mainpage, {'General': {'autosave': '1'}})
1293
+ d.save_ask_on.invoke()
1294
+ self.assertEqual(mainpage, {'General': {'autosave': '0'}})
1295
+
1296
+ def test_context(self):
1297
+ self.page.context_int.delete(0, 'end')
1298
+ self.page.context_int.insert(0, '1')
1299
+ self.assertEqual(extpage, {'CodeContext': {'maxlines': '1'}})
1300
+
1301
+
1302
+ #unittest.skip("Nothing here yet TODO")
1303
+ class ExtPageTest(unittest.TestCase):
1304
+ """Test that the help source list works correctly."""
1305
+ @classmethod
1306
+ def setUpClass(cls):
1307
+ page = dialog.extpage
1308
+ dialog.note.select(page)
1309
+
1310
+
1311
+ class HelpSourceTest(unittest.TestCase):
1312
+ """Test that the help source list works correctly."""
1313
+ @classmethod
1314
+ def setUpClass(cls):
1315
+ page = dialog.extpage
1316
+ dialog.note.select(page)
1317
+ frame = cls.frame = page.frame_help
1318
+ frame.set = frame.set_add_delete_state = Func()
1319
+ frame.upc = frame.update_help_changes = Func()
1320
+ frame.update()
1321
+
1322
+ @classmethod
1323
+ def tearDownClass(cls):
1324
+ frame = cls.frame
1325
+ del frame.set, frame.set_add_delete_state
1326
+ del frame.upc, frame.update_help_changes
1327
+ frame.helplist.delete(0, 'end')
1328
+ frame.user_helplist.clear()
1329
+
1330
+ def setUp(self):
1331
+ changes.clear()
1332
+
1333
+ def test_load_helplist(self):
1334
+ eq = self.assertEqual
1335
+ fr = self.frame
1336
+ fr.helplist.insert('end', 'bad')
1337
+ fr.user_helplist = ['bad', 'worse']
1338
+ idleConf.SetOption('main', 'HelpFiles', '1', 'name;file')
1339
+ fr.load_helplist()
1340
+ eq(fr.helplist.get(0, 'end'), ('name',))
1341
+ eq(fr.user_helplist, [('name', 'file', '1')])
1342
+
1343
+ def test_source_selected(self):
1344
+ fr = self.frame
1345
+ fr.set = fr.set_add_delete_state
1346
+ fr.upc = fr.update_help_changes
1347
+ helplist = fr.helplist
1348
+ dex = 'end'
1349
+ helplist.insert(dex, 'source')
1350
+ helplist.activate(dex)
1351
+
1352
+ helplist.focus_force()
1353
+ helplist.see(dex)
1354
+ helplist.update()
1355
+ x, y, dx, dy = helplist.bbox(dex)
1356
+ x += dx // 2
1357
+ y += dy // 2
1358
+ fr.set.called = fr.upc.called = 0
1359
+ helplist.event_generate('<Enter>', x=0, y=0)
1360
+ helplist.event_generate('<Motion>', x=x, y=y)
1361
+ helplist.event_generate('<Button-1>', x=x, y=y)
1362
+ helplist.event_generate('<ButtonRelease-1>', x=x, y=y)
1363
+ self.assertEqual(helplist.get('anchor'), 'source')
1364
+ self.assertTrue(fr.set.called)
1365
+ self.assertFalse(fr.upc.called)
1366
+
1367
+ def test_set_add_delete_state(self):
1368
+ # Call with 0 items, 1 unselected item, 1 selected item.
1369
+ eq = self.assertEqual
1370
+ fr = self.frame
1371
+ del fr.set_add_delete_state # Unmask method.
1372
+ sad = fr.set_add_delete_state
1373
+ h = fr.helplist
1374
+
1375
+ h.delete(0, 'end')
1376
+ sad()
1377
+ eq(fr.button_helplist_edit.state(), ('disabled',))
1378
+ eq(fr.button_helplist_remove.state(), ('disabled',))
1379
+
1380
+ h.insert(0, 'source')
1381
+ sad()
1382
+ eq(fr.button_helplist_edit.state(), ('disabled',))
1383
+ eq(fr.button_helplist_remove.state(), ('disabled',))
1384
+
1385
+ h.selection_set(0)
1386
+ sad()
1387
+ eq(fr.button_helplist_edit.state(), ())
1388
+ eq(fr.button_helplist_remove.state(), ())
1389
+ fr.set_add_delete_state = Func() # Mask method.
1390
+
1391
+ def test_helplist_item_add(self):
1392
+ # Call without and twice with HelpSource result.
1393
+ # Double call enables check on order.
1394
+ eq = self.assertEqual
1395
+ orig_helpsource = configdialog.HelpSource
1396
+ hs = configdialog.HelpSource = Func(return_self=True)
1397
+ fr = self.frame
1398
+ fr.helplist.delete(0, 'end')
1399
+ fr.user_helplist.clear()
1400
+ fr.set.called = fr.upc.called = 0
1401
+
1402
+ hs.result = ''
1403
+ fr.helplist_item_add()
1404
+ self.assertTrue(list(fr.helplist.get(0, 'end')) ==
1405
+ fr.user_helplist == [])
1406
+ self.assertFalse(fr.upc.called)
1407
+
1408
+ hs.result = ('name1', 'file1')
1409
+ fr.helplist_item_add()
1410
+ hs.result = ('name2', 'file2')
1411
+ fr.helplist_item_add()
1412
+ eq(fr.helplist.get(0, 'end'), ('name1', 'name2'))
1413
+ eq(fr.user_helplist, [('name1', 'file1'), ('name2', 'file2')])
1414
+ eq(fr.upc.called, 2)
1415
+ self.assertFalse(fr.set.called)
1416
+
1417
+ configdialog.HelpSource = orig_helpsource
1418
+
1419
+ def test_helplist_item_edit(self):
1420
+ # Call without and with HelpSource change.
1421
+ eq = self.assertEqual
1422
+ orig_helpsource = configdialog.HelpSource
1423
+ hs = configdialog.HelpSource = Func(return_self=True)
1424
+ fr = self.frame
1425
+ fr.helplist.delete(0, 'end')
1426
+ fr.helplist.insert(0, 'name1')
1427
+ fr.helplist.selection_set(0)
1428
+ fr.helplist.selection_anchor(0)
1429
+ fr.user_helplist.clear()
1430
+ fr.user_helplist.append(('name1', 'file1'))
1431
+ fr.set.called = fr.upc.called = 0
1432
+
1433
+ hs.result = ''
1434
+ fr.helplist_item_edit()
1435
+ hs.result = ('name1', 'file1')
1436
+ fr.helplist_item_edit()
1437
+ eq(fr.helplist.get(0, 'end'), ('name1',))
1438
+ eq(fr.user_helplist, [('name1', 'file1')])
1439
+ self.assertFalse(fr.upc.called)
1440
+
1441
+ hs.result = ('name2', 'file2')
1442
+ fr.helplist_item_edit()
1443
+ eq(fr.helplist.get(0, 'end'), ('name2',))
1444
+ eq(fr.user_helplist, [('name2', 'file2')])
1445
+ self.assertTrue(fr.upc.called == fr.set.called == 1)
1446
+
1447
+ configdialog.HelpSource = orig_helpsource
1448
+
1449
+ def test_helplist_item_remove(self):
1450
+ eq = self.assertEqual
1451
+ fr = self.frame
1452
+ fr.helplist.delete(0, 'end')
1453
+ fr.helplist.insert(0, 'name1')
1454
+ fr.helplist.selection_set(0)
1455
+ fr.helplist.selection_anchor(0)
1456
+ fr.user_helplist.clear()
1457
+ fr.user_helplist.append(('name1', 'file1'))
1458
+ fr.set.called = fr.upc.called = 0
1459
+
1460
+ fr.helplist_item_remove()
1461
+ eq(fr.helplist.get(0, 'end'), ())
1462
+ eq(fr.user_helplist, [])
1463
+ self.assertTrue(fr.upc.called == fr.set.called == 1)
1464
+
1465
+ def test_update_help_changes(self):
1466
+ fr = self.frame
1467
+ del fr.update_help_changes
1468
+ fr.user_helplist.clear()
1469
+ fr.user_helplist.append(('name1', 'file1'))
1470
+ fr.user_helplist.append(('name2', 'file2'))
1471
+
1472
+ fr.update_help_changes()
1473
+ self.assertEqual(mainpage['HelpFiles'],
1474
+ {'1': 'name1;file1', '2': 'name2;file2'})
1475
+ fr.update_help_changes = Func()
1476
+
1477
+
1478
+ class VarTraceTest(unittest.TestCase):
1479
+
1480
+ @classmethod
1481
+ def setUpClass(cls):
1482
+ cls.tracers = configdialog.VarTrace()
1483
+ cls.iv = IntVar(root)
1484
+ cls.bv = BooleanVar(root)
1485
+
1486
+ @classmethod
1487
+ def tearDownClass(cls):
1488
+ del cls.tracers, cls.iv, cls.bv
1489
+
1490
+ def setUp(self):
1491
+ self.tracers.clear()
1492
+ self.called = 0
1493
+
1494
+ def var_changed_increment(self, *params):
1495
+ self.called += 13
1496
+
1497
+ def var_changed_boolean(self, *params):
1498
+ pass
1499
+
1500
+ def test_init(self):
1501
+ tr = self.tracers
1502
+ tr.__init__()
1503
+ self.assertEqual(tr.untraced, [])
1504
+ self.assertEqual(tr.traced, [])
1505
+
1506
+ def test_clear(self):
1507
+ tr = self.tracers
1508
+ tr.untraced.append(0)
1509
+ tr.traced.append(1)
1510
+ tr.clear()
1511
+ self.assertEqual(tr.untraced, [])
1512
+ self.assertEqual(tr.traced, [])
1513
+
1514
+ def test_add(self):
1515
+ tr = self.tracers
1516
+ func = Func()
1517
+ cb = tr.make_callback = mock.Mock(return_value=func)
1518
+
1519
+ iv = tr.add(self.iv, self.var_changed_increment)
1520
+ self.assertIs(iv, self.iv)
1521
+ bv = tr.add(self.bv, self.var_changed_boolean)
1522
+ self.assertIs(bv, self.bv)
1523
+
1524
+ sv = StringVar(root)
1525
+ sv2 = tr.add(sv, ('main', 'section', 'option'))
1526
+ self.assertIs(sv2, sv)
1527
+ cb.assert_called_once()
1528
+ cb.assert_called_with(sv, ('main', 'section', 'option'))
1529
+
1530
+ expected = [(iv, self.var_changed_increment),
1531
+ (bv, self.var_changed_boolean),
1532
+ (sv, func)]
1533
+ self.assertEqual(tr.traced, [])
1534
+ self.assertEqual(tr.untraced, expected)
1535
+
1536
+ del tr.make_callback
1537
+
1538
+ def test_make_callback(self):
1539
+ cb = self.tracers.make_callback(self.iv, ('main', 'section', 'option'))
1540
+ self.assertTrue(callable(cb))
1541
+ self.iv.set(42)
1542
+ # Not attached, so set didn't invoke the callback.
1543
+ self.assertNotIn('section', changes['main'])
1544
+ # Invoke callback manually.
1545
+ cb()
1546
+ self.assertIn('section', changes['main'])
1547
+ self.assertEqual(changes['main']['section']['option'], '42')
1548
+ changes.clear()
1549
+
1550
+ def test_attach_detach(self):
1551
+ tr = self.tracers
1552
+ iv = tr.add(self.iv, self.var_changed_increment)
1553
+ bv = tr.add(self.bv, self.var_changed_boolean)
1554
+ expected = [(iv, self.var_changed_increment),
1555
+ (bv, self.var_changed_boolean)]
1556
+
1557
+ # Attach callbacks and test call increment.
1558
+ tr.attach()
1559
+ self.assertEqual(tr.untraced, [])
1560
+ self.assertCountEqual(tr.traced, expected)
1561
+ iv.set(1)
1562
+ self.assertEqual(iv.get(), 1)
1563
+ self.assertEqual(self.called, 13)
1564
+
1565
+ # Check that only one callback is attached to a variable.
1566
+ # If more than one callback were attached, then var_changed_increment
1567
+ # would be called twice and the counter would be 2.
1568
+ self.called = 0
1569
+ tr.attach()
1570
+ iv.set(1)
1571
+ self.assertEqual(self.called, 13)
1572
+
1573
+ # Detach callbacks.
1574
+ self.called = 0
1575
+ tr.detach()
1576
+ self.assertEqual(tr.traced, [])
1577
+ self.assertCountEqual(tr.untraced, expected)
1578
+ iv.set(1)
1579
+ self.assertEqual(self.called, 0)
1580
+
1581
+
1582
+ if __name__ == '__main__':
1583
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_debugger.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Test debugger, coverage 19%"
2
+
3
+ from idlelib import debugger
4
+ import unittest
5
+ from test.support import requires
6
+ requires('gui')
7
+ from tkinter import Tk
8
+
9
+
10
+ class NameSpaceTest(unittest.TestCase):
11
+
12
+ @classmethod
13
+ def setUpClass(cls):
14
+ cls.root = Tk()
15
+ cls.root.withdraw()
16
+
17
+ @classmethod
18
+ def tearDownClass(cls):
19
+ cls.root.destroy()
20
+ del cls.root
21
+
22
+ def test_init(self):
23
+ debugger.NamespaceViewer(self.root, 'Test')
24
+
25
+
26
+ # Other classes are Idb, Debugger, and StackViewer.
27
+
28
+ if __name__ == '__main__':
29
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_debugobj.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Test debugobj, coverage 40%."
2
+
3
+ from idlelib import debugobj
4
+ import unittest
5
+
6
+
7
+ class ObjectTreeItemTest(unittest.TestCase):
8
+
9
+ def test_init(self):
10
+ ti = debugobj.ObjectTreeItem('label', 22)
11
+ self.assertEqual(ti.labeltext, 'label')
12
+ self.assertEqual(ti.object, 22)
13
+ self.assertEqual(ti.setfunction, None)
14
+
15
+
16
+ class ClassTreeItemTest(unittest.TestCase):
17
+
18
+ def test_isexpandable(self):
19
+ ti = debugobj.ClassTreeItem('label', 0)
20
+ self.assertTrue(ti.IsExpandable())
21
+
22
+
23
+ class AtomicObjectTreeItemTest(unittest.TestCase):
24
+
25
+ def test_isexpandable(self):
26
+ ti = debugobj.AtomicObjectTreeItem('label', 0)
27
+ self.assertFalse(ti.IsExpandable())
28
+
29
+
30
+ class SequenceTreeItemTest(unittest.TestCase):
31
+
32
+ def test_isexpandable(self):
33
+ ti = debugobj.SequenceTreeItem('label', ())
34
+ self.assertFalse(ti.IsExpandable())
35
+ ti = debugobj.SequenceTreeItem('label', (1,))
36
+ self.assertTrue(ti.IsExpandable())
37
+
38
+ def test_keys(self):
39
+ ti = debugobj.SequenceTreeItem('label', 'abc')
40
+ self.assertEqual(list(ti.keys()), [0, 1, 2])
41
+
42
+
43
+ class DictTreeItemTest(unittest.TestCase):
44
+
45
+ def test_isexpandable(self):
46
+ ti = debugobj.DictTreeItem('label', {})
47
+ self.assertFalse(ti.IsExpandable())
48
+ ti = debugobj.DictTreeItem('label', {1:1})
49
+ self.assertTrue(ti.IsExpandable())
50
+
51
+ def test_keys(self):
52
+ ti = debugobj.DictTreeItem('label', {1:1, 0:0, 2:2})
53
+ self.assertEqual(ti.keys(), [0, 1, 2])
54
+
55
+
56
+ if __name__ == '__main__':
57
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_debugobj_r.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Test debugobj_r, coverage 56%."
2
+
3
+ from idlelib import debugobj_r
4
+ import unittest
5
+
6
+
7
+ class WrappedObjectTreeItemTest(unittest.TestCase):
8
+
9
+ def test_getattr(self):
10
+ ti = debugobj_r.WrappedObjectTreeItem(list)
11
+ self.assertEqual(ti.append, list.append)
12
+
13
+ class StubObjectTreeItemTest(unittest.TestCase):
14
+
15
+ def test_init(self):
16
+ ti = debugobj_r.StubObjectTreeItem('socket', 1111)
17
+ self.assertEqual(ti.sockio, 'socket')
18
+ self.assertEqual(ti.oid, 1111)
19
+
20
+
21
+ if __name__ == '__main__':
22
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_delegator.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Test delegator, coverage 100%."
2
+
3
+ from idlelib.delegator import Delegator
4
+ import unittest
5
+
6
+
7
+ class DelegatorTest(unittest.TestCase):
8
+
9
+ def test_mydel(self):
10
+ # Test a simple use scenario.
11
+
12
+ # Initialize an int delegator.
13
+ mydel = Delegator(int)
14
+ self.assertIs(mydel.delegate, int)
15
+ self.assertEqual(mydel._Delegator__cache, set())
16
+ # Trying to access a non-attribute of int fails.
17
+ self.assertRaises(AttributeError, mydel.__getattr__, 'xyz')
18
+
19
+ # Add real int attribute 'bit_length' by accessing it.
20
+ bl = mydel.bit_length
21
+ self.assertIs(bl, int.bit_length)
22
+ self.assertIs(mydel.__dict__['bit_length'], int.bit_length)
23
+ self.assertEqual(mydel._Delegator__cache, {'bit_length'})
24
+
25
+ # Add attribute 'numerator'.
26
+ mydel.numerator
27
+ self.assertEqual(mydel._Delegator__cache, {'bit_length', 'numerator'})
28
+
29
+ # Delete 'numerator'.
30
+ del mydel.numerator
31
+ self.assertNotIn('numerator', mydel.__dict__)
32
+ # The current implementation leaves it in the name cache.
33
+ # self.assertIn('numerator', mydel._Delegator__cache)
34
+ # However, this is not required and not part of the specification
35
+
36
+ # Change delegate to float, first resetting the attributes.
37
+ mydel.setdelegate(float) # calls resetcache
38
+ self.assertNotIn('bit_length', mydel.__dict__)
39
+ self.assertEqual(mydel._Delegator__cache, set())
40
+ self.assertIs(mydel.delegate, float)
41
+
42
+
43
+ if __name__ == '__main__':
44
+ unittest.main(verbosity=2, exit=2)
llava/lib/python3.10/idlelib/idle_test/test_editmenu.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''Test (selected) IDLE Edit menu items.
2
+
3
+ Edit modules have their own test files
4
+ '''
5
+ from test.support import requires
6
+ requires('gui')
7
+ import tkinter as tk
8
+ from tkinter import ttk
9
+ import unittest
10
+ from idlelib import pyshell
11
+
12
+ class PasteTest(unittest.TestCase):
13
+ '''Test pasting into widgets that allow pasting.
14
+
15
+ On X11, replacing selections requires tk fix.
16
+ '''
17
+ @classmethod
18
+ def setUpClass(cls):
19
+ cls.root = root = tk.Tk()
20
+ cls.root.withdraw()
21
+ pyshell.fix_x11_paste(root)
22
+ cls.text = tk.Text(root)
23
+ cls.entry = tk.Entry(root)
24
+ cls.tentry = ttk.Entry(root)
25
+ cls.spin = tk.Spinbox(root)
26
+ root.clipboard_clear()
27
+ root.clipboard_append('two')
28
+
29
+ @classmethod
30
+ def tearDownClass(cls):
31
+ del cls.text, cls.entry, cls.tentry
32
+ cls.root.clipboard_clear()
33
+ cls.root.update_idletasks()
34
+ cls.root.destroy()
35
+ del cls.root
36
+
37
+ def test_paste_text(self):
38
+ "Test pasting into text with and without a selection."
39
+ text = self.text
40
+ for tag, ans in ('', 'onetwo\n'), ('sel', 'two\n'):
41
+ with self.subTest(tag=tag, ans=ans):
42
+ text.delete('1.0', 'end')
43
+ text.insert('1.0', 'one', tag)
44
+ text.event_generate('<<Paste>>')
45
+ self.assertEqual(text.get('1.0', 'end'), ans)
46
+
47
+ def test_paste_entry(self):
48
+ "Test pasting into an entry with and without a selection."
49
+ # Generated <<Paste>> fails for tk entry without empty select
50
+ # range for 'no selection'. Live widget works fine.
51
+ for entry in self.entry, self.tentry:
52
+ for end, ans in (0, 'onetwo'), ('end', 'two'):
53
+ with self.subTest(entry=entry, end=end, ans=ans):
54
+ entry.delete(0, 'end')
55
+ entry.insert(0, 'one')
56
+ entry.select_range(0, end)
57
+ entry.event_generate('<<Paste>>')
58
+ self.assertEqual(entry.get(), ans)
59
+
60
+ def test_paste_spin(self):
61
+ "Test pasting into a spinbox with and without a selection."
62
+ # See note above for entry.
63
+ spin = self.spin
64
+ for end, ans in (0, 'onetwo'), ('end', 'two'):
65
+ with self.subTest(end=end, ans=ans):
66
+ spin.delete(0, 'end')
67
+ spin.insert(0, 'one')
68
+ spin.selection('range', 0, end) # see note
69
+ spin.event_generate('<<Paste>>')
70
+ self.assertEqual(spin.get(), ans)
71
+
72
+
73
+ if __name__ == '__main__':
74
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_grep.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ !Changing this line will break Test_findfile.test_found!
2
+ Non-gui unit tests for grep.GrepDialog methods.
3
+ dummy_command calls grep_it calls findfiles.
4
+ An exception raised in one method will fail callers.
5
+ Otherwise, tests are mostly independent.
6
+ Currently only test grep_it, coverage 51%.
7
+ """
8
+ from idlelib import grep
9
+ import unittest
10
+ from test.support import captured_stdout
11
+ from idlelib.idle_test.mock_tk import Var
12
+ import os
13
+ import re
14
+
15
+
16
+ class Dummy_searchengine:
17
+ '''GrepDialog.__init__ calls parent SearchDiabolBase which attaches the
18
+ passed in SearchEngine instance as attribute 'engine'. Only a few of the
19
+ many possible self.engine.x attributes are needed here.
20
+ '''
21
+ def getpat(self):
22
+ return self._pat
23
+
24
+ searchengine = Dummy_searchengine()
25
+
26
+
27
+ class Dummy_grep:
28
+ # Methods tested
29
+ #default_command = GrepDialog.default_command
30
+ grep_it = grep.GrepDialog.grep_it
31
+ # Other stuff needed
32
+ recvar = Var(False)
33
+ engine = searchengine
34
+ def close(self): # gui method
35
+ pass
36
+
37
+ _grep = Dummy_grep()
38
+
39
+
40
+ class FindfilesTest(unittest.TestCase):
41
+
42
+ @classmethod
43
+ def setUpClass(cls):
44
+ cls.realpath = os.path.realpath(__file__)
45
+ cls.path = os.path.dirname(cls.realpath)
46
+
47
+ @classmethod
48
+ def tearDownClass(cls):
49
+ del cls.realpath, cls.path
50
+
51
+ def test_invaliddir(self):
52
+ with captured_stdout() as s:
53
+ filelist = list(grep.findfiles('invaliddir', '*.*', False))
54
+ self.assertEqual(filelist, [])
55
+ self.assertIn('invalid', s.getvalue())
56
+
57
+ def test_curdir(self):
58
+ # Test os.curdir.
59
+ ff = grep.findfiles
60
+ save_cwd = os.getcwd()
61
+ os.chdir(self.path)
62
+ filename = 'test_grep.py'
63
+ filelist = list(ff(os.curdir, filename, False))
64
+ self.assertIn(os.path.join(os.curdir, filename), filelist)
65
+ os.chdir(save_cwd)
66
+
67
+ def test_base(self):
68
+ ff = grep.findfiles
69
+ readme = os.path.join(self.path, 'README.txt')
70
+
71
+ # Check for Python files in path where this file lives.
72
+ filelist = list(ff(self.path, '*.py', False))
73
+ # This directory has many Python files.
74
+ self.assertGreater(len(filelist), 10)
75
+ self.assertIn(self.realpath, filelist)
76
+ self.assertNotIn(readme, filelist)
77
+
78
+ # Look for .txt files in path where this file lives.
79
+ filelist = list(ff(self.path, '*.txt', False))
80
+ self.assertNotEqual(len(filelist), 0)
81
+ self.assertNotIn(self.realpath, filelist)
82
+ self.assertIn(readme, filelist)
83
+
84
+ # Look for non-matching pattern.
85
+ filelist = list(ff(self.path, 'grep.*', False))
86
+ self.assertEqual(len(filelist), 0)
87
+ self.assertNotIn(self.realpath, filelist)
88
+
89
+ def test_recurse(self):
90
+ ff = grep.findfiles
91
+ parent = os.path.dirname(self.path)
92
+ grepfile = os.path.join(parent, 'grep.py')
93
+ pat = '*.py'
94
+
95
+ # Get Python files only in parent directory.
96
+ filelist = list(ff(parent, pat, False))
97
+ parent_size = len(filelist)
98
+ # Lots of Python files in idlelib.
99
+ self.assertGreater(parent_size, 20)
100
+ self.assertIn(grepfile, filelist)
101
+ # Without subdirectories, this file isn't returned.
102
+ self.assertNotIn(self.realpath, filelist)
103
+
104
+ # Include subdirectories.
105
+ filelist = list(ff(parent, pat, True))
106
+ # More files found now.
107
+ self.assertGreater(len(filelist), parent_size)
108
+ self.assertIn(grepfile, filelist)
109
+ # This file exists in list now.
110
+ self.assertIn(self.realpath, filelist)
111
+
112
+ # Check another level up the tree.
113
+ parent = os.path.dirname(parent)
114
+ filelist = list(ff(parent, '*.py', True))
115
+ self.assertIn(self.realpath, filelist)
116
+
117
+
118
+ class Grep_itTest(unittest.TestCase):
119
+ # Test captured reports with 0 and some hits.
120
+ # Should test file names, but Windows reports have mixed / and \ separators
121
+ # from incomplete replacement, so 'later'.
122
+
123
+ def report(self, pat):
124
+ _grep.engine._pat = pat
125
+ with captured_stdout() as s:
126
+ _grep.grep_it(re.compile(pat), __file__)
127
+ lines = s.getvalue().split('\n')
128
+ lines.pop() # remove bogus '' after last \n
129
+ return lines
130
+
131
+ def test_unfound(self):
132
+ pat = 'xyz*'*7
133
+ lines = self.report(pat)
134
+ self.assertEqual(len(lines), 2)
135
+ self.assertIn(pat, lines[0])
136
+ self.assertEqual(lines[1], 'No hits.')
137
+
138
+ def test_found(self):
139
+
140
+ pat = '""" !Changing this line will break Test_findfile.test_found!'
141
+ lines = self.report(pat)
142
+ self.assertEqual(len(lines), 5)
143
+ self.assertIn(pat, lines[0])
144
+ self.assertIn('py: 1:', lines[1]) # line number 1
145
+ self.assertIn('2', lines[3]) # hits found 2
146
+ self.assertTrue(lines[4].startswith('(Hint:'))
147
+
148
+
149
+ class Default_commandTest(unittest.TestCase):
150
+ # To write this, move outwin import to top of GrepDialog
151
+ # so it can be replaced by captured_stdout in class setup/teardown.
152
+ pass
153
+
154
+
155
+ if __name__ == '__main__':
156
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_help.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Test help, coverage 87%."
2
+
3
+ from idlelib import help
4
+ import unittest
5
+ from test.support import requires
6
+ requires('gui')
7
+ from os.path import abspath, dirname, join
8
+ from tkinter import Tk
9
+
10
+
11
+ class HelpFrameTest(unittest.TestCase):
12
+
13
+ @classmethod
14
+ def setUpClass(cls):
15
+ "By itself, this tests that file parsed without exception."
16
+ cls.root = root = Tk()
17
+ root.withdraw()
18
+ helpfile = join(dirname(dirname(abspath(__file__))), 'help.html')
19
+ cls.frame = help.HelpFrame(root, helpfile)
20
+
21
+ @classmethod
22
+ def tearDownClass(cls):
23
+ del cls.frame
24
+ cls.root.update_idletasks()
25
+ cls.root.destroy()
26
+ del cls.root
27
+
28
+ def test_line1(self):
29
+ text = self.frame.text
30
+ self.assertEqual(text.get('1.0', '1.end'), ' IDLE ')
31
+
32
+
33
+ if __name__ == '__main__':
34
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_help_about.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test help_about, coverage 100%.
2
+ help_about.build_bits branches on sys.platform='darwin'.
3
+ '100% combines coverage on Mac and others.
4
+ """
5
+
6
+ from idlelib import help_about
7
+ import unittest
8
+ from test.support import requires, findfile
9
+ from tkinter import Tk, TclError
10
+ from idlelib.idle_test.mock_idle import Func
11
+ from idlelib.idle_test.mock_tk import Mbox_func
12
+ from idlelib import textview
13
+ import os.path
14
+ from platform import python_version
15
+
16
+ About = help_about.AboutDialog
17
+
18
+
19
+ class LiveDialogTest(unittest.TestCase):
20
+ """Simulate user clicking buttons other than [Close].
21
+
22
+ Test that invoked textview has text from source.
23
+ """
24
+ @classmethod
25
+ def setUpClass(cls):
26
+ requires('gui')
27
+ cls.root = Tk()
28
+ cls.root.withdraw()
29
+ cls.dialog = About(cls.root, 'About IDLE', _utest=True)
30
+
31
+ @classmethod
32
+ def tearDownClass(cls):
33
+ del cls.dialog
34
+ cls.root.update_idletasks()
35
+ cls.root.destroy()
36
+ del cls.root
37
+
38
+ def test_build_bits(self):
39
+ self.assertIn(help_about.build_bits(), ('32', '64'))
40
+
41
+ def test_dialog_title(self):
42
+ """Test about dialog title"""
43
+ self.assertEqual(self.dialog.title(), 'About IDLE')
44
+
45
+ def test_dialog_logo(self):
46
+ """Test about dialog logo."""
47
+ path, file = os.path.split(self.dialog.icon_image['file'])
48
+ fn, ext = os.path.splitext(file)
49
+ self.assertEqual(fn, 'idle_48')
50
+
51
+ def test_printer_buttons(self):
52
+ """Test buttons whose commands use printer function."""
53
+ dialog = self.dialog
54
+ button_sources = [(dialog.py_license, license, 'license'),
55
+ (dialog.py_copyright, copyright, 'copyright'),
56
+ (dialog.py_credits, credits, 'credits')]
57
+
58
+ for button, printer, name in button_sources:
59
+ with self.subTest(name=name):
60
+ printer._Printer__setup()
61
+ button.invoke()
62
+ get = dialog._current_textview.viewframe.textframe.text.get
63
+ lines = printer._Printer__lines
64
+ if len(lines) < 2:
65
+ self.fail(name + ' full text was not found')
66
+ self.assertEqual(lines[0], get('1.0', '1.end'))
67
+ self.assertEqual(lines[1], get('2.0', '2.end'))
68
+ dialog._current_textview.destroy()
69
+
70
+ def test_file_buttons(self):
71
+ """Test buttons that display files."""
72
+ dialog = self.dialog
73
+ button_sources = [(self.dialog.readme, 'README.txt', 'readme'),
74
+ (self.dialog.idle_news, 'NEWS.txt', 'news'),
75
+ (self.dialog.idle_credits, 'CREDITS.txt', 'credits')]
76
+
77
+ for button, filename, name in button_sources:
78
+ with self.subTest(name=name):
79
+ button.invoke()
80
+ fn = findfile(filename, subdir='idlelib')
81
+ get = dialog._current_textview.viewframe.textframe.text.get
82
+ with open(fn, encoding='utf-8') as f:
83
+ self.assertEqual(f.readline().strip(), get('1.0', '1.end'))
84
+ f.readline()
85
+ self.assertEqual(f.readline().strip(), get('3.0', '3.end'))
86
+ dialog._current_textview.destroy()
87
+
88
+
89
+ class DefaultTitleTest(unittest.TestCase):
90
+ "Test default title."
91
+
92
+ @classmethod
93
+ def setUpClass(cls):
94
+ requires('gui')
95
+ cls.root = Tk()
96
+ cls.root.withdraw()
97
+ cls.dialog = About(cls.root, _utest=True)
98
+
99
+ @classmethod
100
+ def tearDownClass(cls):
101
+ del cls.dialog
102
+ cls.root.update_idletasks()
103
+ cls.root.destroy()
104
+ del cls.root
105
+
106
+ def test_dialog_title(self):
107
+ """Test about dialog title"""
108
+ self.assertEqual(self.dialog.title(),
109
+ f'About IDLE {python_version()}'
110
+ f' ({help_about.build_bits()} bit)')
111
+
112
+
113
+ class CloseTest(unittest.TestCase):
114
+ """Simulate user clicking [Close] button"""
115
+
116
+ @classmethod
117
+ def setUpClass(cls):
118
+ requires('gui')
119
+ cls.root = Tk()
120
+ cls.root.withdraw()
121
+ cls.dialog = About(cls.root, 'About IDLE', _utest=True)
122
+
123
+ @classmethod
124
+ def tearDownClass(cls):
125
+ del cls.dialog
126
+ cls.root.update_idletasks()
127
+ cls.root.destroy()
128
+ del cls.root
129
+
130
+ def test_close(self):
131
+ self.assertEqual(self.dialog.winfo_class(), 'Toplevel')
132
+ self.dialog.button_ok.invoke()
133
+ with self.assertRaises(TclError):
134
+ self.dialog.winfo_class()
135
+
136
+
137
+ class Dummy_about_dialog:
138
+ # Dummy class for testing file display functions.
139
+ idle_credits = About.show_idle_credits
140
+ idle_readme = About.show_readme
141
+ idle_news = About.show_idle_news
142
+ # Called by the above
143
+ display_file_text = About.display_file_text
144
+ _utest = True
145
+
146
+
147
+ class DisplayFileTest(unittest.TestCase):
148
+ """Test functions that display files.
149
+
150
+ While somewhat redundant with gui-based test_file_dialog,
151
+ these unit tests run on all buildbots, not just a few.
152
+ """
153
+ dialog = Dummy_about_dialog()
154
+
155
+ @classmethod
156
+ def setUpClass(cls):
157
+ cls.orig_error = textview.showerror
158
+ cls.orig_view = textview.view_text
159
+ cls.error = Mbox_func()
160
+ cls.view = Func()
161
+ textview.showerror = cls.error
162
+ textview.view_text = cls.view
163
+
164
+ @classmethod
165
+ def tearDownClass(cls):
166
+ textview.showerror = cls.orig_error
167
+ textview.view_text = cls.orig_view
168
+
169
+ def test_file_display(self):
170
+ for handler in (self.dialog.idle_credits,
171
+ self.dialog.idle_readme,
172
+ self.dialog.idle_news):
173
+ self.error.message = ''
174
+ self.view.called = False
175
+ with self.subTest(handler=handler):
176
+ handler()
177
+ self.assertEqual(self.error.message, '')
178
+ self.assertEqual(self.view.called, True)
179
+
180
+
181
+ if __name__ == '__main__':
182
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_history.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ " Test history, coverage 100%."
2
+
3
+ from idlelib.history import History
4
+ import unittest
5
+ from test.support import requires
6
+
7
+ import tkinter as tk
8
+ from tkinter import Text as tkText
9
+ from idlelib.idle_test.mock_tk import Text as mkText
10
+ from idlelib.config import idleConf
11
+
12
+ line1 = 'a = 7'
13
+ line2 = 'b = a'
14
+
15
+
16
+ class StoreTest(unittest.TestCase):
17
+ '''Tests History.__init__ and History.store with mock Text'''
18
+
19
+ @classmethod
20
+ def setUpClass(cls):
21
+ cls.text = mkText()
22
+ cls.history = History(cls.text)
23
+
24
+ def tearDown(self):
25
+ self.text.delete('1.0', 'end')
26
+ self.history.history = []
27
+
28
+ def test_init(self):
29
+ self.assertIs(self.history.text, self.text)
30
+ self.assertEqual(self.history.history, [])
31
+ self.assertIsNone(self.history.prefix)
32
+ self.assertIsNone(self.history.pointer)
33
+ self.assertEqual(self.history.cyclic,
34
+ idleConf.GetOption("main", "History", "cyclic", 1, "bool"))
35
+
36
+ def test_store_short(self):
37
+ self.history.store('a')
38
+ self.assertEqual(self.history.history, [])
39
+ self.history.store(' a ')
40
+ self.assertEqual(self.history.history, [])
41
+
42
+ def test_store_dup(self):
43
+ self.history.store(line1)
44
+ self.assertEqual(self.history.history, [line1])
45
+ self.history.store(line2)
46
+ self.assertEqual(self.history.history, [line1, line2])
47
+ self.history.store(line1)
48
+ self.assertEqual(self.history.history, [line2, line1])
49
+
50
+ def test_store_reset(self):
51
+ self.history.prefix = line1
52
+ self.history.pointer = 0
53
+ self.history.store(line2)
54
+ self.assertIsNone(self.history.prefix)
55
+ self.assertIsNone(self.history.pointer)
56
+
57
+
58
+ class TextWrapper:
59
+ def __init__(self, master):
60
+ self.text = tkText(master=master)
61
+ self._bell = False
62
+ def __getattr__(self, name):
63
+ return getattr(self.text, name)
64
+ def bell(self):
65
+ self._bell = True
66
+
67
+
68
+ class FetchTest(unittest.TestCase):
69
+ '''Test History.fetch with wrapped tk.Text.
70
+ '''
71
+ @classmethod
72
+ def setUpClass(cls):
73
+ requires('gui')
74
+ cls.root = tk.Tk()
75
+ cls.root.withdraw()
76
+
77
+ def setUp(self):
78
+ self.text = text = TextWrapper(self.root)
79
+ text.insert('1.0', ">>> ")
80
+ text.mark_set('iomark', '1.4')
81
+ text.mark_gravity('iomark', 'left')
82
+ self.history = History(text)
83
+ self.history.history = [line1, line2]
84
+
85
+ @classmethod
86
+ def tearDownClass(cls):
87
+ cls.root.destroy()
88
+ del cls.root
89
+
90
+ def fetch_test(self, reverse, line, prefix, index, *, bell=False):
91
+ # Perform one fetch as invoked by Alt-N or Alt-P
92
+ # Test the result. The line test is the most important.
93
+ # The last two are diagnostic of fetch internals.
94
+ History = self.history
95
+ History.fetch(reverse)
96
+
97
+ Equal = self.assertEqual
98
+ Equal(self.text.get('iomark', 'end-1c'), line)
99
+ Equal(self.text._bell, bell)
100
+ if bell:
101
+ self.text._bell = False
102
+ Equal(History.prefix, prefix)
103
+ Equal(History.pointer, index)
104
+ Equal(self.text.compare("insert", '==', "end-1c"), 1)
105
+
106
+ def test_fetch_prev_cyclic(self):
107
+ prefix = ''
108
+ test = self.fetch_test
109
+ test(True, line2, prefix, 1)
110
+ test(True, line1, prefix, 0)
111
+ test(True, prefix, None, None, bell=True)
112
+
113
+ def test_fetch_next_cyclic(self):
114
+ prefix = ''
115
+ test = self.fetch_test
116
+ test(False, line1, prefix, 0)
117
+ test(False, line2, prefix, 1)
118
+ test(False, prefix, None, None, bell=True)
119
+
120
+ # Prefix 'a' tests skip line2, which starts with 'b'
121
+ def test_fetch_prev_prefix(self):
122
+ prefix = 'a'
123
+ self.text.insert('iomark', prefix)
124
+ self.fetch_test(True, line1, prefix, 0)
125
+ self.fetch_test(True, prefix, None, None, bell=True)
126
+
127
+ def test_fetch_next_prefix(self):
128
+ prefix = 'a'
129
+ self.text.insert('iomark', prefix)
130
+ self.fetch_test(False, line1, prefix, 0)
131
+ self.fetch_test(False, prefix, None, None, bell=True)
132
+
133
+ def test_fetch_prev_noncyclic(self):
134
+ prefix = ''
135
+ self.history.cyclic = False
136
+ test = self.fetch_test
137
+ test(True, line2, prefix, 1)
138
+ test(True, line1, prefix, 0)
139
+ test(True, line1, prefix, 0, bell=True)
140
+
141
+ def test_fetch_next_noncyclic(self):
142
+ prefix = ''
143
+ self.history.cyclic = False
144
+ test = self.fetch_test
145
+ test(False, prefix, None, None, bell=True)
146
+ test(True, line2, prefix, 1)
147
+ test(False, prefix, None, None, bell=True)
148
+ test(False, prefix, None, None, bell=True)
149
+
150
+ def test_fetch_cursor_move(self):
151
+ # Move cursor after fetch
152
+ self.history.fetch(reverse=True) # initialization
153
+ self.text.mark_set('insert', 'iomark')
154
+ self.fetch_test(True, line2, None, None, bell=True)
155
+
156
+ def test_fetch_edit(self):
157
+ # Edit after fetch
158
+ self.history.fetch(reverse=True) # initialization
159
+ self.text.delete('iomark', 'insert', )
160
+ self.text.insert('iomark', 'a =')
161
+ self.fetch_test(True, line1, 'a =', 0) # prefix is reset
162
+
163
+ def test_history_prev_next(self):
164
+ # Minimally test functions bound to events
165
+ self.history.history_prev('dummy event')
166
+ self.assertEqual(self.history.pointer, 1)
167
+ self.history.history_next('dummy event')
168
+ self.assertEqual(self.history.pointer, None)
169
+
170
+
171
+ if __name__ == '__main__':
172
+ unittest.main(verbosity=2, exit=2)
llava/lib/python3.10/idlelib/idle_test/test_macosx.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Test macosx, coverage 45% on Windows."
2
+
3
+ from idlelib import macosx
4
+ import unittest
5
+ from test.support import requires
6
+ import tkinter as tk
7
+ import unittest.mock as mock
8
+ from idlelib.filelist import FileList
9
+
10
+ mactypes = {'carbon', 'cocoa', 'xquartz'}
11
+ nontypes = {'other'}
12
+ alltypes = mactypes | nontypes
13
+
14
+
15
+ def setUpModule():
16
+ global orig_tktype
17
+ orig_tktype = macosx._tk_type
18
+
19
+
20
+ def tearDownModule():
21
+ macosx._tk_type = orig_tktype
22
+
23
+
24
+ class InitTktypeTest(unittest.TestCase):
25
+ "Test _init_tk_type."
26
+
27
+ @classmethod
28
+ def setUpClass(cls):
29
+ requires('gui')
30
+ cls.root = tk.Tk()
31
+ cls.root.withdraw()
32
+ cls.orig_platform = macosx.platform
33
+
34
+ @classmethod
35
+ def tearDownClass(cls):
36
+ cls.root.update_idletasks()
37
+ cls.root.destroy()
38
+ del cls.root
39
+ macosx.platform = cls.orig_platform
40
+
41
+ def test_init_sets_tktype(self):
42
+ "Test that _init_tk_type sets _tk_type according to platform."
43
+ for platform, types in ('darwin', alltypes), ('other', nontypes):
44
+ with self.subTest(platform=platform):
45
+ macosx.platform = platform
46
+ macosx._tk_type = None
47
+ macosx._init_tk_type()
48
+ self.assertIn(macosx._tk_type, types)
49
+
50
+
51
+ class IsTypeTkTest(unittest.TestCase):
52
+ "Test each of the four isTypeTk predecates."
53
+ isfuncs = ((macosx.isAquaTk, ('carbon', 'cocoa')),
54
+ (macosx.isCarbonTk, ('carbon')),
55
+ (macosx.isCocoaTk, ('cocoa')),
56
+ (macosx.isXQuartz, ('xquartz')),
57
+ )
58
+
59
+ @mock.patch('idlelib.macosx._init_tk_type')
60
+ def test_is_calls_init(self, mockinit):
61
+ "Test that each isTypeTk calls _init_tk_type when _tk_type is None."
62
+ macosx._tk_type = None
63
+ for func, whentrue in self.isfuncs:
64
+ with self.subTest(func=func):
65
+ func()
66
+ self.assertTrue(mockinit.called)
67
+ mockinit.reset_mock()
68
+
69
+ def test_isfuncs(self):
70
+ "Test that each isTypeTk return correct bool."
71
+ for func, whentrue in self.isfuncs:
72
+ for tktype in alltypes:
73
+ with self.subTest(func=func, whentrue=whentrue, tktype=tktype):
74
+ macosx._tk_type = tktype
75
+ (self.assertTrue if tktype in whentrue else self.assertFalse)\
76
+ (func())
77
+
78
+
79
+ class SetupTest(unittest.TestCase):
80
+ "Test setupApp."
81
+
82
+ @classmethod
83
+ def setUpClass(cls):
84
+ requires('gui')
85
+ cls.root = tk.Tk()
86
+ cls.root.withdraw()
87
+ def cmd(tkpath, func):
88
+ assert isinstance(tkpath, str)
89
+ assert isinstance(func, type(cmd))
90
+ cls.root.createcommand = cmd
91
+
92
+ @classmethod
93
+ def tearDownClass(cls):
94
+ cls.root.update_idletasks()
95
+ cls.root.destroy()
96
+ del cls.root
97
+
98
+ @mock.patch('idlelib.macosx.overrideRootMenu') #27312
99
+ def test_setupapp(self, overrideRootMenu):
100
+ "Call setupApp with each possible graphics type."
101
+ root = self.root
102
+ flist = FileList(root)
103
+ for tktype in alltypes:
104
+ with self.subTest(tktype=tktype):
105
+ macosx._tk_type = tktype
106
+ macosx.setupApp(root, flist)
107
+ if tktype in ('carbon', 'cocoa'):
108
+ self.assertTrue(overrideRootMenu.called)
109
+ overrideRootMenu.reset_mock()
110
+
111
+
112
+ if __name__ == '__main__':
113
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_mainmenu.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Test mainmenu, coverage 100%."
2
+ # Reported as 88%; mocking turtledemo absence would have no point.
3
+
4
+ from idlelib import mainmenu
5
+ import re
6
+ import unittest
7
+
8
+
9
+ class MainMenuTest(unittest.TestCase):
10
+
11
+ def test_menudefs(self):
12
+ actual = [item[0] for item in mainmenu.menudefs]
13
+ expect = ['file', 'edit', 'format', 'run', 'shell',
14
+ 'debug', 'options', 'window', 'help']
15
+ self.assertEqual(actual, expect)
16
+
17
+ def test_default_keydefs(self):
18
+ self.assertGreaterEqual(len(mainmenu.default_keydefs), 50)
19
+
20
+ def test_tcl_indexes(self):
21
+ # Test tcl patterns used to find menuitem to alter.
22
+ # On failure, change pattern here and in function(s).
23
+ # Patterns here have '.*' for re instead of '*' for tcl.
24
+ for menu, pattern in (
25
+ ('debug', '.*tack.*iewer'), # PyShell.debug_menu_postcommand
26
+ ('options', '.*ode.*ontext'), # EW.__init__, CodeContext.toggle...
27
+ ('options', '.*ine.*umbers'), # EW.__init__, EW.toggle...event.
28
+ ):
29
+ with self.subTest(menu=menu, pattern=pattern):
30
+ for menutup in mainmenu.menudefs:
31
+ if menutup[0] == menu:
32
+ break
33
+ else:
34
+ self.assertTrue(0, f"{menu} not in menudefs")
35
+ self.assertTrue(any(re.search(pattern, menuitem[0])
36
+ for menuitem in menutup[1]
37
+ if menuitem is not None), # Separator.
38
+ f"{pattern} not in {menu}")
39
+
40
+
41
+ if __name__ == '__main__':
42
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_multicall.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Test multicall, coverage 33%."
2
+
3
+ from idlelib import multicall
4
+ import unittest
5
+ from test.support import requires
6
+ from tkinter import Tk, Text
7
+
8
+
9
+ class MultiCallTest(unittest.TestCase):
10
+
11
+ @classmethod
12
+ def setUpClass(cls):
13
+ requires('gui')
14
+ cls.root = Tk()
15
+ cls.root.withdraw()
16
+ cls.mc = multicall.MultiCallCreator(Text)
17
+
18
+ @classmethod
19
+ def tearDownClass(cls):
20
+ del cls.mc
21
+ cls.root.update_idletasks()
22
+ ## for id in cls.root.tk.call('after', 'info'):
23
+ ## cls.root.after_cancel(id) # Need for EditorWindow.
24
+ cls.root.destroy()
25
+ del cls.root
26
+
27
+ def test_creator(self):
28
+ mc = self.mc
29
+ self.assertIs(multicall._multicall_dict[Text], mc)
30
+ self.assertTrue(issubclass(mc, Text))
31
+ mc2 = multicall.MultiCallCreator(Text)
32
+ self.assertIs(mc, mc2)
33
+
34
+ def test_init(self):
35
+ mctext = self.mc(self.root)
36
+ self.assertIsInstance(mctext._MultiCall__binders, list)
37
+
38
+ def test_yview(self):
39
+ # Added for tree.wheel_event
40
+ # (it depends on yview to not be overridden)
41
+ mc = self.mc
42
+ self.assertIs(mc.yview, Text.yview)
43
+ mctext = self.mc(self.root)
44
+ self.assertIs(mctext.yview.__func__, Text.yview)
45
+
46
+
47
+ if __name__ == '__main__':
48
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_outwin.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Test outwin, coverage 76%."
2
+
3
+ from idlelib import outwin
4
+ import unittest
5
+ from test.support import requires
6
+ from tkinter import Tk, Text
7
+ from idlelib.idle_test.mock_tk import Mbox_func
8
+ from idlelib.idle_test.mock_idle import Func
9
+ from unittest import mock
10
+
11
+
12
+ class OutputWindowTest(unittest.TestCase):
13
+
14
+ @classmethod
15
+ def setUpClass(cls):
16
+ requires('gui')
17
+ root = cls.root = Tk()
18
+ root.withdraw()
19
+ w = cls.window = outwin.OutputWindow(None, None, None, root)
20
+ cls.text = w.text = Text(root)
21
+
22
+ @classmethod
23
+ def tearDownClass(cls):
24
+ cls.window.close()
25
+ del cls.text, cls.window
26
+ cls.root.destroy()
27
+ del cls.root
28
+
29
+ def setUp(self):
30
+ self.text.delete('1.0', 'end')
31
+
32
+ def test_ispythonsource(self):
33
+ # OutputWindow overrides ispythonsource to always return False.
34
+ w = self.window
35
+ self.assertFalse(w.ispythonsource('test.txt'))
36
+ self.assertFalse(w.ispythonsource(__file__))
37
+
38
+ def test_window_title(self):
39
+ self.assertEqual(self.window.top.title(), 'Output')
40
+
41
+ def test_maybesave(self):
42
+ w = self.window
43
+ eq = self.assertEqual
44
+ w.get_saved = Func()
45
+
46
+ w.get_saved.result = False
47
+ eq(w.maybesave(), 'no')
48
+ eq(w.get_saved.called, 1)
49
+
50
+ w.get_saved.result = True
51
+ eq(w.maybesave(), 'yes')
52
+ eq(w.get_saved.called, 2)
53
+ del w.get_saved
54
+
55
+ def test_write(self):
56
+ eq = self.assertEqual
57
+ delete = self.text.delete
58
+ get = self.text.get
59
+ write = self.window.write
60
+
61
+ # No new line - insert stays on same line.
62
+ delete('1.0', 'end')
63
+ test_text = 'test text'
64
+ eq(write(test_text), len(test_text))
65
+ eq(get('1.0', '1.end'), 'test text')
66
+ eq(get('insert linestart', 'insert lineend'), 'test text')
67
+
68
+ # New line - insert moves to next line.
69
+ delete('1.0', 'end')
70
+ test_text = 'test text\n'
71
+ eq(write(test_text), len(test_text))
72
+ eq(get('1.0', '1.end'), 'test text')
73
+ eq(get('insert linestart', 'insert lineend'), '')
74
+
75
+ # Text after new line is tagged for second line of Text widget.
76
+ delete('1.0', 'end')
77
+ test_text = 'test text\nLine 2'
78
+ eq(write(test_text), len(test_text))
79
+ eq(get('1.0', '1.end'), 'test text')
80
+ eq(get('2.0', '2.end'), 'Line 2')
81
+ eq(get('insert linestart', 'insert lineend'), 'Line 2')
82
+
83
+ # Test tags.
84
+ delete('1.0', 'end')
85
+ test_text = 'test text\n'
86
+ test_text2 = 'Line 2\n'
87
+ eq(write(test_text, tags='mytag'), len(test_text))
88
+ eq(write(test_text2, tags='secondtag'), len(test_text2))
89
+ eq(get('mytag.first', 'mytag.last'), test_text)
90
+ eq(get('secondtag.first', 'secondtag.last'), test_text2)
91
+ eq(get('1.0', '1.end'), test_text.rstrip('\n'))
92
+ eq(get('2.0', '2.end'), test_text2.rstrip('\n'))
93
+
94
+ def test_writelines(self):
95
+ eq = self.assertEqual
96
+ get = self.text.get
97
+ writelines = self.window.writelines
98
+
99
+ writelines(('Line 1\n', 'Line 2\n', 'Line 3\n'))
100
+ eq(get('1.0', '1.end'), 'Line 1')
101
+ eq(get('2.0', '2.end'), 'Line 2')
102
+ eq(get('3.0', '3.end'), 'Line 3')
103
+ eq(get('insert linestart', 'insert lineend'), '')
104
+
105
+ def test_goto_file_line(self):
106
+ eq = self.assertEqual
107
+ w = self.window
108
+ text = self.text
109
+
110
+ w.flist = mock.Mock()
111
+ gfl = w.flist.gotofileline = Func()
112
+ showerror = w.showerror = Mbox_func()
113
+
114
+ # No file/line number.
115
+ w.write('Not a file line')
116
+ self.assertIsNone(w.goto_file_line())
117
+ eq(gfl.called, 0)
118
+ eq(showerror.title, 'No special line')
119
+
120
+ # Current file/line number.
121
+ w.write(f'{str(__file__)}: 42: spam\n')
122
+ w.write(f'{str(__file__)}: 21: spam')
123
+ self.assertIsNone(w.goto_file_line())
124
+ eq(gfl.args, (str(__file__), 21))
125
+
126
+ # Previous line has file/line number.
127
+ text.delete('1.0', 'end')
128
+ w.write(f'{str(__file__)}: 42: spam\n')
129
+ w.write('Not a file line')
130
+ self.assertIsNone(w.goto_file_line())
131
+ eq(gfl.args, (str(__file__), 42))
132
+
133
+ del w.flist.gotofileline, w.showerror
134
+
135
+
136
+ class ModuleFunctionTest(unittest.TestCase):
137
+
138
+ @classmethod
139
+ def setUp(cls):
140
+ outwin.file_line_progs = None
141
+
142
+ def test_compile_progs(self):
143
+ outwin.compile_progs()
144
+ for pat, regex in zip(outwin.file_line_pats, outwin.file_line_progs):
145
+ self.assertEqual(regex.pattern, pat)
146
+
147
+ @mock.patch('builtins.open')
148
+ def test_file_line_helper(self, mock_open):
149
+ flh = outwin.file_line_helper
150
+ test_lines = (
151
+ (r'foo file "testfile1", line 42, bar', ('testfile1', 42)),
152
+ (r'foo testfile2(21) bar', ('testfile2', 21)),
153
+ (r' testfile3 : 42: foo bar\n', (' testfile3 ', 42)),
154
+ (r'foo testfile4.py :1: ', ('foo testfile4.py ', 1)),
155
+ ('testfile5: \u19D4\u19D2: ', ('testfile5', 42)),
156
+ (r'testfile6: 42', None), # only one `:`
157
+ (r'testfile7 42 text', None) # no separators
158
+ )
159
+ for line, expected_output in test_lines:
160
+ self.assertEqual(flh(line), expected_output)
161
+ if expected_output:
162
+ mock_open.assert_called_with(expected_output[0], 'r')
163
+
164
+
165
+ if __name__ == '__main__':
166
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_parenmatch.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test parenmatch, coverage 91%.
2
+
3
+ This must currently be a gui test because ParenMatch methods use
4
+ several text methods not defined on idlelib.idle_test.mock_tk.Text.
5
+ """
6
+ from idlelib.parenmatch import ParenMatch
7
+ from test.support import requires
8
+ requires('gui')
9
+
10
+ import unittest
11
+ from unittest.mock import Mock
12
+ from tkinter import Tk, Text
13
+
14
+
15
+ class DummyEditwin:
16
+ def __init__(self, text):
17
+ self.text = text
18
+ self.indentwidth = 8
19
+ self.tabwidth = 8
20
+ self.prompt_last_line = '>>>' # Currently not used by parenmatch.
21
+
22
+
23
+ class ParenMatchTest(unittest.TestCase):
24
+
25
+ @classmethod
26
+ def setUpClass(cls):
27
+ cls.root = Tk()
28
+ cls.root.withdraw()
29
+ cls.text = Text(cls.root)
30
+ cls.editwin = DummyEditwin(cls.text)
31
+ cls.editwin.text_frame = Mock()
32
+
33
+ @classmethod
34
+ def tearDownClass(cls):
35
+ del cls.text, cls.editwin
36
+ cls.root.update_idletasks()
37
+ cls.root.destroy()
38
+ del cls.root
39
+
40
+ def tearDown(self):
41
+ self.text.delete('1.0', 'end')
42
+
43
+ def get_parenmatch(self):
44
+ pm = ParenMatch(self.editwin)
45
+ pm.bell = lambda: None
46
+ return pm
47
+
48
+ def test_paren_styles(self):
49
+ """
50
+ Test ParenMatch with each style.
51
+ """
52
+ text = self.text
53
+ pm = self.get_parenmatch()
54
+ for style, range1, range2 in (
55
+ ('opener', ('1.10', '1.11'), ('1.10', '1.11')),
56
+ ('default',('1.10', '1.11'),('1.10', '1.11')),
57
+ ('parens', ('1.14', '1.15'), ('1.15', '1.16')),
58
+ ('expression', ('1.10', '1.15'), ('1.10', '1.16'))):
59
+ with self.subTest(style=style):
60
+ text.delete('1.0', 'end')
61
+ pm.STYLE = style
62
+ text.insert('insert', 'def foobar(a, b')
63
+
64
+ pm.flash_paren_event('event')
65
+ self.assertIn('<<parenmatch-check-restore>>', text.event_info())
66
+ if style == 'parens':
67
+ self.assertTupleEqual(text.tag_nextrange('paren', '1.0'),
68
+ ('1.10', '1.11'))
69
+ self.assertTupleEqual(
70
+ text.tag_prevrange('paren', 'end'), range1)
71
+
72
+ text.insert('insert', ')')
73
+ pm.restore_event()
74
+ self.assertNotIn('<<parenmatch-check-restore>>',
75
+ text.event_info())
76
+ self.assertEqual(text.tag_prevrange('paren', 'end'), ())
77
+
78
+ pm.paren_closed_event('event')
79
+ self.assertTupleEqual(
80
+ text.tag_prevrange('paren', 'end'), range2)
81
+
82
+ def test_paren_corner(self):
83
+ """
84
+ Test corner cases in flash_paren_event and paren_closed_event.
85
+
86
+ Force execution of conditional expressions and alternate paths.
87
+ """
88
+ text = self.text
89
+ pm = self.get_parenmatch()
90
+
91
+ text.insert('insert', '# Comment.)')
92
+ pm.paren_closed_event('event')
93
+
94
+ text.insert('insert', '\ndef')
95
+ pm.flash_paren_event('event')
96
+ pm.paren_closed_event('event')
97
+
98
+ text.insert('insert', ' a, *arg)')
99
+ pm.paren_closed_event('event')
100
+
101
+ def test_handle_restore_timer(self):
102
+ pm = self.get_parenmatch()
103
+ pm.restore_event = Mock()
104
+ pm.handle_restore_timer(0)
105
+ self.assertTrue(pm.restore_event.called)
106
+ pm.restore_event.reset_mock()
107
+ pm.handle_restore_timer(1)
108
+ self.assertFalse(pm.restore_event.called)
109
+
110
+
111
+ if __name__ == '__main__':
112
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_pathbrowser.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Test pathbrowser, coverage 95%."
2
+
3
+ from idlelib import pathbrowser
4
+ import unittest
5
+ from test.support import requires
6
+ from tkinter import Tk
7
+
8
+ import os.path
9
+ import pyclbr # for _modules
10
+ import sys # for sys.path
11
+
12
+ from idlelib.idle_test.mock_idle import Func
13
+ import idlelib # for __file__
14
+ from idlelib import browser
15
+ from idlelib.tree import TreeNode
16
+
17
+
18
+ class PathBrowserTest(unittest.TestCase):
19
+
20
+ @classmethod
21
+ def setUpClass(cls):
22
+ requires('gui')
23
+ cls.root = Tk()
24
+ cls.root.withdraw()
25
+ cls.pb = pathbrowser.PathBrowser(cls.root, _utest=True)
26
+
27
+ @classmethod
28
+ def tearDownClass(cls):
29
+ cls.pb.close()
30
+ cls.root.update_idletasks()
31
+ cls.root.destroy()
32
+ del cls.root, cls.pb
33
+
34
+ def test_init(self):
35
+ pb = self.pb
36
+ eq = self.assertEqual
37
+ eq(pb.master, self.root)
38
+ eq(pyclbr._modules, {})
39
+ self.assertIsInstance(pb.node, TreeNode)
40
+ self.assertIsNotNone(browser.file_open)
41
+
42
+ def test_settitle(self):
43
+ pb = self.pb
44
+ self.assertEqual(pb.top.title(), 'Path Browser')
45
+ self.assertEqual(pb.top.iconname(), 'Path Browser')
46
+
47
+ def test_rootnode(self):
48
+ pb = self.pb
49
+ rn = pb.rootnode()
50
+ self.assertIsInstance(rn, pathbrowser.PathBrowserTreeItem)
51
+
52
+ def test_close(self):
53
+ pb = self.pb
54
+ pb.top.destroy = Func()
55
+ pb.node.destroy = Func()
56
+ pb.close()
57
+ self.assertTrue(pb.top.destroy.called)
58
+ self.assertTrue(pb.node.destroy.called)
59
+ del pb.top.destroy, pb.node.destroy
60
+
61
+
62
+ class DirBrowserTreeItemTest(unittest.TestCase):
63
+
64
+ def test_DirBrowserTreeItem(self):
65
+ # Issue16226 - make sure that getting a sublist works
66
+ d = pathbrowser.DirBrowserTreeItem('')
67
+ d.GetSubList()
68
+ self.assertEqual('', d.GetText())
69
+
70
+ dir = os.path.split(os.path.abspath(idlelib.__file__))[0]
71
+ self.assertEqual(d.ispackagedir(dir), True)
72
+ self.assertEqual(d.ispackagedir(dir + '/Icons'), False)
73
+
74
+
75
+ class PathBrowserTreeItemTest(unittest.TestCase):
76
+
77
+ def test_PathBrowserTreeItem(self):
78
+ p = pathbrowser.PathBrowserTreeItem()
79
+ self.assertEqual(p.GetText(), 'sys.path')
80
+ sub = p.GetSubList()
81
+ self.assertEqual(len(sub), len(sys.path))
82
+ self.assertEqual(type(sub[0]), pathbrowser.DirBrowserTreeItem)
83
+
84
+
85
+ if __name__ == '__main__':
86
+ unittest.main(verbosity=2, exit=False)
llava/lib/python3.10/idlelib/idle_test/test_percolator.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Test percolator, coverage 100%."
2
+
3
+ from idlelib.percolator import Percolator, Delegator
4
+ import unittest
5
+ from test.support import requires
6
+ requires('gui')
7
+ from tkinter import Text, Tk, END
8
+
9
+
10
+ class MyFilter(Delegator):
11
+ def __init__(self):
12
+ Delegator.__init__(self, None)
13
+
14
+ def insert(self, *args):
15
+ self.insert_called_with = args
16
+ self.delegate.insert(*args)
17
+
18
+ def delete(self, *args):
19
+ self.delete_called_with = args
20
+ self.delegate.delete(*args)
21
+
22
+ def uppercase_insert(self, index, chars, tags=None):
23
+ chars = chars.upper()
24
+ self.delegate.insert(index, chars)
25
+
26
+ def lowercase_insert(self, index, chars, tags=None):
27
+ chars = chars.lower()
28
+ self.delegate.insert(index, chars)
29
+
30
+ def dont_insert(self, index, chars, tags=None):
31
+ pass
32
+
33
+
34
+ class PercolatorTest(unittest.TestCase):
35
+
36
+ @classmethod
37
+ def setUpClass(cls):
38
+ cls.root = Tk()
39
+ cls.text = Text(cls.root)
40
+
41
+ @classmethod
42
+ def tearDownClass(cls):
43
+ del cls.text
44
+ cls.root.destroy()
45
+ del cls.root
46
+
47
+ def setUp(self):
48
+ self.percolator = Percolator(self.text)
49
+ self.filter_one = MyFilter()
50
+ self.filter_two = MyFilter()
51
+ self.percolator.insertfilter(self.filter_one)
52
+ self.percolator.insertfilter(self.filter_two)
53
+
54
+ def tearDown(self):
55
+ self.percolator.close()
56
+ self.text.delete('1.0', END)
57
+
58
+ def test_insertfilter(self):
59
+ self.assertIsNotNone(self.filter_one.delegate)
60
+ self.assertEqual(self.percolator.top, self.filter_two)
61
+ self.assertEqual(self.filter_two.delegate, self.filter_one)
62
+ self.assertEqual(self.filter_one.delegate, self.percolator.bottom)
63
+
64
+ def test_removefilter(self):
65
+ filter_three = MyFilter()
66
+ self.percolator.removefilter(self.filter_two)
67
+ self.assertEqual(self.percolator.top, self.filter_one)
68
+ self.assertIsNone(self.filter_two.delegate)
69
+
70
+ filter_three = MyFilter()
71
+ self.percolator.insertfilter(self.filter_two)
72
+ self.percolator.insertfilter(filter_three)
73
+ self.percolator.removefilter(self.filter_one)
74
+ self.assertEqual(self.percolator.top, filter_three)
75
+ self.assertEqual(filter_three.delegate, self.filter_two)
76
+ self.assertEqual(self.filter_two.delegate, self.percolator.bottom)
77
+ self.assertIsNone(self.filter_one.delegate)
78
+
79
+ def test_insert(self):
80
+ self.text.insert('insert', 'foo')
81
+ self.assertEqual(self.text.get('1.0', END), 'foo\n')
82
+ self.assertTupleEqual(self.filter_one.insert_called_with,
83
+ ('insert', 'foo', None))
84
+
85
+ def test_modify_insert(self):
86
+ self.filter_one.insert = self.filter_one.uppercase_insert
87
+ self.text.insert('insert', 'bAr')
88
+ self.assertEqual(self.text.get('1.0', END), 'BAR\n')
89
+
90
+ def test_modify_chain_insert(self):
91
+ filter_three = MyFilter()
92
+ self.percolator.insertfilter(filter_three)
93
+ self.filter_two.insert = self.filter_two.uppercase_insert
94
+ self.filter_one.insert = self.filter_one.lowercase_insert
95
+ self.text.insert('insert', 'BaR')
96
+ self.assertEqual(self.text.get('1.0', END), 'bar\n')
97
+
98
+ def test_dont_insert(self):
99
+ self.filter_one.insert = self.filter_one.dont_insert
100
+ self.text.insert('insert', 'foo bar')
101
+ self.assertEqual(self.text.get('1.0', END), '\n')
102
+ self.filter_one.insert = self.filter_one.dont_insert
103
+ self.text.insert('insert', 'foo bar')
104
+ self.assertEqual(self.text.get('1.0', END), '\n')
105
+
106
+ def test_without_filter(self):
107
+ self.text.insert('insert', 'hello')
108
+ self.assertEqual(self.text.get('1.0', 'end'), 'hello\n')
109
+
110
+ def test_delete(self):
111
+ self.text.insert('insert', 'foo')
112
+ self.text.delete('1.0', '1.2')
113
+ self.assertEqual(self.text.get('1.0', END), 'o\n')
114
+ self.assertTupleEqual(self.filter_one.delete_called_with,
115
+ ('1.0', '1.2'))
116
+
117
+ if __name__ == '__main__':
118
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_pyparse.py ADDED
@@ -0,0 +1,483 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Test pyparse, coverage 96%."
2
+
3
+ from idlelib import pyparse
4
+ import unittest
5
+ from collections import namedtuple
6
+
7
+
8
+ class ParseMapTest(unittest.TestCase):
9
+
10
+ def test_parsemap(self):
11
+ keepwhite = {ord(c): ord(c) for c in ' \t\n\r'}
12
+ mapping = pyparse.ParseMap(keepwhite)
13
+ self.assertEqual(mapping[ord('\t')], ord('\t'))
14
+ self.assertEqual(mapping[ord('a')], ord('x'))
15
+ self.assertEqual(mapping[1000], ord('x'))
16
+
17
+ def test_trans(self):
18
+ # trans is the production instance of ParseMap, used in _study1
19
+ parser = pyparse.Parser(4, 4)
20
+ self.assertEqual('\t a([{b}])b"c\'d\n'.translate(pyparse.trans),
21
+ 'xxx(((x)))x"x\'x\n')
22
+
23
+
24
+ class PyParseTest(unittest.TestCase):
25
+
26
+ @classmethod
27
+ def setUpClass(cls):
28
+ cls.parser = pyparse.Parser(indentwidth=4, tabwidth=4)
29
+
30
+ @classmethod
31
+ def tearDownClass(cls):
32
+ del cls.parser
33
+
34
+ def test_init(self):
35
+ self.assertEqual(self.parser.indentwidth, 4)
36
+ self.assertEqual(self.parser.tabwidth, 4)
37
+
38
+ def test_set_code(self):
39
+ eq = self.assertEqual
40
+ p = self.parser
41
+ setcode = p.set_code
42
+
43
+ # Not empty and doesn't end with newline.
44
+ with self.assertRaises(AssertionError):
45
+ setcode('a')
46
+
47
+ tests = ('',
48
+ 'a\n')
49
+
50
+ for string in tests:
51
+ with self.subTest(string=string):
52
+ setcode(string)
53
+ eq(p.code, string)
54
+ eq(p.study_level, 0)
55
+
56
+ def test_find_good_parse_start(self):
57
+ eq = self.assertEqual
58
+ p = self.parser
59
+ setcode = p.set_code
60
+ start = p.find_good_parse_start
61
+ def char_in_string_false(index): return False
62
+
63
+ # First line starts with 'def' and ends with ':', then 0 is the pos.
64
+ setcode('def spam():\n')
65
+ eq(start(char_in_string_false), 0)
66
+
67
+ # First line begins with a keyword in the list and ends
68
+ # with an open brace, then 0 is the pos. This is how
69
+ # hyperparser calls this function as the newline is not added
70
+ # in the editor, but rather on the call to setcode.
71
+ setcode('class spam( ' + ' \n')
72
+ eq(start(char_in_string_false), 0)
73
+
74
+ # Split def across lines.
75
+ setcode('"""This is a module docstring"""\n'
76
+ 'class C:\n'
77
+ ' def __init__(self, a,\n'
78
+ ' b=True):\n'
79
+ ' pass\n'
80
+ )
81
+ pos0, pos = 33, 42 # Start of 'class...', ' def' lines.
82
+
83
+ # Passing no value or non-callable should fail (issue 32989).
84
+ with self.assertRaises(TypeError):
85
+ start()
86
+ with self.assertRaises(TypeError):
87
+ start(False)
88
+
89
+ # Make text look like a string. This returns pos as the start
90
+ # position, but it's set to None.
91
+ self.assertIsNone(start(is_char_in_string=lambda index: True))
92
+
93
+ # Make all text look like it's not in a string. This means that it
94
+ # found a good start position.
95
+ eq(start(char_in_string_false), pos)
96
+
97
+ # If the beginning of the def line is not in a string, then it
98
+ # returns that as the index.
99
+ eq(start(is_char_in_string=lambda index: index > pos), pos)
100
+ # If the beginning of the def line is in a string, then it
101
+ # looks for a previous index.
102
+ eq(start(is_char_in_string=lambda index: index >= pos), pos0)
103
+ # If everything before the 'def' is in a string, then returns None.
104
+ # The non-continuation def line returns 44 (see below).
105
+ eq(start(is_char_in_string=lambda index: index < pos), None)
106
+
107
+ # Code without extra line break in def line - mostly returns the same
108
+ # values.
109
+ setcode('"""This is a module docstring"""\n'
110
+ 'class C:\n'
111
+ ' def __init__(self, a, b=True):\n'
112
+ ' pass\n'
113
+ ) # Does not affect class, def positions.
114
+ eq(start(char_in_string_false), pos)
115
+ eq(start(is_char_in_string=lambda index: index > pos), pos)
116
+ eq(start(is_char_in_string=lambda index: index >= pos), pos0)
117
+ # When the def line isn't split, this returns which doesn't match the
118
+ # split line test.
119
+ eq(start(is_char_in_string=lambda index: index < pos), pos)
120
+
121
+ def test_set_lo(self):
122
+ code = (
123
+ '"""This is a module docstring"""\n'
124
+ 'class C:\n'
125
+ ' def __init__(self, a,\n'
126
+ ' b=True):\n'
127
+ ' pass\n'
128
+ )
129
+ pos = 42
130
+ p = self.parser
131
+ p.set_code(code)
132
+
133
+ # Previous character is not a newline.
134
+ with self.assertRaises(AssertionError):
135
+ p.set_lo(5)
136
+
137
+ # A value of 0 doesn't change self.code.
138
+ p.set_lo(0)
139
+ self.assertEqual(p.code, code)
140
+
141
+ # An index that is preceded by a newline.
142
+ p.set_lo(pos)
143
+ self.assertEqual(p.code, code[pos:])
144
+
145
+ def test_study1(self):
146
+ eq = self.assertEqual
147
+ p = self.parser
148
+ setcode = p.set_code
149
+ study = p._study1
150
+
151
+ (NONE, BACKSLASH, FIRST, NEXT, BRACKET) = range(5)
152
+ TestInfo = namedtuple('TestInfo', ['string', 'goodlines',
153
+ 'continuation'])
154
+ tests = (
155
+ TestInfo('', [0], NONE),
156
+ # Docstrings.
157
+ TestInfo('"""This is a complete docstring."""\n', [0, 1], NONE),
158
+ TestInfo("'''This is a complete docstring.'''\n", [0, 1], NONE),
159
+ TestInfo('"""This is a continued docstring.\n', [0, 1], FIRST),
160
+ TestInfo("'''This is a continued docstring.\n", [0, 1], FIRST),
161
+ TestInfo('"""Closing quote does not match."\n', [0, 1], FIRST),
162
+ TestInfo('"""Bracket in docstring [\n', [0, 1], FIRST),
163
+ TestInfo("'''Incomplete two line docstring.\n\n", [0, 2], NEXT),
164
+ # Single-quoted strings.
165
+ TestInfo('"This is a complete string."\n', [0, 1], NONE),
166
+ TestInfo('"This is an incomplete string.\n', [0, 1], NONE),
167
+ TestInfo("'This is more incomplete.\n\n", [0, 1, 2], NONE),
168
+ # Comment (backslash does not continue comments).
169
+ TestInfo('# Comment\\\n', [0, 1], NONE),
170
+ # Brackets.
171
+ TestInfo('("""Complete string in bracket"""\n', [0, 1], BRACKET),
172
+ TestInfo('("""Open string in bracket\n', [0, 1], FIRST),
173
+ TestInfo('a = (1 + 2) - 5 *\\\n', [0, 1], BACKSLASH), # No bracket.
174
+ TestInfo('\n def function1(self, a,\n b):\n',
175
+ [0, 1, 3], NONE),
176
+ TestInfo('\n def function1(self, a,\\\n', [0, 1, 2], BRACKET),
177
+ TestInfo('\n def function1(self, a,\n', [0, 1, 2], BRACKET),
178
+ TestInfo('())\n', [0, 1], NONE), # Extra closer.
179
+ TestInfo(')(\n', [0, 1], BRACKET), # Extra closer.
180
+ # For the mismatched example, it doesn't look like continuation.
181
+ TestInfo('{)(]\n', [0, 1], NONE), # Mismatched.
182
+ )
183
+
184
+ for test in tests:
185
+ with self.subTest(string=test.string):
186
+ setcode(test.string) # resets study_level
187
+ study()
188
+ eq(p.study_level, 1)
189
+ eq(p.goodlines, test.goodlines)
190
+ eq(p.continuation, test.continuation)
191
+
192
+ # Called again, just returns without reprocessing.
193
+ self.assertIsNone(study())
194
+
195
+ def test_get_continuation_type(self):
196
+ eq = self.assertEqual
197
+ p = self.parser
198
+ setcode = p.set_code
199
+ gettype = p.get_continuation_type
200
+
201
+ (NONE, BACKSLASH, FIRST, NEXT, BRACKET) = range(5)
202
+ TestInfo = namedtuple('TestInfo', ['string', 'continuation'])
203
+ tests = (
204
+ TestInfo('', NONE),
205
+ TestInfo('"""This is a continuation docstring.\n', FIRST),
206
+ TestInfo("'''This is a multiline-continued docstring.\n\n", NEXT),
207
+ TestInfo('a = (1 + 2) - 5 *\\\n', BACKSLASH),
208
+ TestInfo('\n def function1(self, a,\\\n', BRACKET)
209
+ )
210
+
211
+ for test in tests:
212
+ with self.subTest(string=test.string):
213
+ setcode(test.string)
214
+ eq(gettype(), test.continuation)
215
+
216
+ def test_study2(self):
217
+ eq = self.assertEqual
218
+ p = self.parser
219
+ setcode = p.set_code
220
+ study = p._study2
221
+
222
+ TestInfo = namedtuple('TestInfo', ['string', 'start', 'end', 'lastch',
223
+ 'openbracket', 'bracketing'])
224
+ tests = (
225
+ TestInfo('', 0, 0, '', None, ((0, 0),)),
226
+ TestInfo("'''This is a multiline continuation docstring.\n\n",
227
+ 0, 48, "'", None, ((0, 0), (0, 1), (48, 0))),
228
+ TestInfo(' # Comment\\\n',
229
+ 0, 12, '', None, ((0, 0), (1, 1), (12, 0))),
230
+ # A comment without a space is a special case
231
+ TestInfo(' #Comment\\\n',
232
+ 0, 0, '', None, ((0, 0),)),
233
+ # Backslash continuation.
234
+ TestInfo('a = (1 + 2) - 5 *\\\n',
235
+ 0, 19, '*', None, ((0, 0), (4, 1), (11, 0))),
236
+ # Bracket continuation with close.
237
+ TestInfo('\n def function1(self, a,\n b):\n',
238
+ 1, 48, ':', None, ((1, 0), (17, 1), (46, 0))),
239
+ # Bracket continuation with unneeded backslash.
240
+ TestInfo('\n def function1(self, a,\\\n',
241
+ 1, 28, ',', 17, ((1, 0), (17, 1))),
242
+ # Bracket continuation.
243
+ TestInfo('\n def function1(self, a,\n',
244
+ 1, 27, ',', 17, ((1, 0), (17, 1))),
245
+ # Bracket continuation with comment at end of line with text.
246
+ TestInfo('\n def function1(self, a, # End of line comment.\n',
247
+ 1, 51, ',', 17, ((1, 0), (17, 1), (28, 2), (51, 1))),
248
+ # Multi-line statement with comment line in between code lines.
249
+ TestInfo(' a = ["first item",\n # Comment line\n "next item",\n',
250
+ 0, 55, ',', 6, ((0, 0), (6, 1), (7, 2), (19, 1),
251
+ (23, 2), (38, 1), (42, 2), (53, 1))),
252
+ TestInfo('())\n',
253
+ 0, 4, ')', None, ((0, 0), (0, 1), (2, 0), (3, 0))),
254
+ TestInfo(')(\n', 0, 3, '(', 1, ((0, 0), (1, 0), (1, 1))),
255
+ # Wrong closers still decrement stack level.
256
+ TestInfo('{)(]\n',
257
+ 0, 5, ']', None, ((0, 0), (0, 1), (2, 0), (2, 1), (4, 0))),
258
+ # Character after backslash.
259
+ TestInfo(':\\a\n', 0, 4, '\\a', None, ((0, 0),)),
260
+ TestInfo('\n', 0, 0, '', None, ((0, 0),)),
261
+ )
262
+
263
+ for test in tests:
264
+ with self.subTest(string=test.string):
265
+ setcode(test.string)
266
+ study()
267
+ eq(p.study_level, 2)
268
+ eq(p.stmt_start, test.start)
269
+ eq(p.stmt_end, test.end)
270
+ eq(p.lastch, test.lastch)
271
+ eq(p.lastopenbracketpos, test.openbracket)
272
+ eq(p.stmt_bracketing, test.bracketing)
273
+
274
+ # Called again, just returns without reprocessing.
275
+ self.assertIsNone(study())
276
+
277
+ def test_get_num_lines_in_stmt(self):
278
+ eq = self.assertEqual
279
+ p = self.parser
280
+ setcode = p.set_code
281
+ getlines = p.get_num_lines_in_stmt
282
+
283
+ TestInfo = namedtuple('TestInfo', ['string', 'lines'])
284
+ tests = (
285
+ TestInfo('[x for x in a]\n', 1), # Closed on one line.
286
+ TestInfo('[x\nfor x in a\n', 2), # Not closed.
287
+ TestInfo('[x\\\nfor x in a\\\n', 2), # "", unneeded backslashes.
288
+ TestInfo('[x\nfor x in a\n]\n', 3), # Closed on multi-line.
289
+ TestInfo('\n"""Docstring comment L1"""\nL2\nL3\nL4\n', 1),
290
+ TestInfo('\n"""Docstring comment L1\nL2"""\nL3\nL4\n', 1),
291
+ TestInfo('\n"""Docstring comment L1\\\nL2\\\nL3\\\nL4\\\n', 4),
292
+ TestInfo('\n\n"""Docstring comment L1\\\nL2\\\nL3\\\nL4\\\n"""\n', 5)
293
+ )
294
+
295
+ # Blank string doesn't have enough elements in goodlines.
296
+ setcode('')
297
+ with self.assertRaises(IndexError):
298
+ getlines()
299
+
300
+ for test in tests:
301
+ with self.subTest(string=test.string):
302
+ setcode(test.string)
303
+ eq(getlines(), test.lines)
304
+
305
+ def test_compute_bracket_indent(self):
306
+ eq = self.assertEqual
307
+ p = self.parser
308
+ setcode = p.set_code
309
+ indent = p.compute_bracket_indent
310
+
311
+ TestInfo = namedtuple('TestInfo', ['string', 'spaces'])
312
+ tests = (
313
+ TestInfo('def function1(self, a,\n', 14),
314
+ # Characters after bracket.
315
+ TestInfo('\n def function1(self, a,\n', 18),
316
+ TestInfo('\n\tdef function1(self, a,\n', 18),
317
+ # No characters after bracket.
318
+ TestInfo('\n def function1(\n', 8),
319
+ TestInfo('\n\tdef function1(\n', 8),
320
+ TestInfo('\n def function1( \n', 8), # Ignore extra spaces.
321
+ TestInfo('[\n"first item",\n # Comment line\n "next item",\n', 0),
322
+ TestInfo('[\n "first item",\n # Comment line\n "next item",\n', 2),
323
+ TestInfo('["first item",\n # Comment line\n "next item",\n', 1),
324
+ TestInfo('(\n', 4),
325
+ TestInfo('(a\n', 1),
326
+ )
327
+
328
+ # Must be C_BRACKET continuation type.
329
+ setcode('def function1(self, a, b):\n')
330
+ with self.assertRaises(AssertionError):
331
+ indent()
332
+
333
+ for test in tests:
334
+ setcode(test.string)
335
+ eq(indent(), test.spaces)
336
+
337
+ def test_compute_backslash_indent(self):
338
+ eq = self.assertEqual
339
+ p = self.parser
340
+ setcode = p.set_code
341
+ indent = p.compute_backslash_indent
342
+
343
+ # Must be C_BACKSLASH continuation type.
344
+ errors = (('def function1(self, a, b\\\n'), # Bracket.
345
+ (' """ (\\\n'), # Docstring.
346
+ ('a = #\\\n'), # Inline comment.
347
+ )
348
+ for string in errors:
349
+ with self.subTest(string=string):
350
+ setcode(string)
351
+ with self.assertRaises(AssertionError):
352
+ indent()
353
+
354
+ TestInfo = namedtuple('TestInfo', ('string', 'spaces'))
355
+ tests = (TestInfo('a = (1 + 2) - 5 *\\\n', 4),
356
+ TestInfo('a = 1 + 2 - 5 *\\\n', 4),
357
+ TestInfo(' a = 1 + 2 - 5 *\\\n', 8),
358
+ TestInfo(' a = "spam"\\\n', 6),
359
+ TestInfo(' a = \\\n"a"\\\n', 4),
360
+ TestInfo(' a = #\\\n"a"\\\n', 5),
361
+ TestInfo('a == \\\n', 2),
362
+ TestInfo('a != \\\n', 2),
363
+ # Difference between containing = and those not.
364
+ TestInfo('\\\n', 2),
365
+ TestInfo(' \\\n', 6),
366
+ TestInfo('\t\\\n', 6),
367
+ TestInfo('a\\\n', 3),
368
+ TestInfo('{}\\\n', 4),
369
+ TestInfo('(1 + 2) - 5 *\\\n', 3),
370
+ )
371
+ for test in tests:
372
+ with self.subTest(string=test.string):
373
+ setcode(test.string)
374
+ eq(indent(), test.spaces)
375
+
376
+ def test_get_base_indent_string(self):
377
+ eq = self.assertEqual
378
+ p = self.parser
379
+ setcode = p.set_code
380
+ baseindent = p.get_base_indent_string
381
+
382
+ TestInfo = namedtuple('TestInfo', ['string', 'indent'])
383
+ tests = (TestInfo('', ''),
384
+ TestInfo('def a():\n', ''),
385
+ TestInfo('\tdef a():\n', '\t'),
386
+ TestInfo(' def a():\n', ' '),
387
+ TestInfo(' def a(\n', ' '),
388
+ TestInfo('\t\n def a(\n', ' '),
389
+ TestInfo('\t\n # Comment.\n', ' '),
390
+ )
391
+
392
+ for test in tests:
393
+ with self.subTest(string=test.string):
394
+ setcode(test.string)
395
+ eq(baseindent(), test.indent)
396
+
397
+ def test_is_block_opener(self):
398
+ yes = self.assertTrue
399
+ no = self.assertFalse
400
+ p = self.parser
401
+ setcode = p.set_code
402
+ opener = p.is_block_opener
403
+
404
+ TestInfo = namedtuple('TestInfo', ['string', 'assert_'])
405
+ tests = (
406
+ TestInfo('def a():\n', yes),
407
+ TestInfo('\n def function1(self, a,\n b):\n', yes),
408
+ TestInfo(':\n', yes),
409
+ TestInfo('a:\n', yes),
410
+ TestInfo('):\n', yes),
411
+ TestInfo('(:\n', yes),
412
+ TestInfo('":\n', no),
413
+ TestInfo('\n def function1(self, a,\n', no),
414
+ TestInfo('def function1(self, a):\n pass\n', no),
415
+ TestInfo('# A comment:\n', no),
416
+ TestInfo('"""A docstring:\n', no),
417
+ TestInfo('"""A docstring:\n', no),
418
+ )
419
+
420
+ for test in tests:
421
+ with self.subTest(string=test.string):
422
+ setcode(test.string)
423
+ test.assert_(opener())
424
+
425
+ def test_is_block_closer(self):
426
+ yes = self.assertTrue
427
+ no = self.assertFalse
428
+ p = self.parser
429
+ setcode = p.set_code
430
+ closer = p.is_block_closer
431
+
432
+ TestInfo = namedtuple('TestInfo', ['string', 'assert_'])
433
+ tests = (
434
+ TestInfo('return\n', yes),
435
+ TestInfo('\tbreak\n', yes),
436
+ TestInfo(' continue\n', yes),
437
+ TestInfo(' raise\n', yes),
438
+ TestInfo('pass \n', yes),
439
+ TestInfo('pass\t\n', yes),
440
+ TestInfo('return #\n', yes),
441
+ TestInfo('raised\n', no),
442
+ TestInfo('returning\n', no),
443
+ TestInfo('# return\n', no),
444
+ TestInfo('"""break\n', no),
445
+ TestInfo('"continue\n', no),
446
+ TestInfo('def function1(self, a):\n pass\n', yes),
447
+ )
448
+
449
+ for test in tests:
450
+ with self.subTest(string=test.string):
451
+ setcode(test.string)
452
+ test.assert_(closer())
453
+
454
+ def test_get_last_stmt_bracketing(self):
455
+ eq = self.assertEqual
456
+ p = self.parser
457
+ setcode = p.set_code
458
+ bracketing = p.get_last_stmt_bracketing
459
+
460
+ TestInfo = namedtuple('TestInfo', ['string', 'bracket'])
461
+ tests = (
462
+ TestInfo('', ((0, 0),)),
463
+ TestInfo('a\n', ((0, 0),)),
464
+ TestInfo('()()\n', ((0, 0), (0, 1), (2, 0), (2, 1), (4, 0))),
465
+ TestInfo('(\n)()\n', ((0, 0), (0, 1), (3, 0), (3, 1), (5, 0))),
466
+ TestInfo('()\n()\n', ((3, 0), (3, 1), (5, 0))),
467
+ TestInfo('()(\n)\n', ((0, 0), (0, 1), (2, 0), (2, 1), (5, 0))),
468
+ TestInfo('(())\n', ((0, 0), (0, 1), (1, 2), (3, 1), (4, 0))),
469
+ TestInfo('(\n())\n', ((0, 0), (0, 1), (2, 2), (4, 1), (5, 0))),
470
+ # Same as matched test.
471
+ TestInfo('{)(]\n', ((0, 0), (0, 1), (2, 0), (2, 1), (4, 0))),
472
+ TestInfo('(((())\n',
473
+ ((0, 0), (0, 1), (1, 2), (2, 3), (3, 4), (5, 3), (6, 2))),
474
+ )
475
+
476
+ for test in tests:
477
+ with self.subTest(string=test.string):
478
+ setcode(test.string)
479
+ eq(bracketing(), test.bracket)
480
+
481
+
482
+ if __name__ == '__main__':
483
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_rpc.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Test rpc, coverage 20%."
2
+
3
+ from idlelib import rpc
4
+ import unittest
5
+
6
+
7
+
8
+ class CodePicklerTest(unittest.TestCase):
9
+
10
+ def test_pickle_unpickle(self):
11
+ def f(): return a + b + c
12
+ func, (cbytes,) = rpc.pickle_code(f.__code__)
13
+ self.assertIs(func, rpc.unpickle_code)
14
+ self.assertIn(b'test_rpc.py', cbytes)
15
+ code = rpc.unpickle_code(cbytes)
16
+ self.assertEqual(code.co_names, ('a', 'b', 'c'))
17
+
18
+ def test_code_pickler(self):
19
+ self.assertIn(type((lambda:None).__code__),
20
+ rpc.CodePickler.dispatch_table)
21
+
22
+ def test_dumps(self):
23
+ def f(): pass
24
+ # The main test here is that pickling code does not raise.
25
+ self.assertIn(b'test_rpc.py', rpc.dumps(f.__code__))
26
+
27
+
28
+ if __name__ == '__main__':
29
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_runscript.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Test runscript, coverage 16%."
2
+
3
+ from idlelib import runscript
4
+ import unittest
5
+ from test.support import requires
6
+ from tkinter import Tk
7
+ from idlelib.editor import EditorWindow
8
+
9
+
10
+ class ScriptBindingTest(unittest.TestCase):
11
+
12
+ @classmethod
13
+ def setUpClass(cls):
14
+ requires('gui')
15
+ cls.root = Tk()
16
+ cls.root.withdraw()
17
+
18
+ @classmethod
19
+ def tearDownClass(cls):
20
+ cls.root.update_idletasks()
21
+ for id in cls.root.tk.call('after', 'info'):
22
+ cls.root.after_cancel(id) # Need for EditorWindow.
23
+ cls.root.destroy()
24
+ del cls.root
25
+
26
+ def test_init(self):
27
+ ew = EditorWindow(root=self.root)
28
+ sb = runscript.ScriptBinding(ew)
29
+ ew._close()
30
+
31
+
32
+ if __name__ == '__main__':
33
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_scrolledlist.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Test scrolledlist, coverage 38%."
2
+
3
+ from idlelib.scrolledlist import ScrolledList
4
+ import unittest
5
+ from test.support import requires
6
+ requires('gui')
7
+ from tkinter import Tk
8
+
9
+
10
+ class ScrolledListTest(unittest.TestCase):
11
+
12
+ @classmethod
13
+ def setUpClass(cls):
14
+ cls.root = Tk()
15
+
16
+ @classmethod
17
+ def tearDownClass(cls):
18
+ cls.root.destroy()
19
+ del cls.root
20
+
21
+
22
+ def test_init(self):
23
+ ScrolledList(self.root)
24
+
25
+
26
+ if __name__ == '__main__':
27
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_search.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Test search, coverage 69%."
2
+
3
+ from idlelib import search
4
+ import unittest
5
+ from test.support import requires
6
+ requires('gui')
7
+ from tkinter import Tk, Text, BooleanVar
8
+ from idlelib import searchengine
9
+
10
+ # Does not currently test the event handler wrappers.
11
+ # A usage test should simulate clicks and check highlighting.
12
+ # Tests need to be coordinated with SearchDialogBase tests
13
+ # to avoid duplication.
14
+
15
+
16
+ class SearchDialogTest(unittest.TestCase):
17
+
18
+ @classmethod
19
+ def setUpClass(cls):
20
+ cls.root = Tk()
21
+
22
+ @classmethod
23
+ def tearDownClass(cls):
24
+ cls.root.destroy()
25
+ del cls.root
26
+
27
+ def setUp(self):
28
+ self.engine = searchengine.SearchEngine(self.root)
29
+ self.dialog = search.SearchDialog(self.root, self.engine)
30
+ self.dialog.bell = lambda: None
31
+ self.text = Text(self.root)
32
+ self.text.insert('1.0', 'Hello World!')
33
+
34
+ def test_find_again(self):
35
+ # Search for various expressions
36
+ text = self.text
37
+
38
+ self.engine.setpat('')
39
+ self.assertFalse(self.dialog.find_again(text))
40
+ self.dialog.bell = lambda: None
41
+
42
+ self.engine.setpat('Hello')
43
+ self.assertTrue(self.dialog.find_again(text))
44
+
45
+ self.engine.setpat('Goodbye')
46
+ self.assertFalse(self.dialog.find_again(text))
47
+
48
+ self.engine.setpat('World!')
49
+ self.assertTrue(self.dialog.find_again(text))
50
+
51
+ self.engine.setpat('Hello World!')
52
+ self.assertTrue(self.dialog.find_again(text))
53
+
54
+ # Regular expression
55
+ self.engine.revar = BooleanVar(self.root, True)
56
+ self.engine.setpat('W[aeiouy]r')
57
+ self.assertTrue(self.dialog.find_again(text))
58
+
59
+ def test_find_selection(self):
60
+ # Select some text and make sure it's found
61
+ text = self.text
62
+ # Add additional line to find
63
+ self.text.insert('2.0', 'Hello World!')
64
+
65
+ text.tag_add('sel', '1.0', '1.4') # Select 'Hello'
66
+ self.assertTrue(self.dialog.find_selection(text))
67
+
68
+ text.tag_remove('sel', '1.0', 'end')
69
+ text.tag_add('sel', '1.6', '1.11') # Select 'World!'
70
+ self.assertTrue(self.dialog.find_selection(text))
71
+
72
+ text.tag_remove('sel', '1.0', 'end')
73
+ text.tag_add('sel', '1.0', '1.11') # Select 'Hello World!'
74
+ self.assertTrue(self.dialog.find_selection(text))
75
+
76
+ # Remove additional line
77
+ text.delete('2.0', 'end')
78
+
79
+ if __name__ == '__main__':
80
+ unittest.main(verbosity=2, exit=2)
llava/lib/python3.10/idlelib/idle_test/test_searchengine.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Test searchengine, coverage 99%."
2
+
3
+ from idlelib import searchengine as se
4
+ import unittest
5
+ # from test.support import requires
6
+ from tkinter import BooleanVar, StringVar, TclError # ,Tk, Text
7
+ from tkinter import messagebox
8
+ from idlelib.idle_test.mock_tk import Var, Mbox
9
+ from idlelib.idle_test.mock_tk import Text as mockText
10
+ import re
11
+
12
+ # With mock replacements, the module does not use any gui widgets.
13
+ # The use of tk.Text is avoided (for now, until mock Text is improved)
14
+ # by patching instances with an index function returning what is needed.
15
+ # This works because mock Text.get does not use .index.
16
+ # The tkinter imports are used to restore searchengine.
17
+
18
+ def setUpModule():
19
+ # Replace s-e module tkinter imports other than non-gui TclError.
20
+ se.BooleanVar = Var
21
+ se.StringVar = Var
22
+ se.messagebox = Mbox
23
+
24
+ def tearDownModule():
25
+ # Restore 'just in case', though other tests should also replace.
26
+ se.BooleanVar = BooleanVar
27
+ se.StringVar = StringVar
28
+ se.messagebox = messagebox
29
+
30
+
31
+ class Mock:
32
+ def __init__(self, *args, **kwargs): pass
33
+
34
+ class GetTest(unittest.TestCase):
35
+ # SearchEngine.get returns singleton created & saved on first call.
36
+ def test_get(self):
37
+ saved_Engine = se.SearchEngine
38
+ se.SearchEngine = Mock # monkey-patch class
39
+ try:
40
+ root = Mock()
41
+ engine = se.get(root)
42
+ self.assertIsInstance(engine, se.SearchEngine)
43
+ self.assertIs(root._searchengine, engine)
44
+ self.assertIs(se.get(root), engine)
45
+ finally:
46
+ se.SearchEngine = saved_Engine # restore class to module
47
+
48
+ class GetLineColTest(unittest.TestCase):
49
+ # Test simple text-independent helper function
50
+ def test_get_line_col(self):
51
+ self.assertEqual(se.get_line_col('1.0'), (1, 0))
52
+ self.assertEqual(se.get_line_col('1.11'), (1, 11))
53
+
54
+ self.assertRaises(ValueError, se.get_line_col, ('1.0 lineend'))
55
+ self.assertRaises(ValueError, se.get_line_col, ('end'))
56
+
57
+ class GetSelectionTest(unittest.TestCase):
58
+ # Test text-dependent helper function.
59
+ ## # Need gui for text.index('sel.first/sel.last/insert').
60
+ ## @classmethod
61
+ ## def setUpClass(cls):
62
+ ## requires('gui')
63
+ ## cls.root = Tk()
64
+ ##
65
+ ## @classmethod
66
+ ## def tearDownClass(cls):
67
+ ## cls.root.destroy()
68
+ ## del cls.root
69
+
70
+ def test_get_selection(self):
71
+ # text = Text(master=self.root)
72
+ text = mockText()
73
+ text.insert('1.0', 'Hello World!')
74
+
75
+ # fix text.index result when called in get_selection
76
+ def sel(s):
77
+ # select entire text, cursor irrelevant
78
+ if s == 'sel.first': return '1.0'
79
+ if s == 'sel.last': return '1.12'
80
+ raise TclError
81
+ text.index = sel # replaces .tag_add('sel', '1.0, '1.12')
82
+ self.assertEqual(se.get_selection(text), ('1.0', '1.12'))
83
+
84
+ def mark(s):
85
+ # no selection, cursor after 'Hello'
86
+ if s == 'insert': return '1.5'
87
+ raise TclError
88
+ text.index = mark # replaces .mark_set('insert', '1.5')
89
+ self.assertEqual(se.get_selection(text), ('1.5', '1.5'))
90
+
91
+
92
+ class ReverseSearchTest(unittest.TestCase):
93
+ # Test helper function that searches backwards within a line.
94
+ def test_search_reverse(self):
95
+ Equal = self.assertEqual
96
+ line = "Here is an 'is' test text."
97
+ prog = re.compile('is')
98
+ Equal(se.search_reverse(prog, line, len(line)).span(), (12, 14))
99
+ Equal(se.search_reverse(prog, line, 14).span(), (12, 14))
100
+ Equal(se.search_reverse(prog, line, 13).span(), (5, 7))
101
+ Equal(se.search_reverse(prog, line, 7).span(), (5, 7))
102
+ Equal(se.search_reverse(prog, line, 6), None)
103
+
104
+
105
+ class SearchEngineTest(unittest.TestCase):
106
+ # Test class methods that do not use Text widget.
107
+
108
+ def setUp(self):
109
+ self.engine = se.SearchEngine(root=None)
110
+ # Engine.root is only used to create error message boxes.
111
+ # The mock replacement ignores the root argument.
112
+
113
+ def test_is_get(self):
114
+ engine = self.engine
115
+ Equal = self.assertEqual
116
+
117
+ Equal(engine.getpat(), '')
118
+ engine.setpat('hello')
119
+ Equal(engine.getpat(), 'hello')
120
+
121
+ Equal(engine.isre(), False)
122
+ engine.revar.set(1)
123
+ Equal(engine.isre(), True)
124
+
125
+ Equal(engine.iscase(), False)
126
+ engine.casevar.set(1)
127
+ Equal(engine.iscase(), True)
128
+
129
+ Equal(engine.isword(), False)
130
+ engine.wordvar.set(1)
131
+ Equal(engine.isword(), True)
132
+
133
+ Equal(engine.iswrap(), True)
134
+ engine.wrapvar.set(0)
135
+ Equal(engine.iswrap(), False)
136
+
137
+ Equal(engine.isback(), False)
138
+ engine.backvar.set(1)
139
+ Equal(engine.isback(), True)
140
+
141
+ def test_setcookedpat(self):
142
+ engine = self.engine
143
+ engine.setcookedpat(r'\s')
144
+ self.assertEqual(engine.getpat(), r'\s')
145
+ engine.revar.set(1)
146
+ engine.setcookedpat(r'\s')
147
+ self.assertEqual(engine.getpat(), r'\\s')
148
+
149
+ def test_getcookedpat(self):
150
+ engine = self.engine
151
+ Equal = self.assertEqual
152
+
153
+ Equal(engine.getcookedpat(), '')
154
+ engine.setpat('hello')
155
+ Equal(engine.getcookedpat(), 'hello')
156
+ engine.wordvar.set(True)
157
+ Equal(engine.getcookedpat(), r'\bhello\b')
158
+ engine.wordvar.set(False)
159
+
160
+ engine.setpat(r'\s')
161
+ Equal(engine.getcookedpat(), r'\\s')
162
+ engine.revar.set(True)
163
+ Equal(engine.getcookedpat(), r'\s')
164
+
165
+ def test_getprog(self):
166
+ engine = self.engine
167
+ Equal = self.assertEqual
168
+
169
+ engine.setpat('Hello')
170
+ temppat = engine.getprog()
171
+ Equal(temppat.pattern, re.compile('Hello', re.IGNORECASE).pattern)
172
+ engine.casevar.set(1)
173
+ temppat = engine.getprog()
174
+ Equal(temppat.pattern, re.compile('Hello').pattern, 0)
175
+
176
+ engine.setpat('')
177
+ Equal(engine.getprog(), None)
178
+ Equal(Mbox.showerror.message,
179
+ 'Error: Empty regular expression')
180
+ engine.setpat('+')
181
+ engine.revar.set(1)
182
+ Equal(engine.getprog(), None)
183
+ Equal(Mbox.showerror.message,
184
+ 'Error: nothing to repeat\nPattern: +\nOffset: 0')
185
+
186
+ def test_report_error(self):
187
+ showerror = Mbox.showerror
188
+ Equal = self.assertEqual
189
+ pat = '[a-z'
190
+ msg = 'unexpected end of regular expression'
191
+
192
+ Equal(self.engine.report_error(pat, msg), None)
193
+ Equal(showerror.title, 'Regular expression error')
194
+ expected_message = ("Error: " + msg + "\nPattern: [a-z")
195
+ Equal(showerror.message, expected_message)
196
+
197
+ Equal(self.engine.report_error(pat, msg, 5), None)
198
+ Equal(showerror.title, 'Regular expression error')
199
+ expected_message += "\nOffset: 5"
200
+ Equal(showerror.message, expected_message)
201
+
202
+
203
+ class SearchTest(unittest.TestCase):
204
+ # Test that search_text makes right call to right method.
205
+
206
+ @classmethod
207
+ def setUpClass(cls):
208
+ ## requires('gui')
209
+ ## cls.root = Tk()
210
+ ## cls.text = Text(master=cls.root)
211
+ cls.text = mockText()
212
+ test_text = (
213
+ 'First line\n'
214
+ 'Line with target\n'
215
+ 'Last line\n')
216
+ cls.text.insert('1.0', test_text)
217
+ cls.pat = re.compile('target')
218
+
219
+ cls.engine = se.SearchEngine(None)
220
+ cls.engine.search_forward = lambda *args: ('f', args)
221
+ cls.engine.search_backward = lambda *args: ('b', args)
222
+
223
+ ## @classmethod
224
+ ## def tearDownClass(cls):
225
+ ## cls.root.destroy()
226
+ ## del cls.root
227
+
228
+ def test_search(self):
229
+ Equal = self.assertEqual
230
+ engine = self.engine
231
+ search = engine.search_text
232
+ text = self.text
233
+ pat = self.pat
234
+
235
+ engine.patvar.set(None)
236
+ #engine.revar.set(pat)
237
+ Equal(search(text), None)
238
+
239
+ def mark(s):
240
+ # no selection, cursor after 'Hello'
241
+ if s == 'insert': return '1.5'
242
+ raise TclError
243
+ text.index = mark
244
+ Equal(search(text, pat), ('f', (text, pat, 1, 5, True, False)))
245
+ engine.wrapvar.set(False)
246
+ Equal(search(text, pat), ('f', (text, pat, 1, 5, False, False)))
247
+ engine.wrapvar.set(True)
248
+ engine.backvar.set(True)
249
+ Equal(search(text, pat), ('b', (text, pat, 1, 5, True, False)))
250
+ engine.backvar.set(False)
251
+
252
+ def sel(s):
253
+ if s == 'sel.first': return '2.10'
254
+ if s == 'sel.last': return '2.16'
255
+ raise TclError
256
+ text.index = sel
257
+ Equal(search(text, pat), ('f', (text, pat, 2, 16, True, False)))
258
+ Equal(search(text, pat, True), ('f', (text, pat, 2, 10, True, True)))
259
+ engine.backvar.set(True)
260
+ Equal(search(text, pat), ('b', (text, pat, 2, 10, True, False)))
261
+ Equal(search(text, pat, True), ('b', (text, pat, 2, 16, True, True)))
262
+
263
+
264
+ class ForwardBackwardTest(unittest.TestCase):
265
+ # Test that search_forward method finds the target.
266
+ ## @classmethod
267
+ ## def tearDownClass(cls):
268
+ ## cls.root.destroy()
269
+ ## del cls.root
270
+
271
+ @classmethod
272
+ def setUpClass(cls):
273
+ cls.engine = se.SearchEngine(None)
274
+ ## requires('gui')
275
+ ## cls.root = Tk()
276
+ ## cls.text = Text(master=cls.root)
277
+ cls.text = mockText()
278
+ # search_backward calls index('end-1c')
279
+ cls.text.index = lambda index: '4.0'
280
+ test_text = (
281
+ 'First line\n'
282
+ 'Line with target\n'
283
+ 'Last line\n')
284
+ cls.text.insert('1.0', test_text)
285
+ cls.pat = re.compile('target')
286
+ cls.res = (2, (10, 16)) # line, slice indexes of 'target'
287
+ cls.failpat = re.compile('xyz') # not in text
288
+ cls.emptypat = re.compile(r'\w*') # empty match possible
289
+
290
+ def make_search(self, func):
291
+ def search(pat, line, col, wrap, ok=0):
292
+ res = func(self.text, pat, line, col, wrap, ok)
293
+ # res is (line, matchobject) or None
294
+ return (res[0], res[1].span()) if res else res
295
+ return search
296
+
297
+ def test_search_forward(self):
298
+ # search for non-empty match
299
+ Equal = self.assertEqual
300
+ forward = self.make_search(self.engine.search_forward)
301
+ pat = self.pat
302
+ Equal(forward(pat, 1, 0, True), self.res)
303
+ Equal(forward(pat, 3, 0, True), self.res) # wrap
304
+ Equal(forward(pat, 3, 0, False), None) # no wrap
305
+ Equal(forward(pat, 2, 10, False), self.res)
306
+
307
+ Equal(forward(self.failpat, 1, 0, True), None)
308
+ Equal(forward(self.emptypat, 2, 9, True, ok=True), (2, (9, 9)))
309
+ #Equal(forward(self.emptypat, 2, 9, True), self.res)
310
+ # While the initial empty match is correctly ignored, skipping
311
+ # the rest of the line and returning (3, (0,4)) seems buggy - tjr.
312
+ Equal(forward(self.emptypat, 2, 10, True), self.res)
313
+
314
+ def test_search_backward(self):
315
+ # search for non-empty match
316
+ Equal = self.assertEqual
317
+ backward = self.make_search(self.engine.search_backward)
318
+ pat = self.pat
319
+ Equal(backward(pat, 3, 5, True), self.res)
320
+ Equal(backward(pat, 2, 0, True), self.res) # wrap
321
+ Equal(backward(pat, 2, 0, False), None) # no wrap
322
+ Equal(backward(pat, 2, 16, False), self.res)
323
+
324
+ Equal(backward(self.failpat, 3, 9, True), None)
325
+ Equal(backward(self.emptypat, 2, 10, True, ok=True), (2, (9,9)))
326
+ # Accepted because 9 < 10, not because ok=True.
327
+ # It is not clear that ok=True is useful going back - tjr
328
+ Equal(backward(self.emptypat, 2, 9, True), (2, (5, 9)))
329
+
330
+
331
+ if __name__ == '__main__':
332
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_statusbar.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Test statusbar, coverage 100%."
2
+
3
+ from idlelib import statusbar
4
+ import unittest
5
+ from test.support import requires
6
+ from tkinter import Tk
7
+
8
+
9
+ class Test(unittest.TestCase):
10
+
11
+ @classmethod
12
+ def setUpClass(cls):
13
+ requires('gui')
14
+ cls.root = Tk()
15
+ cls.root.withdraw()
16
+
17
+ @classmethod
18
+ def tearDownClass(cls):
19
+ cls.root.update_idletasks()
20
+ cls.root.destroy()
21
+ del cls.root
22
+
23
+ def test_init(self):
24
+ bar = statusbar.MultiStatusBar(self.root)
25
+ self.assertEqual(bar.labels, {})
26
+
27
+ def test_set_label(self):
28
+ bar = statusbar.MultiStatusBar(self.root)
29
+ bar.set_label('left', text='sometext', width=10)
30
+ self.assertIn('left', bar.labels)
31
+ left = bar.labels['left']
32
+ self.assertEqual(left['text'], 'sometext')
33
+ self.assertEqual(left['width'], 10)
34
+ bar.set_label('left', text='revised text')
35
+ self.assertEqual(left['text'], 'revised text')
36
+ bar.set_label('right', text='correct text')
37
+ self.assertEqual(bar.labels['right']['text'], 'correct text')
38
+
39
+
40
+ if __name__ == '__main__':
41
+ unittest.main(verbosity=2)
llava/lib/python3.10/idlelib/idle_test/test_undo.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Test undo, coverage 77%."
2
+ # Only test UndoDelegator so far.
3
+
4
+ from idlelib.undo import UndoDelegator
5
+ import unittest
6
+ from test.support import requires
7
+ requires('gui')
8
+
9
+ from unittest.mock import Mock
10
+ from tkinter import Text, Tk
11
+ from idlelib.percolator import Percolator
12
+
13
+
14
+ class UndoDelegatorTest(unittest.TestCase):
15
+
16
+ @classmethod
17
+ def setUpClass(cls):
18
+ cls.root = Tk()
19
+ cls.text = Text(cls.root)
20
+ cls.percolator = Percolator(cls.text)
21
+
22
+ @classmethod
23
+ def tearDownClass(cls):
24
+ cls.percolator.redir.close()
25
+ del cls.percolator, cls.text
26
+ cls.root.destroy()
27
+ del cls.root
28
+
29
+ def setUp(self):
30
+ self.delegator = UndoDelegator()
31
+ self.delegator.bell = Mock()
32
+ self.percolator.insertfilter(self.delegator)
33
+
34
+ def tearDown(self):
35
+ self.percolator.removefilter(self.delegator)
36
+ self.text.delete('1.0', 'end')
37
+ self.delegator.resetcache()
38
+
39
+ def test_undo_event(self):
40
+ text = self.text
41
+
42
+ text.insert('insert', 'foobar')
43
+ text.insert('insert', 'h')
44
+ text.event_generate('<<undo>>')
45
+ self.assertEqual(text.get('1.0', 'end'), '\n')
46
+
47
+ text.insert('insert', 'foo')
48
+ text.insert('insert', 'bar')
49
+ text.delete('1.2', '1.4')
50
+ text.insert('insert', 'hello')
51
+ text.event_generate('<<undo>>')
52
+ self.assertEqual(text.get('1.0', '1.4'), 'foar')
53
+ text.event_generate('<<undo>>')
54
+ self.assertEqual(text.get('1.0', '1.6'), 'foobar')
55
+ text.event_generate('<<undo>>')
56
+ self.assertEqual(text.get('1.0', '1.3'), 'foo')
57
+ text.event_generate('<<undo>>')
58
+ self.delegator.undo_event('event')
59
+ self.assertTrue(self.delegator.bell.called)
60
+
61
+ def test_redo_event(self):
62
+ text = self.text
63
+
64
+ text.insert('insert', 'foo')
65
+ text.insert('insert', 'bar')
66
+ text.delete('1.0', '1.3')
67
+ text.event_generate('<<undo>>')
68
+ text.event_generate('<<redo>>')
69
+ self.assertEqual(text.get('1.0', '1.3'), 'bar')
70
+ text.event_generate('<<redo>>')
71
+ self.assertTrue(self.delegator.bell.called)
72
+
73
+ def test_dump_event(self):
74
+ """
75
+ Dump_event cannot be tested directly without changing
76
+ environment variables. So, test statements in dump_event
77
+ indirectly
78
+ """
79
+ text = self.text
80
+ d = self.delegator
81
+
82
+ text.insert('insert', 'foo')
83
+ text.insert('insert', 'bar')
84
+ text.delete('1.2', '1.4')
85
+ self.assertTupleEqual((d.pointer, d.can_merge), (3, True))
86
+ text.event_generate('<<undo>>')
87
+ self.assertTupleEqual((d.pointer, d.can_merge), (2, False))
88
+
89
+ def test_get_set_saved(self):
90
+ # test the getter method get_saved
91
+ # test the setter method set_saved
92
+ # indirectly test check_saved
93
+ d = self.delegator
94
+
95
+ self.assertTrue(d.get_saved())
96
+ self.text.insert('insert', 'a')
97
+ self.assertFalse(d.get_saved())
98
+ d.saved_change_hook = Mock()
99
+
100
+ d.set_saved(True)
101
+ self.assertEqual(d.pointer, d.saved)
102
+ self.assertTrue(d.saved_change_hook.called)
103
+
104
+ d.set_saved(False)
105
+ self.assertEqual(d.saved, -1)
106
+ self.assertTrue(d.saved_change_hook.called)
107
+
108
+ def test_undo_start_stop(self):
109
+ # test the undo_block_start and undo_block_stop methods
110
+ text = self.text
111
+
112
+ text.insert('insert', 'foo')
113
+ self.delegator.undo_block_start()
114
+ text.insert('insert', 'bar')
115
+ text.insert('insert', 'bar')
116
+ self.delegator.undo_block_stop()
117
+ self.assertEqual(text.get('1.0', '1.3'), 'foo')
118
+
119
+ # test another code path
120
+ self.delegator.undo_block_start()
121
+ text.insert('insert', 'bar')
122
+ self.delegator.undo_block_stop()
123
+ self.assertEqual(text.get('1.0', '1.3'), 'foo')
124
+
125
+ def test_addcmd(self):
126
+ text = self.text
127
+ # when number of undo operations exceeds max_undo
128
+ self.delegator.max_undo = max_undo = 10
129
+ for i in range(max_undo + 10):
130
+ text.insert('insert', 'foo')
131
+ self.assertLessEqual(len(self.delegator.undolist), max_undo)
132
+
133
+
134
+ if __name__ == '__main__':
135
+ unittest.main(verbosity=2, exit=False)