Commit ae48313c authored by Andrew Maclean's avatar Andrew Maclean Committed by David Gobbi

Fixing tests for Python3.

parent 8320da24
......@@ -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!")
......@@ -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
......@@ -48,7 +53,7 @@ class TestTemplates(Testing.vtkTest):
result = a.GetValue(i)
self.assertEqual(value, result)
elif t in [str, 'str', 'unicode']:
value = unicode("hello")
value = u"hello"
a.SetValue(i, value)
result = a.GetValue(i)
self.assertEqual(value, result)
......@@ -85,7 +90,7 @@ class TestTemplates(Testing.vtkTest):
result = a.GetValue(i)
self.assertEqual(value, result)
elif t in [str, 'str', 'unicode']:
value = unicode("hello")
value = u"hello"
a.SetValue(i, value)
result = a.GetValue(i)
self.assertEqual(value, result)
......
......@@ -6,7 +6,7 @@ from vtk.test import Testing
try:
import numpy as np
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)
def GenerateCell(cellType, points):
......
......@@ -86,4 +86,4 @@ try:
# iren.Start()
except IOError:
print "Couldn't open PolyField.vtk for writing."
print("Couldn't open PolyField.vtk for writing.")
......@@ -185,4 +185,4 @@ try:
# iren.Start()
except IOError:
print "Couldn't open RGridField.vtk for writing."
print("Couldn't open RGridField.vtk for writing.")
......@@ -142,4 +142,4 @@ try:
# iren.Start()
except IOError:
print "Couldn't open combsg.vtk or SGridField.vtk for writing."
print("Couldn't open combsg.vtk or SGridField.vtk for writing.")
......@@ -141,4 +141,4 @@ try:
# iren.Start()
except IOError:
print "Couldn't open UGridField.vtk for writing."
print("Couldn't open UGridField.vtk for writing.")
......@@ -79,7 +79,7 @@ class TestClip(Testing.vtkTest):
nps = i.GetNumberOfPoints()
ps = vtk.vtkPoints()
ps.SetNumberOfPoints(nps)
for idx in xrange(nps):
for idx in range(nps):
ps.SetPoint(idx, i.GetPoint(idx))
st.SetPoints(ps)
......
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
......
......@@ -182,7 +182,7 @@ oa = pd.GetCellData().GetArray('testarray')
correctcelldata = [1, 3, 0, 2]
for i in range(4):
if oa.GetValue(i) != correctcelldata[i]:
print 'Bad celldata of test array'
print('Bad celldata of test array')
import sys
sys.exit(1)
# --- end of script --
......@@ -15,9 +15,9 @@ sg.SetExtent(0,xlim,0,ylim,0,zlim)
#a handy point iterator, calls action() on each point
def forEachPoint(xlim,ylim,zlim, action):
for z in xrange(0,zlim+1):
for y in xrange(0,ylim+1):
for x in xrange(0,xlim+1):
for z in range(0,zlim+1):
for y in range(0,ylim+1):
for x in range(0,xlim+1):
action((x,y,z))
#make geometry
......@@ -44,7 +44,7 @@ if 64 < numcells:
sg.BlankCell(64)
if 164 < numcells:
sg.BlankCell(164)
for c in xrange(180,261):
for c in range(180,261):
if c < sg.GetNumberOfCells():
sg.BlankCell(c)
......@@ -53,9 +53,9 @@ dsf.SetInputData(sg)
dsf.Update()
nviscells = dsf.GetOutput().GetNumberOfCells()
if nviscells != 356:
print "Problem"
print "Test expected 356 visible surface polygons but got", \
nviscells
print("Problem")
print("Test expected 356 visible surface polygons but got", \
nviscells)
exit(-1)
#render it so we can look at it
......
......@@ -153,9 +153,9 @@ ren3.GetActiveCamera().SetPosition(1, -1, 0)
ren3.ResetCamera()
renWin.Render()
print Actor1b.GetCenter()
print Actor2b.GetCenter()
print Actor3b.GetCenter()
print(Actor1b.GetCenter())
print(Actor2b.GetCenter())
print(Actor3b.GetCenter())
iren.Initialize()
#iren.Start()
......@@ -54,7 +54,7 @@ try:
pass
except IOError:
print "Unable to test the writer/reader."
print("Unable to test the writer/reader.")
input = ptLoad.GetOutput()
# Generate hyperstreamlines
......
......@@ -44,7 +44,7 @@ def MotionCallback (x, y):
ren1.SetDisplayPoint(x, y, z)
ren1.DisplayToWorld()
pt = ren1.GetWorldPoint()
print pt ###############
print(pt) ###############
x = pt[0]
y = pt[1]
z = pt[2]
......
......@@ -113,7 +113,7 @@ def main():
res += '\n'
print res
print(res)
if __name__ == '__main__':
main()
......@@ -43,25 +43,25 @@ class TestGlobFileNames(vtk.test.Testing.vtkTest):
if n != 93:
for i in range(0, n):
print "File:", i, " ", fileNames.GetValue(i)
print "GetNumberOfValues should return 93, returned", n
print("File:", i, " ", fileNames.GetValue(i))
print("GetNumberOfValues should return 93, returned", n)
print"Listing of ", VTK_DATA_ROOT, "/Data/headsq"
print("Listing of ", VTK_DATA_ROOT, "/Data/headsq")
directory = vtk.vtkDirectory()
directory.Open(VTK_DATA_ROOT + "/Data/headsq")
m = directory.GetNumberOfFiles()
for j in range(0, m):
print directory.GetFile(j)
print(directory.GetFile(j))
exit(1)
for i in range(0, n):
filename = fileNames.GetValue(i)
if filename != globFileNames.GetNthFileName(i):
print "mismatched filename for pattern quarter.*:", filename
print("mismatched filename for pattern quarter.*:", filename)
exit(1)
m = re.search("[\w|\W]*quarter.*", filename)
if m == None:
print "string does not match pattern quarter.*:", filename
print("string does not match pattern quarter.*:", filename)
# check that we can re-use the Glob object
......@@ -75,15 +75,15 @@ class TestGlobFileNames(vtk.test.Testing.vtkTest):
filename = fileNames.GetValue(i)
if filename != globFileNames.GetNthFileName(i):
print "mismatched filename for pattern financial.*: ", filename
print("mismatched filename for pattern financial.*: ", filename)
exit(1)
m = re.search("[\w|\W]*financial.*", filename)
if m == None:
print "string does not match pattern financial.*:", filename
print("string does not match pattern financial.*:", filename)
exit(1)
vtk.test.Testing.interact()
if __name__ == "__main__":
vtk.test.Testing.main([(TestGlobFileNames, 'test')])
\ No newline at end of file
vtk.test.Testing.main([(TestGlobFileNames, 'test')])
......@@ -47,8 +47,8 @@ class TestSortFileNames(vtk.test.Testing.vtkTest):
sortFileNames.GroupingOn()
if sortFileNames.GetNumberOfGroups() != 2:
print "GetNumberOfGroups returned incorrect number"
exit(1)
print("GetNumberOfGroups returned incorrect number")
exit(1)
fileNames1 = sortFileNames.GetNthGroup(0)
fileNames2 = sortFileNames.GetNthGroup(1)
......@@ -59,33 +59,33 @@ class TestSortFileNames(vtk.test.Testing.vtkTest):
n = fileNames1.GetNumberOfValues()
if n != numberOfFiles1:
for i in range(0, n):
print fileNames1.GetValue(i)
print "GetNumberOfValues should return", numberOfFiles1, "not", n
print(fileNames1.GetValue(i))
print("GetNumberOfValues should return", numberOfFiles1, "not", n)
exit(1)
for i in range(0, numberOfFiles1):
j = i + 1
s = VTK_DATA_ROOT + "/Data/headsq/quarter." + str(j)
if fileNames1.GetValue(i) != s:
print "string does not match pattern"
print fileNames1.GetValue(i)
print s
print("string does not match pattern")
print(fileNames1.GetValue(i))
print(s)
exit(1)
n = fileNames2.GetNumberOfValues()
if n != numberOfFiles2:
for i in range(0, n):
print fileNames2.GetValue(i)
print "GetNumberOfValues should return", numberOfFiles2, "not", n
print(fileNames2.GetValue(i))
print("GetNumberOfValues should return", numberOfFiles2, "not", n)
exit(1)
for i in range(0, numberOfFiles2):
j = i + 1
s = VTK_DATA_ROOT + "/Data/track" + str(j) + ".binary.vtk"
if fileNames2.GetValue(i) != s:
print "string does not match pattern"
print fileNames2.GetValue(i)
print s
print("string does not match pattern")
print(fileNames2.GetValue(i))
print(s)
exit(1)
vtk.test.Testing.interact()
......
......@@ -25,20 +25,20 @@ shr.SetInputData(rd2.GetOutput().GetBlock(0).GetBlock(0))
shr.Update()
ph = rdr.GetOutput().GetBlock(0).GetBlock(0).GetCell(0)
print '%d polyhedral faces' % ph.GetNumberOfFaces()
print('%d polyhedral faces' % ph.GetNumberOfFaces())
if ph.GetNumberOfFaces() != 12:
sys.exit(1)
for i in range(ph.GetNumberOfFaces()):
pg = ph.GetFace(i)
if pg.GetNumberOfEdges() != 5 or pg.GetNumberOfPoints() != 5:
print ' %d edges on face %d' % (pg.GetNumberOfEdges(), i)
print ' %d points on face %d' % (pg.GetNumberOfPoints(), i)
print(' %d edges on face %d' % (pg.GetNumberOfEdges(), i))
print(' %d points on face %d' % (pg.GetNumberOfPoints(), i))
sys.exit(1)
#for j in range(pg.GetNumberOfPoints()):
# pid = pg.GetPointId(j)
# x = [0.0,0.0,0.0]
# pg.GetPoints().GetPoint(pid, x)
# print ' p%02d: %g %g %g' % (pid, x[0], x[1], x[2]);
# print(' p%02d: %g %g %g' % (pid, x[0], x[1], x[2]))
renWin = vtkRenderWindow()
ri = vtkRenderWindowInteractor()
......
......@@ -16,5 +16,5 @@ data = rdr.GetOutput().GetBlock(0).GetBlock(0)
# Test that this dataset with NaNs gets a correct range i.e. range without NaNs
# in it.
drange = data.GetPointData().GetArray("dist_from_origin").GetRange()[:]
print "'dist_from_origin' Range: ", drange
print("'dist_from_origin' Range: ", drange)
assert (abs(drange[0] - 0.5) < 1e-3) and (abs(drange[1] - 1.118) < 1e-3)
......@@ -10,7 +10,7 @@ class TestPlot3D(Testing.vtkTest):
for name in names:
r = vtk.vtkMultiBlockPLOT3DReader()
print "Testing ", name[0], name[1]
print("Testing ", name[0], name[1])
if name[0] == "multi-ascii.xyz":
r.BinaryFileOff()
r.MultiGridOn()
......@@ -40,7 +40,7 @@ class TestPlot3D(Testing.vtkTest):
for name in names:
r = vtk.vtkMultiBlockPLOT3DReader()
print "Testing ", name[0]
print("Testing ", name[0])
r.AutoDetectFormatOn()
r.SetFileName(str(VTK_DATA_ROOT) + "/Data/" + name[0])
r.SetQFileName(str(VTK_DATA_ROOT) + "/Data/" + name[1])
......
......@@ -19,9 +19,9 @@ dim_ref = [value for value in output.GetDimensions()]
origin_ref = [value for value in output.GetOrigin()]
spacing_ref = [value for value in output.GetSpacing()]
print dim_ref
print origin_ref
print spacing_ref
print(dim_ref)
print(origin_ref)
print(spacing_ref)
writer = vtk.vtkJSONImageWriter()
writer.SetInputData(image1.GetOutput())
......@@ -31,36 +31,36 @@ writer.SetSlice(3)
writer.Write()
# Try to load JSON file and compare with dumped data
print "Writing file:", tmp_file
print("Writing file:", tmp_file)
json_file = open(tmp_file, "r")
json_obj = json.load(json_file)
json_file.close()
slice = json_obj['RTData']
if json_obj["dimensions"] != dim_ref:
print "Dimension ERROR"
print("Dimension ERROR")
sys.exit(1)
else:
print "Dimension OK"
print("Dimension OK")
if json_obj["origin"] != origin_ref:
print "Origin ERROR"
print("Origin ERROR")
sys.exit(1)
else:
print "Origin OK"
print("Origin OK")
if json_obj["spacing"] != spacing_ref:
print "Spacing ERROR"
print("Spacing ERROR")
sys.exit(1)
else:
print "Spacing OK"
print("Spacing OK")
if len(slice) == 441:
print "Slice size OK"
print("Slice size OK")
else:
print "Slice size ERROR - Size of ", str(len(slice))
print("Slice size ERROR - Size of ", str(len(slice)))
sys.exit(1)
for i in range(len(expected_first_values)):
if expected_first_values[i] != slice[i]:
sys.exit(1)
print "All good..."
print("All good...")
sys.exit()
......@@ -90,4 +90,4 @@ try:
viewer.Render()
except IOError:
print "Unable to test the writers."
print("Unable to test the writers.")
......@@ -73,4 +73,4 @@ try:
viewer.Render()
except IOError:
print "Unable to test the writer/reader."
print("Unable to test the writer/reader.")
......@@ -138,4 +138,4 @@ try:
# iren.Start()
except IOError:
print "Unable to test the writer/reader."
print("Unable to test the writer/reader.")
......@@ -129,4 +129,4 @@ try:
# iren.Start()
except IOError:
print "Unable to test the writer/reader."
print("Unable to test the writer/reader.")
......@@ -153,4 +153,4 @@ try:
pass
except IOError:
print "Unable to test the writer/reader."
print("Unable to test the writer/reader.")
......@@ -15,7 +15,7 @@ def Gather(c, arr, root):
c.Gather(vtkArr, vtkResult, root)
result = [vtkResult.GetValue(i) for i in range(vtkResult.GetNumberOfTuples())]
return [ tuple(result[i : i + count]) \
for i in xrange(0, vtkResult.GetNumberOfTuples(), count) ]
for i in range(0, vtkResult.GetNumberOfTuples(), count) ]
renWin = vtk.vtkRenderWindow()
......@@ -43,10 +43,10 @@ bounds = r.GetOutput().GetBlock(block).GetBounds()
bounds = Gather(c, bounds, root=0)
if rank == 0:
print "Reader:", r.GetClassName()
print "Bounds:"
print("Reader:", r.GetClassName())
print("Bounds:")
for i in range(size):
print bounds[i]
print(bounds[i])
c.Barrier()
aname = "StagnationEnergy"
......@@ -54,8 +54,8 @@ rng = r.GetOutput().GetBlock(block).GetPointData().GetArray(aname).GetRange(0)
rng = Gather(c, rng, root=0)
if rank == 0:
print "StagnationEnergy Ranges:"
print("StagnationEnergy Ranges:")
for i in range(size):
print rng[i]
print(rng[i])
assert rng[i][0] > 1.1 and rng[i][0] < 24.1 and \
rng[i][1] > 1.1 and rng[i][1] < 24.1
......@@ -130,4 +130,4 @@ try:
# iren.Start()
except IOError:
print "Unable to test the writers."
print("Unable to test the writers.")
......@@ -22,9 +22,9 @@ fow.SetFlush(0)
fow.SetInstance(fow)
# Prepare some test files.
f = open('emptyFile.vtk', 'wb')
f = open('emptyFile.vtk', 'wt')
f.close()
f = open('junkFile.vtk', 'wb')
f = open('junkFile.vtk', 'wt')
f.write("v9np7598mapwcawoiur-,rjpmW9MJV28nun-q38ynq-9.8ugujqvt-8n3-nv8")
f.close()
......
......@@ -80,4 +80,4 @@ try:
# iren.Start()
except IOError:
print "Unable to test the writer/reader."
print("Unable to test the writer/reader.")
......@@ -91,4 +91,4 @@ try:
# iren.Start()
except IOError:
print "Unable to test the writer/reader."
print("Unable to test the writer/reader.")
......@@ -15,7 +15,7 @@ demModel = vtk.vtkDEMReader()
demModel.SetFileName(VTK_DATA_ROOT + "/Data/SainteHelens.dem")
demModel.Update()
print demModel
print(demModel)
lo = Scale * demModel.GetElevationBounds()[0]
hi = Scale * demModel.GetElevationBounds()[1]
......
#!/usr/bin/env python
import vtk
from __future__ import print_function
import vtk
class TestStyleBase(object):
......@@ -35,7 +36,7 @@ class TestStyleBase(object):
style.UseTimersOff()
style.AutoAdjustCameraClippingRangeOn()
print "Testing: " + style.GetClassName()
print("Testing: " + style.GetClassName())
iren = style.GetInteractor()
renwin = iren.GetRenderWindow()
......@@ -54,9 +55,9 @@ class TestStyleBase(object):
for ctrl in ctrls:
for shift in shifts:
print " - ctrl: " + str(ctrl) + " shift: " + str(shift) + " " + "button: ",
print(" - ctrl: " + str(ctrl) + " shift: " + str(shift) + " " + "button: ", end=' ')
for button in buttons:
print button,
print(button, end=' ')
# First try to find a starting position where an actor
# can be picked (not mandatory for trackball modes).
# Search in increasingly big area, until we reach win size
......@@ -70,7 +71,7 @@ class TestStyleBase(object):
break
else:
if search > win_center_x or search > win_center_y:
print " (resetting camera)",
print(" (resetting camera)", end=' ')
self.ren1.ResetCamera()
search = radius
else:
......@@ -111,7 +112,7 @@ class TestStyleBase(object):
iren.SetEventInformationFlipY(x, y, ctrl, shift, '', 0, '')
eval('iren.InvokeEvent("' + button + 'ButtonReleaseEvent")')
print "."
print(".")
style.SetUseTimers(use_timers)
......
""" Test for various numpy_interface modules. Main goal is to test
parallel algorithms in vtk.numpy_interface.algorithms."""
from __future__ import print_function
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.", end=' ')
print("This test requires numpy!")
sys.exit(0)
import vtk
......@@ -29,12 +31,12 @@ def PRINT(text, values):
MPI.COMM_WORLD.Allreduce([values, MPI.DOUBLE], [res, MPI.DOUBLE], MPI.SUM)
assert numpy.abs(res) < 1E-5
if rank == 0:
print text, res
print(text, res)
def testArrays(rtData, rtData2, grad, grad2, total_npts):
" Test various parallel algorithms."
if rank == 0:
print '-----------------------'
print('-----------------------')
PRINT( "SUM ones:", algs.sum(rtData / rtData) - total_npts )
PRINT( "SUM sin:", (algs.sum(algs.sin(rtData) + 1) - numpy.sum(numpy.sin(rtData2) + 1)) / numpy.sum(numpy.sin(rtData2) + 1) )
......@@ -180,7 +182,7 @@ else:
start = rank*NUM_BLOCKS - 3
end = start + NUM_BLOCKS
for i in xrange(start, end):
for i in range(start, end):
a = vtk.vtkImageData()
a.ShallowCopy(w.GetOutput())
c.SetBlock(i, a)
......
......@@ -93,10 +93,10 @@ ren1.ResetCameraClippingRange()
renWin.Render()
print ren1.GetLastRenderingUsedDepthPeeling()
print(ren1.GetLastRenderingUsedDepthPeeling())
if (ren1.GetLastRenderingUsedDepthPeeling()):
print "depth peeling was used"
print("depth peeling was used")
else:
print "depth peeling was not used (alpha blending instead)"
print("depth peeling was not used (alpha blending instead)")
#iren.Start()
......@@ -25,8 +25,8 @@ sphere.SetThetaResolution(32)
sphere.Update()
pd = sphere.GetOutput().GetPointData()
for i in xrange(pd.GetNumberOfArrays()):
print pd.GetArray(i).GetName()
for i in range(pd.GetNumberOfArrays()):
print(pd.GetArray(i).GetName())
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(sphere.GetOutputPort())
......
......@@ -25,8 +25,8 @@ sphere.SetThetaResolution(32)
sphere.Update()
pd = sphere.GetOutput().GetPointData()
for i in xrange(pd.GetNumberOfArrays()):
print pd.GetArray(i).GetName()
for i in range(pd.GetNumberOfArrays()):
print(pd.GetArray(i).GetName())
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(sphere.GetOutputPort())
......
......@@ -30,10 +30,10 @@ renWin.SetSize(256, 256)
# render first image
renWin.Render()
if 0 == renWin.GetAlphaBitPlanes():
print "Failed to find a visual with alpha bit planes."
print(