File: Test.py

package info (click to toggle)
python-pmw 0.8.5-6
  • links: PTS
  • area: main
  • in suites: woody
  • size: 1,820 kB
  • ctags: 3,468
  • sloc: python: 14,898; makefile: 37; sh: 17
file content (485 lines) | stat: -rw-r--r-- 12,511 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
# Functions used by widget tests.

import imp
import os
import re
import string
import sys
import traceback
import types
import Tkinter

script_name = imp.find_module(__name__)[1]
if not os.path.isabs(script_name):
    script_name = os.path.join(os.getcwd(), script_name)

while 1:
    script_dir = os.path.dirname(script_name)
    if not os.path.islink(script_name):
	break
    script_name = os.path.join(script_dir, os.readlink(script_name))
script_dir = os.path.join(os.getcwd(), script_dir)
script_dir = os.path.normpath(script_dir)
 
# Add the '../../..' directory to the path.
package_dir = os.path.dirname(script_dir)
package_dir = os.path.dirname(package_dir)
package_dir = os.path.dirname(package_dir)
sys.path[:0] = [package_dir]

import Pmw
# Need to import TestVersion, rather than do its work here, since
# __name__ will be known there.
import TestVersion

# Set this to 1 to generate tracebacks on exceptions, rather than
# catching them and continuing with the tests.
# This is useful for debugging the test scripts.
dont_even_try = 0

_delay = 1
_verbose = 0
_printTraceback = 0
_initialised = 0

##############################################################################
# Public functions:

rand = 12345
def random():
    global rand
    rand = (rand * 125) % 2796203
    return rand

def initialise():
    global _initialised, font, flagup, earthris, emptyimage, \
            stringvar, floatvar, root, reliefs
    if not _initialised:
	root = Tkinter.Tk(className = 'PmwTest')
	root.withdraw()
	Pmw.initialise(root, fontScheme = 'pmw1')
	font = {}
	font['small'] = '6x13'
	font['large'] = '10x20'
	font['variable'] = '-Adobe-Helvetica-Bold-R-Normal--*-120-*-*-*-*-*-*'
	flagup = Tkinter.BitmapImage(file = 'flagup.bmp')
	earthris = Tkinter.PhotoImage(file = 'earthris.gif')
	emptyimage = Tkinter.PhotoImage()
	stringvar = Tkinter.StringVar()
	stringvar.set('this is some text')
	floatvar = Tkinter.DoubleVar()
	floatvar.set(50.0)
	if haveBlt():
	    global vectorSize, vector_x, vector_y
	    vector_x = Pmw.Blt.Vector()
	    vector_y = []
	    for y in range(3):
		vector_y.append(Pmw.Blt.Vector())
	    vectorSize = 50
	    for index in range(vectorSize):
		vector_x.append(index)
		vector_y[0].append(random() % 100)
		vector_y[1].append(random() % 200)
		vector_y[2].append(random() % 100 + 300)

	# "solid" relief type was added to 8.0
	if Tkinter.TkVersion >= 8.0:
	  reliefs = 'flat, groove, raised, ridge, solid, or sunken'
	else:
	  reliefs = 'flat, groove, raised, ridge, or sunken'

	_initialised = 1

def haveBlt():
    return Pmw.Blt.haveblt(root)

def bell():
    root.bell()

def setdelay(newdelay):
    global _delay
    _delay = newdelay

def setverbose(newverbose):
    global _verbose
    _verbose = newverbose

def printtraceback(newprintTraceback = 1):
    global _printTraceback
    _printTraceback = newprintTraceback

def num_options(widget):
    return len(widget.configure())

def callback():
    return 1

def callback1(dummy):
    # Callback taking 1 argument
    return dummy

def callback2(dummy1, dummy2):
    # Callback taking 2 arguments
    return (dummy1, dummy2)

def callbackN(*args):
    # Callback taking zero or more arguments
    return args

def actioncallback():
    w = currentWidget()
    w.action('button press')

def currentWidget():
    return _currentWidget

def delay():
    return _delay

def set_geom(width, height):
    _currentToplevel.geometry(str(width) + 'x' + str(height))

def runTests(allTestData):
    root.after(_delay, _runTest, None, None, allTestData, 0, -1, -1)
    root.mainloop()

_pattern = None

##############################################################################
# Private functions:

