...
 
Commits (23)
......@@ -29,10 +29,38 @@
# (To distribute this file outside of CMake, substitute the full
# License text for the above reference.)
INCLUDE(CMakeFindFrameworks)
# Use the executable's path as a hint
set(_Python_LIBRARY_PATH_HINT)
if(PYTHON_EXECUTABLE)
if(WIN32)
get_filename_component(_Python_PREFIX ${PYTHON_EXECUTABLE} PATH)
if(_Python_PREFIX)
set(_Python_LIBRARY_PATH_HINT ${_Python_PREFIX}/libs)
endif()
unset(_Python_PREFIX)
else()
get_filename_component(_Python_PREFIX ${PYTHON_EXECUTABLE} PATH)
get_filename_component(_Python_PREFIX ${_Python_PREFIX} PATH)
if(_Python_PREFIX)
set(_Python_LIBRARY_PATH_HINT ${_Python_PREFIX}/lib)
endif()
unset(_Python_PREFIX)
endif()
endif()
include(CMakeFindFrameworks)
# Search for the python framework on Apple.
CMAKE_FIND_FRAMEWORKS(Python)
# Save CMAKE_FIND_FRAMEWORK
if(DEFINED CMAKE_FIND_FRAMEWORK)
set(_PythonLibs_CMAKE_FIND_FRAMEWORK ${CMAKE_FIND_FRAMEWORK})
else()
unset(_PythonLibs_CMAKE_FIND_FRAMEWORK)
endif()
# To avoid picking up the system Python.h pre-maturely.
set(CMAKE_FIND_FRAMEWORK LAST)
set(_PythonInterp_VERSION)
if(PYTHONINTERP_FOUND)
set(_PythonInterp_VERSION ${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR})
......@@ -42,27 +70,47 @@ endif()
# the user supplied additional versions to the front.
set(_Python_VERSIONS
${Python_ADDITIONAL_VERSIONS} ${_PythonInterp_VERSION}
2.7 2.6 2.5 2.4 2.3 2.2 2.1 2.0 1.6 1.5)
2.7 2.6 2.5 3.6 3.5 3.4 3.3 3.2)
FOREACH(_CURRENT_VERSION ${_Python_VERSIONS})
STRING(REPLACE "." "" _CURRENT_VERSION_NO_DOTS ${_CURRENT_VERSION})
IF(WIN32)
FIND_LIBRARY(PYTHON_DEBUG_LIBRARY
foreach(_CURRENT_VERSION ${_Python_VERSIONS})
string(REPLACE "." "" _CURRENT_VERSION_NO_DOTS ${_CURRENT_VERSION})
if(WIN32)
find_library(PYTHON_DEBUG_LIBRARY
NAMES python${_CURRENT_VERSION_NO_DOTS}_d python
HINTS ${_Python_LIBRARY_PATH_HINT}
PATHS
[HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\${_CURRENT_VERSION}\\InstallPath]/libs/Debug
[HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\${_CURRENT_VERSION}\\InstallPath]/libs )
ENDIF()
FIND_LIBRARY(PYTHON_LIBRARY
NAMES python${_CURRENT_VERSION_NO_DOTS} python${_CURRENT_VERSION}
[HKEY_CURRENT_USER\\SOFTWARE\\Python\\PythonCore\\${_CURRENT_VERSION}\\InstallPath]/libs/Debug
[HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\${_CURRENT_VERSION}\\InstallPath]/libs
[HKEY_CURRENT_USER\\SOFTWARE\\Python\\PythonCore\\${_CURRENT_VERSION}\\InstallPath]/libs
)
endif()
set(PYTHON_FRAMEWORK_LIBRARIES)
if(Python_FRAMEWORKS AND NOT PYTHON_LIBRARY)
foreach(dir ${Python_FRAMEWORKS})
list(APPEND PYTHON_FRAMEWORK_LIBRARIES
${dir}/Versions/${_CURRENT_VERSION}/lib)
endforeach()
endif()
find_library(PYTHON_LIBRARY
NAMES
python${_CURRENT_VERSION_NO_DOTS}
python${_CURRENT_VERSION}mu
python${_CURRENT_VERSION}m
python${_CURRENT_VERSION}u
python${_CURRENT_VERSION}
HINTS
${_Python_LIBRARY_PATH_HINT}
PATHS
${PYTHON_FRAMEWORK_LIBRARIES}
[HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\${_CURRENT_VERSION}\\InstallPath]/libs
[HKEY_CURRENT_USER\\SOFTWARE\\Python\\PythonCore\\${_CURRENT_VERSION}\\InstallPath]/libs
# Avoid finding the .dll in the PATH. We want the .lib.
NO_SYSTEM_ENVIRONMENT_PATH
)
# Look for the static library in the Python config directory
FIND_LIBRARY(PYTHON_LIBRARY
find_library(PYTHON_LIBRARY
NAMES python${_CURRENT_VERSION_NO_DOTS} python${_CURRENT_VERSION}
# Avoid finding the .dll in the PATH. We want the .lib.
NO_SYSTEM_ENVIRONMENT_PATH
......@@ -70,40 +118,55 @@ FOREACH(_CURRENT_VERSION ${_Python_VERSIONS})
PATH_SUFFIXES python${_CURRENT_VERSION}/config
)
# Only look for include directory if library was found, this ensures
# that version will be matched between include dir and library
IF(PYTHON_LIBRARY)
SET(PYTHON_FRAMEWORK_INCLUDES)
IF(Python_FRAMEWORKS AND NOT PYTHON_INCLUDE_DIR)
FOREACH(dir ${Python_FRAMEWORKS})
SET(PYTHON_FRAMEWORK_INCLUDES ${PYTHON_FRAMEWORK_INCLUDES}
${dir}/Versions/${_CURRENT_VERSION}/include/python${_CURRENT_VERSION})
ENDFOREACH()
ENDIF()
# Search frameworks and registry locations first
FIND_PATH(PYTHON_INCLUDE_DIR
# Don't search for include dir until library location is known
if(PYTHON_LIBRARY)
# Use the library's install prefix as a hint
set(_Python_INCLUDE_PATH_HINT)
get_filename_component(_Python_PREFIX ${PYTHON_LIBRARY} PATH)
get_filename_component(_Python_PREFIX ${_Python_PREFIX} PATH)
if(_Python_PREFIX)
set(_Python_INCLUDE_PATH_HINT ${_Python_PREFIX}/include)
endif()
unset(_Python_PREFIX)
# Add framework directories to the search paths
set(PYTHON_FRAMEWORK_INCLUDES)
if(Python_FRAMEWORKS AND NOT PYTHON_INCLUDE_DIR)
foreach(dir ${Python_FRAMEWORKS})
list(APPEND PYTHON_FRAMEWORK_INCLUDES
${dir}/Versions/${_CURRENT_VERSION}/include)
endforeach()
endif()
find_path(PYTHON_INCLUDE_DIR
NAMES Python.h
HINTS
${_Python_INCLUDE_PATH_HINT}
PATHS
${PYTHON_FRAMEWORK_INCLUDES}
[HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\${_CURRENT_VERSION}\\InstallPath]/include
NO_DEFAULT_PATH
)
# Broaden to default paths as a second step (mainly for UNIX)
FIND_PATH(PYTHON_INCLUDE_DIR
NAMES Python.h
[HKEY_CURRENT_USER\\SOFTWARE\\Python\\PythonCore\\${_CURRENT_VERSION}\\InstallPath]/include
PATH_SUFFIXES
python${_CURRENT_VERSION}mu
python${_CURRENT_VERSION}m
python${_CURRENT_VERSION}u
python${_CURRENT_VERSION}
)
ENDIF()
endif()
# For backward compatibility, set PYTHON_INCLUDE_PATH
SET(PYTHON_INCLUDE_PATH "${PYTHON_INCLUDE_DIR}")
# For backward compatibility, set PYTHON_INCLUDE_PATH.
set(PYTHON_INCLUDE_PATH "${PYTHON_INCLUDE_DIR}")
ENDFOREACH()
if(PYTHON_LIBRARY AND PYTHON_INCLUDE_DIR)
break()
endif()
endforeach()
MARK_AS_ADVANCED(
unset(_Python_INCLUDE_PATH_HINT)
unset(_Python_LIBRARY_PATH_HINT)
mark_as_advanced(
PYTHON_DEBUG_LIBRARY
PYTHON_LIBRARY
PYTHON_INCLUDE_DIR
......@@ -138,5 +201,13 @@ SET(PYTHON_LIBRARIES "${PYTHON_LIBRARY}")
SET(PYTHON_DEBUG_LIBRARIES "${PYTHON_DEBUG_LIBRARY}")
INCLUDE(FindPackageHandleStandardArgs)
# Restore CMAKE_FIND_FRAMEWORK
if(DEFINED _PythonLibs_CMAKE_FIND_FRAMEWORK)
set(CMAKE_FIND_FRAMEWORK ${_PythonLibs_CMAKE_FIND_FRAMEWORK})
unset(_PythonLibs_CMAKE_FIND_FRAMEWORK)
else()
unset(CMAKE_FIND_FRAMEWORK)
endif()
include(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(PythonLibs DEFAULT_MSG PYTHON_LIBRARIES PYTHON_INCLUDE_DIRS)
......@@ -8,6 +8,8 @@ Usage:
--process ...
"""
from __future__ import print_function
import sys
import subprocess
import time
......@@ -25,7 +27,7 @@ if prev <= len(sys.argv):
procs = []
for cmdlist in command_lists:
print >> sys.stderr, "Executing '", " ".join(cmdlist), "'"
print("Executing '", " ".join(cmdlist), "'", file=sys.stderr)
proc = subprocess.Popen(cmdlist)
procs.append(proc)
# sleep to ensure that the process starts.
......@@ -39,6 +41,6 @@ for proc in procs:
for proc in procs:
if proc.returncode != 0:
print >> sys.stderr, "ERROR: A process exited with error. Test will fail."
print("ERROR: A process exited with error. Test will fail.", file=sys.stderr)
sys.exit(1) # error
print "All's well!"
print("All's well!")
......@@ -448,7 +448,7 @@ include(VTKParallelCMakeTests)
# Add the option for build the Python wrapping to VTK.
option(VTK_WRAP_PYTHON "Should VTK Python wrapping be built?" OFF)
set(VTK_PYTHON_VERSION 2 CACHE STRING
"Python version to use: 2, 2.x, or empty")
"Python version to use: 2, 2.x, 3, 3.x, or empty")
# Add the option for build the Python wrapping to VTK.
option(VTK_WRAP_JAVA "Should VTK Java wrapping be built?" OFF)
......
......@@ -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(repr(b) + " " + repr(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)
def testBufferShared(self):
"""Test the special buffer_shared() check that VTK provides."""
a = bytearray(b'hello')
self.assertEqual(vtk.buffer_shared(a, a), True)
b = bytearray(b'hello')
self.assertEqual(vtk.buffer_shared(a, b), False)
a = vtk.vtkFloatArray()
a.SetNumberOfComponents(3)
a.InsertNextTuple((10, 7, 4))
a.InsertNextTuple((85, 8, 2))
b = vtk.vtkFloatArray()
b.SetVoidArray(a, 6, True)
self.assertEqual(vtk.buffer_shared(a, b), True)
c = vtk.vtkFloatArray()
c.DeepCopy(a)
self.assertEqual(vtk.buffer_shared(a, c), False)
if sys.hexversion >= 0x02070000:
m = memoryview(a)
self.assertEqual(vtk.buffer_shared(a, m), True)
if sys.hexversion < 0x03000000:
m = buffer(a)
self.assertEqual(vtk.buffer_shared(a, m), True)
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: %i' % len(emptyInputWorked))
print('Empty Input failed: %i' % len(emptyInputFailed))
print('Abstract classes: %i' % len(abstractClasses))
print('Non-existent classes: %i' % len(nonexistentClasses))
print('No concrete implementation: %i' % len(noConcreteImplementation))
print('No observer could be added: %i' % 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 + ' ' + str(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 + ' ' + str(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: %i' % len(setGetWorked))
print('Set(Get()) failed: %i' % len(setGetFailed))
print('Abstract classes: %i' % len(abstractClasses))
print('Non-existent classes: %i' % len(nonexistentClasses))
print('No concrete implementation: %i' % len(noConcreteImplementation))
print('No observer could be added: %i' % len(noObserver))
print('-' * 40)
print('Total number of classes tested: %i' % len(classesTested))
print('-' * 40)
print('Excluded from testing: %i' % 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,17 +14,17 @@ 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'
eightbit = 'Francois'.encode('ascii')
else:
cedilla = unicode('Fran\xe7ois', 'latin1')
nocedilla = unicode('Francois')
eightbit = 'Francois'
class TestString(Testing.vtkTest):
def testPassByValue(self):
......@@ -58,32 +58,52 @@ 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')
def testPassStringAsUnicode(self):
"""Pass a string when unicode is expected. Should fail."""
if not unicode_support:
return
self.assertEqual(u, cedilla)
def testPassBytesAsUnicode(self):
"""Pass 8-bit string when unicode is expected. Should fail."""
a = vtk.vtkUnicodeStringArray()
self.assertRaises(exceptions.TypeError,
a.InsertNextValue, ('Francois',))
self.assertRaises(TypeError,
a.InsertNextValue, eightbit)
def testPassUnicodeAsString(self):
"""Pass a unicode where a string is expected. Should succeed."""
if not unicode_support:
return
"""Pass unicode where string is expected. Should succeed."""
a = vtk.vtkStringArray()
a.InsertNextValue(nocedilla)
s = a.GetValue(0)
self.assertEqual(s, 'Francois')
def testPassBytesAsString(self):
"""Pass 8-bit string where string is expected. Should succeed."""
a = vtk.vtkStringArray()
a.InsertNextValue(u'Francois')
a.InsertNextValue(eightbit)
s = a.GetValue(0)
self.assertEqual(s, 'Francois')
def testPassEncodedString(self):
"""Pass encoded 8-bit strings."""
a = vtk.vtkStringArray()
# latin1 encoded string will be returned as "bytes", which is
# just a normal str object in Python 2
encoded = cedilla.encode('latin1')
a.InsertNextValue(encoded)
result = a.GetValue(0)
self.assertEqual(type(result), bytes)
self.assertEqual(result, encoded)
# utf-8 encoded string will be returned as "str", which is
# actually unicode in Python 3
a = vtk.vtkStringArray()
encoded = cedilla.encode('utf-8')
a.InsertNextValue(encoded)
result = a.GetValue(0)
self.assertEqual(type(result), str)
if sys.hexversion >= 0x03000000:
self.assertEqual(result.encode('utf-8'), encoded)
else:
self.assertEqual(result, encoded)
if __name__ == "__main__":
Testing.main([(TestString, 'test')])
......@@ -14,14 +14,15 @@ Created on Sept 26, 2010 by David Gobbi
"""
import sys
import exceptions
import vtk
from vtk.test import Testing
class vtkCustomObject(vtk.vtkObject):
def __init__(self):
def __init__(self, extra=None):
"""Initialize all attributes."""
self._ExtraObject = vtk.vtkObject()
if extra is None:
extra = vtk.vtkObject()
self._ExtraObject = extra
def GetClassName(self):
"""Get the class name."""
......@@ -34,11 +35,11 @@ class vtkCustomObject(vtk.vtkObject):
def SetExtraObject(self, o):
"""Setter method."""
# make sure it is "None" or a vtkobject instance
if o == None or type(o) == type(self):
if o == None or isinstance(o, vtk.vtkObjectBase):
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)"""
......@@ -54,6 +55,13 @@ class TestSubclass(Testing.vtkTest):
o = vtkCustomObject()
self.assertEqual(o.GetClassName(), "vtkCustomObject")
def testConstructorArgs(self):
"""Test the use of constructor arguments."""
extra = vtk.vtkObject()
o = vtkCustomObject(extra)
self.assertEqual(o.GetClassName(), "vtkCustomObject")
self.assertEqual(id(o.GetExtraObject()), id(extra))
def testCallUnboundMethods(self):
"""Test calling an unbound method in an overridded method"""
o = vtkCustomObject()
......
......@@ -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')
def testUnicodeConstructor(self):
"""Construct from unicode"""
if unicode_support:
v = vtk.vtkVariant(u'hello')
self.assertEqual(v.GetType(), vtk.VTK_UNICODE_STRING)
self.assertEqual(v.ToUnicodeString(), u'hello')
v = vtk.vtkVariant(cedilla)
self.assertEqual(v.GetType(), vtk.VTK_UNICODE_STRING)
self.assertEqual(v.ToUnicodeString(), cedilla)
def testObjectConstructor(self):
"""Construct from VTK object"""
......@@ -117,27 +119,41 @@ class TestVariant(Testing.vtkTest):
def testCompare(self):
"""Use comparison operators to sort a list of vtkVariants"""
if not unicode_support:
return
l = map(vtk.vtkVariant, [1, 2.5, vtk.vtkVariant(), "0", u'hello'])
s = map(vtk.vtkVariant, [vtk.vtkVariant(), "0", 1, 2.5, u'hello'])
original = [1, 2.5, vtk.vtkVariant(), "0", cedilla]
ordered = [vtk.vtkVariant(), "0", 1, 2.5, cedilla]
l = [vtk.vtkVariant(x) for x in original]
s = [vtk.vtkVariant(x) for x in ordered]
l.sort()
self.assertEqual(l, s)
def testComparisonMethods(self):
v1 = vtk.vtkVariant(10)
v2 = vtk.vtkVariant("10")
# compare without regards to type
self.assertEqual(vtk.vtkVariantEqual(v1, v2), True)
self.assertEqual(vtk.vtkVariantLessThan(v1, v2), False)
# compare with different types being non-equivalent
self.assertEqual(vtk.vtkVariantStrictEquality(v1, v2), False)
if sys.hexversion >= 0x03000000:
self.assertEqual(vtk.vtkVariantStrictWeakOrder(v1, v2), True)
else:
# for Python 2, it worked like the cmp() function
self.assertEqual(vtk.vtkVariantStrictWeakOrder(v1, v2), -1)
def testStrictWeakOrder(self):
"""Use vtkVariantStrictWeakOrder to sort a list of vtkVariants"""
if not unicode_support:
return
l = map(vtk.vtkVariant, [1, 2.5, vtk.vtkVariant(), "0", u'hello'])
s = map(vtk.vtkVariant, [vtk.vtkVariant(), 1, 2.5, "0", u'hello'])
l.sort(vtk.vtkVariantStrictWeakOrder)
original = [1, 2.5, vtk.vtkVariant(), "0", cedilla]
ordered = [vtk.vtkVariant(), 1, 2.5, "0", cedilla]
l = [vtk.vtkVariant(x) for x in original]
s = [vtk.vtkVariant(x) for x in ordered]
l.sort(key=vtk.vtkVariantStrictWeakOrderKey)
self.assertEqual(l, s)
def testVariantExtract(self):
"""Use vtkVariantExtract"""
l = [1, '2', u'3', 4.0, vtk.vtkObject()]
s = map(vtk.vtkVariant, l)
m = map(vtk.vtkVariantExtract, s)
l = [1, '2', cedilla, 4.0, vtk.vtkObject()]
s = [vtk.vtkVariant(x) for x in l]
m = [vtk.vtkVariantExtract(x) for x in s]
self.assertEqual(l, m)
def testHash(self):
......@@ -149,9 +165,9 @@ class TestVariant(Testing.vtkTest):
self.assertEqual(d[vtk.vtkVariant('1')], 'int')
# strings and unicode have the same hash
d[vtk.vtkVariant(u's')] = 'unicode'
d[vtk.vtkVariant('s')] = 'string'
self.assertEqual(d[vtk.vtkVariant(u's')], 'string')
d[vtk.vtkVariant('s').ToString()] = 'string'
d[vtk.vtkVariant('s').ToUnicodeString()] = 'unicode'
self.assertEqual(d[vtk.vtkVariant('s').ToString()], 'unicode')
# every vtkObject is hashed by memory address
o1 = vtk.vtkIntArray()
......
......@@ -16,8 +16,8 @@ from vtk.test import Testing
try:
import weakref
except ImportError:
print "No weakref in this version of Python. Time to upgrade?"
print "Python version:", sys.version
print("No weakref in this version of Python. Time to upgrade?")
print("Python version:", sys.version)
sys.exit(0)
......@@ -34,7 +34,7 @@ class TestWeakref(Testing.vtkTest):
proxy = weakref.proxy(o)
self.assertEqual(proxy.GetClassName(), 'vtkObject')
del o
self.assertRaises(weakref.ReferenceError, getattr,
self.assertRaises(ReferenceError, getattr,
proxy, 'GetClassName')
......
......@@ -16,7 +16,7 @@ import sys
try:
import numpy.core.numeric as numeric
except ImportError:
print "WARNING: This test requires Numeric Python: http://numpy.sf.net"
print("WARNING: This test requires Numeric Python: http://numpy.sf.net")
sys.exit(0)
import os
......
......@@ -12,7 +12,12 @@ Created on May 29, 2011 by David Gobbi
"""
import sys
import exceptions
try:
# for Python2
import exceptions
except ImportError:
# In Python 3 standard exceptions were moved to builtin module.
pass
import vtk
from vtk.test import Testing
......@@ -24,6 +29,12 @@ arrayCodes = ['c', 'b', 'B', 'h', 'H',
'i', 'I', 'l', 'L', 'q', 'Q',
'f', 'd']
# create a unicode string for python 2 and python 3
if sys.hexversion >= 0x03000000:
francois = 'Fran\xe7ois'
else:
francois = unicode('Fran\xe7ois', 'latin1')
class TestTemplates(Testing.vtkTest):
def testDenseArray(self):
......@@ -47,8 +58,13 @@ class TestTemplates(Testing.vtkTest):
a.SetValue(i, value)
result = a.GetValue(i)
self.assertEqual(value, result)
elif t in [str, 'str', 'unicode']: