Commit b7308b03 authored by David Gobbi's avatar David Gobbi
Browse files

Patch CommonCore python tests for py3k.

This change modifies the python code for the tests so that they are
cross-compatible between python 2 and python 3.  The new code will not
run on Python 2.5 or earlier, because only python 2.6 and 2.7 allow
py3k-friendly syntax.

The numpy_interface does not fully support python 3 yet, due to changes
in the way numeric operators work and the way type coercion is done.
parent d3eb4043
......@@ -4,43 +4,43 @@ try:
import vtk
except:
print "Cannot import vtk"
print("Cannot import vtk")
sys.exit(1)
try:
print dir(vtk)
print(dir(vtk))
except:
print "Cannot print dir(vtk)"
print("Cannot print(dir(vtk)")
sys.exit(1)
try:
try:
try:
o = vtk.vtkLineWidget()
print "Using Hybrid"
print("Using Hybrid")
except:
o = vtk.vtkActor()
print "Using Rendering"
print("Using Rendering")
except:
o = vtk.vtkObject()
print "Using Common"
print("Using Common")
except:
print "Cannot create vtkObject"
print("Cannot create vtkObject")
sys.exit(1)
try:
print o
print "Reference count: %d" % o.GetReferenceCount()
print "Class name: %s" % o.GetClassName()
print(o)
print("Reference count: %d" % o.GetReferenceCount())
print("Class name: %s" % o.GetClassName())
except:
print "Cannot print object"
print("Cannot print object")
sys.exit(1)
try:
b = vtk.vtkObject()
d = b.SafeDownCast(o)
print b, d
print(b, d)
except:
print "Cannot downcast"
print("Cannot downcast")
sys.exit(1)
sys.exit(0)
......
......@@ -38,8 +38,10 @@ class TestArrayArguments(Testing.vtkTest):
a.GetTupleValue(0, to);
self.assertEqual(ti, to)
d1 = a.GetTuple(0)
d2 = map(float, ti)
self.assertEqual(map(round, d1), map(round, d2))
d2 = [float(x) for x in ti]
r1 = [round(x) for x in d1]
r2 = [round(x) for x in d2]
self.assertEqual(r1, r2)
def testUnsignedArrayArguments(self):
for arrayClass in unsignedArrays:
......@@ -52,8 +54,10 @@ class TestArrayArguments(Testing.vtkTest):
a.GetTupleValue(0, to);
self.assertEqual(ti, to)
d1 = a.GetTuple(0)
d2 = map(float, ti)
self.assertEqual(map(round, d1), map(round, d2))
d2 = [float(x) for x in ti]
r1 = [round(x) for x in d1]
r2 = [round(x) for x in d2]
self.assertEqual(r1, r2)
def testCharArrayArguments(self):
a = vtk.vtkCharArray()
......@@ -65,7 +69,7 @@ class TestArrayArguments(Testing.vtkTest):
#to = "***"
#a.GetTupleValue(0, to);
d1 = list(a.GetTuple(0))
d2 = map(float, map(ord, ti))
d2 = [ord(x) for x in ti]
self.assertEqual(d1, d2)
def testBitArrayArguments(self):
......@@ -76,7 +80,7 @@ class TestArrayArguments(Testing.vtkTest):
to = [0,0]
a.SetTuple(0, ti)
a.GetTuple(0, to);
self.assertEqual(ti, map(int,to))
self.assertEqual(ti, [int(x) for x in to])
def testNDimArrayArguments(self):
a = [[0,0,0],[0,0,0],[0,0,0]]
......
......@@ -8,7 +8,7 @@ arrayType = ['Bit', 'Char', 'Double', 'Float', 'Int', 'Long', 'Short',\
'UnsignedChar', 'UnsignedInt', 'UnsignedLong', 'UnsignedShort']
for array in arrayType:
print array, 'array'
print(array, 'array')
vtkClass = 'vtk' + array + 'Array'
a = getattr(vtk, vtkClass)()
a.Allocate(1,1)
......@@ -46,7 +46,7 @@ for array in arrayType:
for j in range(0, a.GetNumberOfComponents()):
if a.GetComponent(i, j) != b.GetComponent(i, j):
s = '%s: bad component %d, %d' % (array, i, j)
print s
print(s)
k += 1
b.InsertComponent(2001, 0, 1)
......
......@@ -11,7 +11,6 @@ Created on Aug 1, 2015 by David Gobbi
import sys
import struct
import exceptions
import vtk
from vtk.test import Testing
......@@ -95,7 +94,7 @@ class TestBuffer(Testing.vtkTest):
self.assertEqual(m.strides, (5, 1))
self.assertEqual(m.ndim, 2)
# test the contents of the memoryview
self.assertEqual(m.tobytes(), bytes("helloworld"))
self.assertEqual(m.tobytes(), b"helloworld")
def testBitArray(self):
"""Test the special case of the bit array."""
......
......@@ -9,7 +9,6 @@ Updated on Feb 12, 2014 by Jean-Christophe Fillion-Robin
"""
import sys
import exceptions
import gc
import vtk
from vtk.test import Testing
......
......@@ -383,30 +383,30 @@ def TestEmptyInput(batch, batchNo=0, batchSize=0):
else:
nextRes = "No next"
# if verbose:
# print res, nextRes
# print(res, nextRes)
classesTested.add(a)
ok = TestOne(a)
if ok == 0:
if verbose:
print res + ' - Fail'
print(res + ' - Fail')
elif ok == 1:
if verbose:
print res + ' - Ok'
print(res + ' - Ok')
elif ok == 2:
if verbose:
print res + ' - no observer could be added.'
print(res + ' - no observer could be added.')
elif ok == 3:
if verbose:
print res + ' - is Abstract'
print(res + ' - is Abstract')
elif ok == 4:
if verbose:
print res + ' - No concrete implementation'
print(res + ' - No concrete implementation')
elif ok == 5:
if verbose:
print res + ' - Does not exist'
print(res + ' - Does not exist')
else:
if verbose:
print res + ' - Unknown status'
print(res + ' - Unknown status')
idx += 1
def BatchTest(vtkClasses, batchNo, batchSize):
......@@ -428,27 +428,27 @@ def BatchTest(vtkClasses, batchNo, batchSize):
total += 1
if total == batchSize:
TestEmptyInput(batch, batchNo, batchSize)
print total
print(total)
batch = set()
total = 0
idx += 1
if batch:
TestEmptyInput(batch, batchNo, batchSize)
print total
print(total)
def PrintResultSummary():
print '-' * 40
print 'Empty Input worked:', len(emptyInputWorked)
print 'Empty Input failed:', len(emptyInputFailed)
print 'Abstract classes: ', len(abstractClasses)
print 'Non-existent classes: ', len(nonexistentClasses)
print 'No concrete implementation: ', len(noConcreteImplementation)
print 'No observer could be added: ', len(noObserver)
print '-' * 40
print 'Total number of classes tested: ', len(classesTested) # , classesTested
print '-' * 40
print 'Excluded from testing: ', len(classExceptions)
print '-' * 40
print('-' * 40)
print('Empty Input worked:', len(emptyInputWorked))
print('Empty Input failed:', len(emptyInputFailed))
print('Abstract classes: ', len(abstractClasses))
print('Non-existent classes: ', len(nonexistentClasses))
print('No concrete implementation: ', len(noConcreteImplementation))
print('No observer could be added: ', len(noObserver))
print('-' * 40)
print('Total number of classes tested: ', len(classesTested)) # , classesTested
print('-' * 40)
print('Excluded from testing: ', len(classExceptions))
print('-' * 40)
def ProgramOptions():
desc = """
......@@ -489,7 +489,7 @@ def CheckPythonVersion(ver):
def main(argv=None):
if not CheckPythonVersion(0x02060000):
print 'This program requires Python 2.6 or greater.'
print('This program requires Python 2.6 or greater.')
return
global classExceptions
......@@ -507,7 +507,7 @@ def main(argv=None):
if opts.verbose:
verbose = opts.verbose
print 'CTEST_FULL_OUTPUT (Avoid ctest truncation of output)'
print('CTEST_FULL_OUTPUT (Avoid ctest truncation of output)')
# RedirectVTKMessages()
if classNames:
......
......@@ -4,7 +4,6 @@ Created on Nov 13, 2014 by David Gobbi
"""
import sys
import exceptions
import vtk
from vtk.test import Testing
......
......@@ -15,7 +15,7 @@ class TestCase2 :
self.Filter = vtk.vtkProgrammableFilter()
self.Filter.SetExecuteMethod(self.ExecMethod)
def ExecMethod(self) :
print 'execute method called'
print('execute method called')
test2 = TestCase2()
......
......@@ -21,7 +21,6 @@ Created on Aug 19, 2010 by David Gobbi
"""
import sys
import exceptions
import vtk
from vtk.test import Testing
......
......@@ -2,7 +2,6 @@
"""
import sys
import exceptions
import vtk
from vtk.test import Testing
......
......@@ -41,6 +41,11 @@ class TestMutable(Testing.vtkTest):
self.assertEqual(round(x[0],6), 0.5)
self.assertEqual(round(x[1],6), 0.5)
self.assertEqual(round(x[2],6), 0.5)
vtk.vtkPlane().IntersectWithLine(p1, p2, n, p0, t, x)
self.assertEqual(round(t,6), 0.5)
self.assertEqual(round(x[0],6), 0.5)
self.assertEqual(round(x[1],6), 0.5)
self.assertEqual(round(x[2],6), 0.5)
t.set(0)
p = vtk.vtkPlane()
p.SetOrigin(0.5, 0.0, 0.0)
......@@ -50,6 +55,11 @@ class TestMutable(Testing.vtkTest):
self.assertEqual(round(x[0],6), 0.5)
self.assertEqual(round(x[1],6), 0.5)
self.assertEqual(round(x[2],6), 0.5)
vtk.vtkPlane.IntersectWithLine(p, p1, p2, t, x)
self.assertEqual(round(t,6), 0.5)
self.assertEqual(round(x[0],6), 0.5)
self.assertEqual(round(x[1],6), 0.5)
self.assertEqual(round(x[2],6), 0.5)
if __name__ == "__main__":
Testing.main([(TestMutable, 'test')])
......@@ -3,8 +3,8 @@ import sys
try:
import numpy
except ImportError:
print "Numpy (http://numpy.scipy.org) not found.",
print "This test requires numpy!"
print("Numpy (http://numpy.scipy.org) not found.")
print("This test requires numpy!")
sys.exit(0)
import vtk
......
......@@ -14,8 +14,8 @@ from vtk.test import Testing
try:
import numpy
except ImportError:
print "Numpy (http://numpy.scipy.org) not found.",
print "This test requires numpy!"
print("Numpy (http://numpy.scipy.org) not found.",)
print("This test requires numpy!")
sys.exit(0)
from vtk.util.numpy_support import numpy_to_vtk, vtk_to_numpy
......@@ -55,7 +55,7 @@ class TestNumpySupport(Testing.vtkTest):
t_z.append(numpy.array([-2147483648, 0, 2147483647], numpy.int32))
t_z.append(numpy.array([0, 255], numpy.uint8))
t_z.append(numpy.array([0, 65535], numpy.uint16))
t_z.append(numpy.array([0, 4294967295L], numpy.uint32))
t_z.append(numpy.array([0, 4294967295], numpy.uint32))
t_z.append(numpy.array([-1.0e38, 0, 1.0e38], 'f'))
t_z.append(numpy.array([-1.0e299, 0, 1.0e299], 'd'))
......
......@@ -15,7 +15,6 @@ Created on May 7, 2011 by David Gobbi
"""
import sys
import exceptions
import vtk
from vtk.test import Testing
......
......@@ -9,7 +9,6 @@ Created on Feb 15, 2015 by David Gobbi
"""
import sys
import exceptions
import vtk
from vtk.test import Testing
......
......@@ -227,8 +227,8 @@ def TestOne(cname):
except KeyError:
# Key is not present
setParameterFail[cname] = set(['Set' + m])
except Exception, err:
print cname, 'Set' + m, err
except Exception as err:
print(cname, 'Set' + m, err)
except TypeError:
# Get...() takes 1 or more arguments.
try:
......@@ -238,8 +238,8 @@ def TestOne(cname):
except KeyError:
# Key is not present
getParameterFail[cname] = set(['Get' + m])
except Exception, err:
print cname, 'Get' + m, err
except Exception as err:
print(cname, 'Get' + m, err)
ok = setGetStatus
else:
noGetSetPairs.add(cname)
......@@ -292,32 +292,32 @@ def TestSetGet(batch, batchNo=0, batchSize=0):
else:
nextRes = "No next"
# if verbose:
# print res, nextRes
# print(res, nextRes)
classesTested.add(a)
ok = TestOne(a)
if ok == 0:
if verbose:
print res + ' - Fail'
print(res + ' - Fail')
elif ok == 1:
if verbose:
print res + ' - Ok'
print(res + ' - Ok')
elif ok == 2:
if verbose:
print res + ' - no observer could be added.'
print(res + ' - no observer could be added.')
elif ok == 3:
if verbose:
print res + ' - is Abstract'
print(res + ' - is Abstract')
elif ok == 4:
if verbose:
print res + ' - No concrete implementation'
print(res + ' - No concrete implementation')
elif ok == 5:
if verbose:
print res + ' - Does not exist'
print(res + ' - Does not exist')
else:
if verbose:
print res + ' - Unknown status'
print(res + ' - Unknown status')
idx += 1
# print nextRes
# print(nextRes)
def BatchTest(vtkClasses, batchNo, batchSize):
'''
......@@ -345,18 +345,18 @@ def BatchTest(vtkClasses, batchNo, batchSize):
TestSetGet(batch, batchNo, batchSize)
def PrintResultSummary():
print '-' * 40
print 'Set(Get()) worked:', len(setGetWorked)
print 'Set(Get()) failed:', len(setGetFailed)
print 'Abstract classes: ', len(abstractClasses)
print 'Non-existent classes: ', len(nonexistentClasses)
print 'No concrete implementation: ', len(noConcreteImplementation)
print 'No observer could be added: ', len(noObserver)
print '-' * 40
print 'Total number of classes tested: ', len(classesTested)
print '-' * 40
print 'Excluded from testing: ', len(classExceptions)
print '-' * 40
print('-' * 40)
print('Set(Get()) worked:', len(setGetWorked))
print('Set(Get()) failed:', len(setGetFailed))
print('Abstract classes: ', len(abstractClasses))
print('Non-existent classes: ', len(nonexistentClasses))
print('No concrete implementation: ', len(noConcreteImplementation))
print('No observer could be added: ', len(noObserver))
print('-' * 40)
print('Total number of classes tested: ', len(classesTested))
print('-' * 40)
print('Excluded from testing: ', len(classExceptions))
print('-' * 40)
def ProgramOptions():
desc = """
......@@ -397,7 +397,7 @@ def CheckPythonVersion(ver):
def main(argv=None):
if not CheckPythonVersion(0x02060000):
print 'This program requires Python 2.6 or greater.'
print('This program requires Python 2.6 or greater.')
return
global classExceptions
......@@ -415,7 +415,7 @@ def main(argv=None):
if opts.verbose:
verbose = opts.verbose
print 'CTEST_FULL_OUTPUT (Avoid ctest truncation of output)'
print('CTEST_FULL_OUTPUT (Avoid ctest truncation of output)')
# RedirectVTKMessages()
if classNames:
......@@ -436,7 +436,7 @@ def main(argv=None):
# for j in intervals:
# for i in range(j[0], j[1]):
# BatchTest(vtkClasses, i, 100)
# print vtkClasses
# print(vtkClasses)
PrintResultSummary()
......
......@@ -14,16 +14,15 @@ Created on May 12, 2010 by David Gobbi
"""
import sys
import exceptions
import vtk
from vtk.test import Testing
unicode_support = False
try:
unicode('hello')
unicode_support = True
except:
print "unicode not supported on this python installation"
if sys.hexversion > 0x03000000:
cedilla = 'Fran\xe7ois'
nocedilla = 'Francois'
else:
cedilla = unicode('Fran\xe7ois', 'latin1')
nocedilla = unicode('Francois')
class TestString(Testing.vtkTest):
......@@ -58,30 +57,21 @@ class TestString(Testing.vtkTest):
def testPassAndReturnUnicodeByReference(self):
"""Pass a unicode string by const reference"""
if not unicode_support:
return
a = vtk.vtkUnicodeStringArray()
a.InsertNextValue(u'Fran\xe7ois')
a.InsertNextValue(cedilla)
u = a.GetValue(0)
self.assertEqual(u, u'Fran\xe7ois')
self.assertEqual(u, cedilla)
def testPassStringAsUnicode(self):
"""Pass a string when unicode is expected. Should fail."""
if not unicode_support:
return
a = vtk.vtkUnicodeStringArray()
self.assertRaises(exceptions.TypeError,
self.assertRaises(TypeError,
a.InsertNextValue, ('Francois',))
def testPassUnicodeAsString(self):
"""Pass a unicode where a string is expected. Should succeed."""
if not unicode_support:
return
a = vtk.vtkStringArray()
a.InsertNextValue(u'Francois')
a.InsertNextValue(nocedilla)
s = a.GetValue(0)
self.assertEqual(s, 'Francois')
......
......@@ -14,7 +14,6 @@ Created on Sept 26, 2010 by David Gobbi
"""
import sys
import exceptions
import vtk
from vtk.test import Testing
......@@ -38,7 +37,7 @@ class vtkCustomObject(vtk.vtkObject):
self._ExtraObject = o
self.Modified()
else:
raise TypeError, "requires None or a vtkobject"
raise TypeError("requires None or a vtkobject")
def GetMTime(self):
"""Override a method (only works when called from Python)"""
......
......@@ -27,7 +27,7 @@ class TerminationCrashTestCase:
self.Object = vtk.vtkObject()
self.Object.AddObserver('StartEvent', self.Handler)
def Handler(self, obj, evt) :
print 'event received'
print('event received')
test = TerminationCrashTestCase()
......@@ -15,16 +15,13 @@ Created on May 12, 2010 by David Gobbi
"""
import sys
import exceptions
import vtk
from vtk.test import Testing
unicode_support = False
try:
unicode('hello')
unicode_support = True
except:
print "unicode not supported on this python installation"
if sys.hexversion > 0x03000000:
cedilla = 'Fran\xe7ois'
else:
cedilla = unicode('Fran\xe7ois', 'latin1')
class TestVariant(Testing.vtkTest):
......@@ -59,12 +56,17 @@ class TestVariant(Testing.vtkTest):
self.assertEqual(v.GetType(), vtk.VTK_STRING)
self.assertEqual(v.ToString(), 'hello')
def testBytesConstructor(self):
"""Construct from bytes"""
v = vtk.vtkVariant(b'hello')
self.assertEqual(v.GetType(), vtk.VTK_STRING)
self.assertEqual(v.ToString(), 'hello')