def _print_results(result, expected, description):
    if type(expected) == types.ClassType:
	if hasattr(result, '__class__'):
	    ok = (result.__class__ == expected)
	else:
	    ok = 0
    else:
	ok = (result == expected)

	# Megawidgets return a value of the correct type.  Tk widgets
	# always return a string, so convert the string and check again.
	if not ok:
	    if type(expected) == types.InstanceType:
	      if result == str(expected) and (
                  expected is earthris or expected is stringvar or
		  expected is floatvar or expected is flagup):
	        ok = 1
	    elif type(expected) == types.IntType:
		if type(result) is types.StringType:
		    try:
			ok = (string.atoi(result) == expected)
		    except ValueError:
			pass
	    elif type(expected) == types.FloatType:
		if type(result) is types.StringType:
		    try:
			ok = (string.atof(result) == expected)
		    except ValueError:
			pass
	    elif expected == callback:
		ok = re.search('^[0-9]*callback$', str(result)) is not None
	    elif expected == callback1:
		ok = re.search('^[0-9]*callback1$', str(result)) is not None
	    elif expected == callback2:
		ok = re.search('^[0-9]*callback2$', str(result)) is not None
	    elif expected == actioncallback:
		ok = re.search('^[0-9]*actioncallback$',str(result)) is not None
        
    if not ok or _verbose > 0:
	print '====', description
	if not ok or _verbose > 1:
	    print '==== result was:'
	    print result, type(result)
    if ok:
	if _verbose > 1:
	    print '++++ PASSED'
    else:
        print '---- result should have been:'
	print expected, type(expected)
	if _printTraceback:
	    traceback.print_exc()
	print '---- FAILED'
	print

def _destroyToplevel(top, title):
    if _verbose > 0:
	print '==== destruction of Toplevel for', title
    top.destroy()

def _Toplevel(title):
    if _verbose > 0:
	print '==== construction of Toplevel for', title
    top = Tkinter.Toplevel()
    top.geometry('+100+100')
    top.title(title)
    return top

def _constructor(isToplevel, isWidget, top, classCmd, kw):
    if _verbose > 0:
	print '====', classCmd.__name__, 'construction'
    if isWidget:
	if dont_even_try:
	    w = apply(classCmd, (top,), kw)
	else:
	    try:
		w = apply(classCmd, (top,), kw)
	    except:
		print 'Could not construct', classCmd.__name__
		traceback.print_exc()
		print 'Can not continue'
		print 'Bye'
		return None

	isMegaWidget = hasattr(classCmd, 'defineoptions')
	# Check the option types:
	options = w.configure()
	option_list = options.keys()
	option_list.sort()
	for option in option_list:
	    # Some of the options (like bd, bg and fg) have only two parts
	    # and are just abbreviations.  Only check 'real' options.
	    if len(options[option]) == 5:
		initoption = isMegaWidget and w.isinitoption(option)
		if dont_even_try:
		    value = w.cget(option)
		    if option not in ('class', 'container') and not initoption:
		      apply(w.configure, (), {option : value})
		      newvalue = w.cget(option)
		      if newvalue != value:
			print '====', classCmd.__name__, 'widget', \
			  '\'' + option + '\'', 'option'
			print '---- setting option returns different value'
			print '---- FAILED'
			print
		else:
		    try:
			value = w.cget(option)
			if option not in ('class', 'container') and not initoption:
			  try:
			      apply(w.configure, (), {option : value})
			      newvalue = w.cget(option)
			      if newvalue != value:
				print '====', classCmd.__name__, 'widget', \
				  '\'' + option + '\'', 'option'
				print '---- setting option returns different value'
				print '---- FAILED'
				print
			  except:
			    print '====', classCmd.__name__, 'widget', \
			      '\'' + option + '\'', 'option'
			    print '---- could not set option'
			    print '---- FAILED'
			    print
		    except KeyError:
			print '====', classCmd.__name__, 'widget', \
			    '\'' + option + '\'', 'option'
			print '---- unknown option'
			print '---- FAILED'
			print

	if hasattr(classCmd, 'geometry'):
	    w.geometry('+100+100')
	    w.title(classCmd.__name__)
    else:
	w = apply(classCmd, (), kw)
    return w

def _destructor(widget, isWidget):
    if _verbose > 0:
        print '====', widget.__class__.__name__, 'destruction'
    if isWidget:
	if dont_even_try:
	    widget.destroy()
	else:
	    try:
		widget.destroy()
                ref = sys.getrefcount(widget)
                if isWidget and ref != 6:
                    print '====', widget.__class__.__name__, 'destructor'
                    print '---- refcount', ref, 'not zero after destruction'
                    print '---- FAILED'
                    print
	    except:
		print 'Could not destroy', widget.__class__.__name__
		traceback.print_exc()
		print 'Can not continue'
		print 'Bye'
		return None
    return 1

