Commit 6f284f4f authored by David Gobbi's avatar David Gobbi Committed by Kitware Robot
Browse files

Merge topic 'python-py3k'

db62b85e Merge commit Remove_vtksys_stl into python-py3k
b7308b03 Patch CommonCore python tests for py3k.
d3eb4043 Python API compatibility for py3k.
c96458b9 Make vtk/__init__.py compatible with py3k.
e1ff8866 Fix PyVTKTemplate dict compatibility methods.
16bb32d4 Add the new py3k buffer interface.
f2aebb86 Provide py3k module initialization.
4f297425

 Remove vestigial "module" arg from python init.
...
Acked-by: Kitware Robot's avatarKitware Robot <kwrobot@kitware.com>
Reviewed-by: Ben Boeckel's avatarBen Boeckel <ben.boeckel@kitware.com>
Reviewed-by: Andrew Maclean's avatarAndrew Maclean <andrew.amaclean@gmail.com>
Merge-request: !478
parents dda6f307 db62b85e
......@@ -3,6 +3,7 @@ vtk_add_test_python(
PythonSmoke.py
TestArrays.py
TestArrayArguments.py
TestBuffer.py
TestEmptyInput.py
TestEnums.py
TestExecuteMethodFinalizeCrash.py
......
......@@ -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)
......
"""Test buffer protocol for VTK arrays
Python 2.6 introduced a new buffer protocol that can expose raw
memory as a multi-dimensional array. This is used, for example,
by numpy in order to automatically generate arrays from memory
exposed by other python extension modules.
Created on Aug 1, 2015 by David Gobbi
"""
import sys
import struct
import vtk
from vtk.test import Testing
# array types and the corresponding format
lsize = vtk.VTK_SIZEOF_LONG
idsize = vtk.VTK_SIZEOF_ID_TYPE
if idsize == 8:
idchar = 'q'
else:
idchar = 'i'
arrayType = {
'SignedChar':('b', 1), 'UnsignedChar':('B', 1),
'Short':('h', 2), 'UnsignedShort':('H', 2),
'Int':('i', 4), 'UnsignedInt':('I', 4),
'Long':('l', lsize), 'UnsignedLong':('L', lsize),
'IdType':(idchar, idsize),
'LongLong':('q', 8), 'UnsignedLongLong':('Q', 8)
}
class TestBuffer(Testing.vtkTest):
def testOneDimensionalDataArray(self):
"""Test one-dimensional data array."""
if sys.hexversion < 0x02070000:
return
for atype,ainfo in arrayType.items():
aclass = getattr(vtk, 'vtk' + atype + 'Array')
a = aclass()
a.InsertNextValue(10)
a.InsertNextValue(7)
a.InsertNextValue(85)
m = memoryview(a)
self.assertEqual(m.format, ainfo[0])
self.assertEqual(m.itemsize, ainfo[1])
self.assertEqual(m.strides, (ainfo[1],))
self.assertEqual(m.shape, (3,))
self.assertEqual(m.ndim, 1)
# test the contents of the memoryview
tp = struct.unpack(3*ainfo[0], m.tobytes())
self.assertEqual(tp, (10, 7, 85))
# now test re-creating the array from a buffer
b = aclass()
b.SetVoidArray(m, 3, True)
self.assertEqual(b.GetValue(0), 10)
self.assertEqual(b.GetValue(1), 7)
self.assertEqual(b.GetValue(2), 85)
def testTwoDimensionalDataArray(self):
"""Test data array with components."""
if sys.hexversion < 0x02070000:
return
for atype,ainfo in arrayType.items():
aclass = getattr(vtk, 'vtk' + atype + 'Array')
a = aclass()
a.SetNumberOfComponents(3)
a.InsertNextTuple((10, 7, 4))
a.InsertNextTuple((85, 8, 2))
m = memoryview(a)
self.assertEqual(m.format, ainfo[0])
self.assertEqual(m.itemsize, ainfo[1])
self.assertEqual(m.shape, (2, 3))
self.assertEqual(m.strides, (ainfo[1]*3, ainfo[1]))
self.assertEqual(m.ndim, 2)
# test the contents of the memoryview
tp = struct.unpack(6*ainfo[0], m.tobytes())
self.assertEqual(tp, (10, 7, 4, 85, 8, 2))
def testCharArray(self):
"""Test the special case of the char array."""
if sys.hexversion < 0x02070000:
return
# bit array is actually stored as a byte array
a = vtk.vtkCharArray()
a.SetNumberOfComponents(5)
a.InsertNextTupleValue("hello")
a.InsertNextTupleValue("world")
m = memoryview(a)
self.assertEqual(m.format, 'c')
self.assertEqual(m.itemsize, 1)
self.assertEqual(m.shape, (2, 5))
self.assertEqual(m.strides, (5, 1))
self.assertEqual(m.ndim, 2)
# test the contents of the memoryview
self.assertEqual(m.tobytes(), b"helloworld")
def testBitArray(self):
"""Test the special case of the bit array."""
if sys.hexversion < 0x02070000:
return
# bit array is actually stored as a byte array
a = vtk.vtkBitArray()
a.InsertNextValue(0)
a.InsertNextValue(1)
a.InsertNextValue(1)
a.InsertNextValue(0)
a.InsertNextValue(1)
m = memoryview(a)
self.assertEqual(m.format, 'B')
self.assertEqual(m.itemsize, 1)
self.assertEqual(m.shape, (1,))
# test the contents of the memoryview
self.assertEqual(ord(m.tobytes()) & 0xF8, 0x68)
if __name__ == "__main__":
Testing.main([(TestBuffer, 'test')])
......@@ -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)