# Structure of allTestData:
# (
#   (
#     'ButtonBox', 
#     (
#       (
#         Pmw.ButtonBox,
#         {},
#         (
#           (c.pack, ()),
#           (c.pack, ()),
#           (c.pack, ()),
#           ...
#         )
#       ),
#       (
#         Pmw.ButtonBox,
#         {},
#         (
#           (c.pack, ()),
#           (c.pack, ()),
#           (c.pack, ()),
#           ...
#         )
#       ),
#       ...
#     )
#   ),
#   (
#     'ButtonBox', 
#     (
#       (
#         Pmw.ButtonBox,
#         {},
#         (
#           (c.pack, ()),
#           (c.pack, ()),
#           (c.pack, ()),
#           ...
#         )
#       ),
#       (
#         Pmw.ButtonBox,
#         {},
#         (
#           (c.pack, ()),
#           (c.pack, ()),
#           (c.pack, ()),
#           ...
#         )
#       ),
#       ...
#     )
#   ),
#   ...
# )

def _runTest(top, w, allTestData, index0, index1, index2):
    if index0 >= len(allTestData):
	root.quit()
	return
    classCmd, fileTests = allTestData[index0]
    if classCmd == Tkinter.Menu:
	isToplevel = 1
    else:
	isToplevel = hasattr(classCmd, 'userdeletefunc')
    isWidget = hasattr(classCmd, 'cget')
    title = classCmd.__name__

    if index1 == -1:
	if isToplevel:
	    top = None
	else:
	    top = _Toplevel(title)
	global _currentToplevel
	_currentToplevel = top
	index1 = 0
    elif index1 >= len(fileTests):
	if not isToplevel:
	    _destroyToplevel(top, title)
	index1 = -1
	index0 = index0 + 1
    else:
	methodTests, kw = fileTests[index1]
	if index2 == -1:
	    w = _constructor(isToplevel, isWidget, top, classCmd, kw)
	    if w is None:
	        root.quit()
		return
	    global _currentWidget
	    _currentWidget = w
	    index2 = 0
	elif index2 >= len(methodTests):
	    if _destructor(w, isWidget) is None:
	        root.quit()
		return
	    index2 = -1
	    index1 = index1 + 1
	else:
	    methodTestData = methodTests[index2]
	    if type(methodTestData[0]) == types.StringType:
		_configureTest(w, methodTestData)
	    else:
		_methodTest(w, methodTestData)
	    index2 = index2 + 1
    root.update()
    root.after(_delay, _runTest, top, w, allTestData, index0, index1, index2)

def _configureTest(w, testData):
    option = testData[0]
    value = testData[1]
    if dont_even_try:
	apply(w.configure, (), {option: value})
	result = w.cget(option)
    else:
	try:
	    apply(w.configure, (), {option: value})
	    result = w.cget(option)
	except:
	    result = _getErrorValue()
    if len(testData) > 2:
	expected = testData[2]
    else:
	expected = value
    _print_results(result, expected, \
	w.__class__.__name__ + ' option ' + str(testData))

def _getErrorValue():
    exc_type, exc_value, exc_traceback = sys.exc_info()
    if type(exc_type) == types.ClassType:
	# Handle python 1.5 class exceptions.
	exc_type = exc_type.__name__
    if type(exc_value) == types.StringType:
	return exc_type + ': ' + exc_value
    else:
	return exc_type + ': ' + str(exc_value)

def _methodTest(w, testData):
    func = testData[0]
    args = testData[1]
    kw = {}
    expected = None
    if len(testData) == 3:
	if type(testData[2]) == types.DictionaryType:
	    kw = testData[2]
	else:
	    expected = testData[2]
    elif len(testData) > 3:
	kw = testData[2]
	expected = testData[3]
    if type(args) != types.TupleType:
	args = (args,)
    if func is num_options:
	args = (w,) + args
    origArgs = args
    if type(func) == types.MethodType and func.im_self is None:
	args = (w,) + args
    if dont_even_try:
	result = apply(func, args, kw)
    else:
	try:
	    result = apply(func, args, kw)
	except:
	    result = _getErrorValue()
    if hasattr(func, 'im_func'):
	name = w.__class__.__name__ + ' method ' + \
	    func.im_func.func_code.co_name
    elif hasattr(func, '__dict__'):
	name = 'static method ' + func.__dict__['_func'].func_code.co_name
    else:
	name = 'function ' + func.__name__
    name = name + ' ' + str(origArgs)
    if kw:
	name = name + ' ' + str(kw)
    _print_results(result, expected, name)