summaryrefslogtreecommitdiff
path: root/py
diff options
context:
space:
mode:
Diffstat (limited to 'py')
-rwxr-xr-xpy/allDemos.py2
-rwxr-xr-xpy/allTests.py18
-rw-r--r--py/config/Make.rules.mak2
-rwxr-xr-xpy/demo/Glacier2/callback/Client.py36
-rwxr-xr-xpy/demo/Glacier2/callback/Server.py6
-rwxr-xr-xpy/demo/Glacier2/callback/expect.py8
-rwxr-xr-xpy/demo/Ice/async/Client.py24
-rwxr-xr-xpy/demo/Ice/async/Server.py6
-rwxr-xr-xpy/demo/Ice/async/expect.py5
-rwxr-xr-xpy/demo/Ice/bidir/Client.py9
-rwxr-xr-xpy/demo/Ice/bidir/Server.py13
-rwxr-xr-xpy/demo/Ice/bidir/expect.py5
-rwxr-xr-xpy/demo/Ice/callback/Client.py16
-rwxr-xr-xpy/demo/Ice/callback/Server.py6
-rwxr-xr-xpy/demo/Ice/callback/expect.py4
-rwxr-xr-xpy/demo/Ice/converter/Client.py24
-rwxr-xr-xpy/demo/Ice/converter/Server.py4
-rwxr-xr-xpy/demo/Ice/converter/expect.py31
-rwxr-xr-xpy/demo/Ice/hello/Client.py34
-rwxr-xr-xpy/demo/Ice/hello/Server.py5
-rwxr-xr-xpy/demo/Ice/hello/expect.py5
-rwxr-xr-xpy/demo/Ice/latency/Client.py10
-rwxr-xr-xpy/demo/Ice/latency/Server.py2
-rwxr-xr-xpy/demo/Ice/latency/expect.py13
-rwxr-xr-xpy/demo/Ice/minimal/Server.py2
-rwxr-xr-xpy/demo/Ice/minimal/expect.py11
-rwxr-xr-xpy/demo/Ice/session/Client.py26
-rwxr-xr-xpy/demo/Ice/session/Server.py22
-rwxr-xr-xpy/demo/Ice/session/expect.py4
-rwxr-xr-xpy/demo/Ice/throughput/Client.py65
-rwxr-xr-xpy/demo/Ice/throughput/Server.py13
-rwxr-xr-xpy/demo/Ice/throughput/expect.py4
-rwxr-xr-xpy/demo/Ice/value/Client.py93
-rwxr-xr-xpy/demo/Ice/value/Printer.py4
-rwxr-xr-xpy/demo/Ice/value/Server.py2
-rwxr-xr-xpy/demo/Ice/value/expect.py4
-rwxr-xr-xpy/demo/IceGrid/simple/Client.py14
-rwxr-xr-xpy/demo/IceGrid/simple/Server.py6
-rwxr-xr-xpy/demo/IceGrid/simple/expect.py7
-rwxr-xr-xpy/demo/IceStorm/clock/Publisher.py16
-rwxr-xr-xpy/demo/IceStorm/clock/Subscriber.py124
-rwxr-xr-xpy/demo/IceStorm/clock/expect.py4
-rwxr-xr-xpy/demo/book/printer/Server.py2
-rwxr-xr-xpy/demo/book/printer/expect.py12
-rwxr-xr-xpy/demo/book/simple_filesystem/Client.py10
-rwxr-xr-xpy/demo/book/simple_filesystem/Server.py12
-rwxr-xr-xpy/demo/book/simple_filesystem/expect.py12
-rw-r--r--py/modules/IcePy/Communicator.cpp14
-rw-r--r--py/modules/IcePy/Config.h8
-rw-r--r--py/modules/IcePy/Connection.cpp77
-rw-r--r--py/modules/IcePy/ConnectionInfo.cpp34
-rw-r--r--py/modules/IcePy/Current.cpp15
-rw-r--r--py/modules/IcePy/Endpoint.cpp82
-rw-r--r--py/modules/IcePy/EndpointInfo.cpp72
-rw-r--r--py/modules/IcePy/ImplicitContext.cpp76
-rw-r--r--py/modules/IcePy/Init.cpp64
-rw-r--r--py/modules/IcePy/Logger.cpp13
-rw-r--r--py/modules/IcePy/ObjectAdapter.cpp12
-rw-r--r--py/modules/IcePy/Operation.cpp305
-rw-r--r--py/modules/IcePy/Properties.cpp17
-rw-r--r--py/modules/IcePy/Proxy.cpp123
-rw-r--r--py/modules/IcePy/Slice.cpp4
-rw-r--r--py/modules/IcePy/Types.cpp488
-rw-r--r--py/modules/IcePy/Util.cpp85
-rw-r--r--py/modules/IcePy/Util.h32
-rw-r--r--py/python/Ice.py66
-rw-r--r--py/test/Ice/adapterDeactivation/AllTests.py24
-rwxr-xr-xpy/test/Ice/adapterDeactivation/run.py7
-rw-r--r--py/test/Ice/ami/AllTests.py86
-rwxr-xr-xpy/test/Ice/ami/Client.py2
-rwxr-xr-xpy/test/Ice/ami/Server.py2
-rwxr-xr-xpy/test/Ice/ami/run.py6
-rwxr-xr-xpy/test/Ice/application/Client.py16
-rw-r--r--py/test/Ice/binding/AllTests.py62
-rwxr-xr-xpy/test/Ice/binding/run.py7
-rwxr-xr-xpy/test/Ice/blobject/Client.py10
-rw-r--r--py/test/Ice/blobject/RouterI.py8
-rwxr-xr-xpy/test/Ice/blobject/run.py12
-rw-r--r--py/test/Ice/checksum/AllTests.py9
-rwxr-xr-xpy/test/Ice/checksum/Client.py2
-rwxr-xr-xpy/test/Ice/checksum/Server.py2
-rwxr-xr-xpy/test/Ice/checksum/run.py7
-rw-r--r--py/test/Ice/custom/AllTests.py23
-rwxr-xr-xpy/test/Ice/custom/Server.py25
-rwxr-xr-xpy/test/Ice/custom/run.py7
-rw-r--r--py/test/Ice/defaultServant/AllTests.py12
-rwxr-xr-xpy/test/Ice/defaultServant/run.py12
-rw-r--r--py/test/Ice/defaultValue/AllTests.py7
-rwxr-xr-xpy/test/Ice/defaultValue/run.py11
-rw-r--r--py/test/Ice/exceptions/AllTests.py279
-rwxr-xr-xpy/test/Ice/exceptions/run.py13
-rw-r--r--py/test/Ice/facets/AllTests.py57
-rwxr-xr-xpy/test/Ice/facets/run.py7
-rw-r--r--py/test/Ice/faultTolerance/AllTests.py65
-rwxr-xr-xpy/test/Ice/faultTolerance/Server.py8
-rwxr-xr-xpy/test/Ice/faultTolerance/run.py16
-rw-r--r--py/test/Ice/info/AllTests.py22
-rwxr-xr-xpy/test/Ice/info/Client.py2
-rwxr-xr-xpy/test/Ice/info/Server.py2
-rwxr-xr-xpy/test/Ice/info/run.py7
-rw-r--r--py/test/Ice/inheritance/AllTests.py37
-rwxr-xr-xpy/test/Ice/inheritance/run.py7
-rw-r--r--py/test/Ice/location/AllTests.py78
-rwxr-xr-xpy/test/Ice/location/Client.py2
-rwxr-xr-xpy/test/Ice/location/Server.py6
-rwxr-xr-xpy/test/Ice/location/run.py7
-rw-r--r--py/test/Ice/objects/AllTests.py75
-rwxr-xr-xpy/test/Ice/objects/run.py7
-rw-r--r--py/test/Ice/operations/AllTests.py37
-rw-r--r--py/test/Ice/operations/BatchOneways.py35
-rwxr-xr-xpy/test/Ice/operations/Client.py7
-rwxr-xr-xpy/test/Ice/operations/Collocated.py2
-rw-r--r--py/test/Ice/operations/Oneways.py1
-rwxr-xr-xpy/test/Ice/operations/Server.py2
-rwxr-xr-xpy/test/Ice/operations/ServerAMD.py16
-rw-r--r--py/test/Ice/operations/TestI.py16
-rw-r--r--py/test/Ice/operations/Twoways.py120
-rw-r--r--py/test/Ice/operations/TwowaysAMI.py75
-rw-r--r--py/test/Ice/operations/TwowaysNewAMI.py75
-rwxr-xr-xpy/test/Ice/operations/run.py13
-rw-r--r--py/test/Ice/properties/Client.py12
-rwxr-xr-xpy/test/Ice/properties/run.py31
-rw-r--r--py/test/Ice/proxy/AllTests.py48
-rwxr-xr-xpy/test/Ice/proxy/Client.py2
-rwxr-xr-xpy/test/Ice/proxy/Collocated.py2
-rwxr-xr-xpy/test/Ice/proxy/Server.py2
-rwxr-xr-xpy/test/Ice/proxy/ServerAMD.py2
-rwxr-xr-xpy/test/Ice/proxy/run.py13
-rw-r--r--py/test/Ice/retry/AllTests.py42
-rwxr-xr-xpy/test/Ice/retry/Client.py2
-rwxr-xr-xpy/test/Ice/retry/Server.py2
-rwxr-xr-xpy/test/Ice/retry/run.py7
-rw-r--r--py/test/Ice/servantLocator/AllTests.py56
-rwxr-xr-xpy/test/Ice/servantLocator/run.py13
-rw-r--r--py/test/Ice/slicing/exceptions/AllTests.py182
-rwxr-xr-xpy/test/Ice/slicing/exceptions/run.py11
-rw-r--r--py/test/Ice/slicing/objects/AllTests.py283
-rwxr-xr-xpy/test/Ice/slicing/objects/run.py11
-rw-r--r--py/test/Ice/timeout/AllTests.py43
-rwxr-xr-xpy/test/Ice/timeout/Client.py2
-rwxr-xr-xpy/test/Ice/timeout/Server.py2
-rwxr-xr-xpy/test/Ice/timeout/run.py7
-rwxr-xr-xpy/test/Slice/keyword/Client.py12
-rwxr-xr-xpy/test/Slice/keyword/run.py12
-rwxr-xr-xpy/test/Slice/structure/Client.py7
-rwxr-xr-xpy/test/Slice/structure/run.py12
146 files changed, 2601 insertions, 2016 deletions
diff --git a/py/allDemos.py b/py/allDemos.py
index 1a48f615ac7..16704586aa7 100755
--- a/py/allDemos.py
+++ b/py/allDemos.py
@@ -15,7 +15,7 @@ for toplevel in [".", "..", "../..", "../../..", "../../../.."]:
if os.path.exists(os.path.join(toplevel, "demoscript")):
break
else:
- raise "can't find toplevel directory!"
+ raise RutimeError("can't find toplevel directory!")
sys.path.append(os.path.join(toplevel))
from demoscript import Util
diff --git a/py/allTests.py b/py/allTests.py
index ce7e46276d3..90707542ac5 100755
--- a/py/allTests.py
+++ b/py/allTests.py
@@ -10,15 +10,15 @@
import os, sys, re, getopt
-for toplevel in [".", "..", "../..", "../../..", "../../../.."]:
- toplevel = os.path.abspath(toplevel)
- if os.path.exists(os.path.join(toplevel, "scripts", "TestUtil.py")):
- break
-else:
- raise "can't find toplevel directory!"
-
-sys.path.append(os.path.join(toplevel))
-from scripts import *
+path = [ ".", "..", "../..", "../../..", "../../../.." ]
+head = os.path.dirname(sys.argv[0])
+if len(head) > 0:
+ path = [os.path.join(head, p) for p in path]
+path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
+if len(path) == 0:
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0], "scripts"))
+import TestUtil
#
# List of all basic tests.
diff --git a/py/config/Make.rules.mak b/py/config/Make.rules.mak
index 29ae83b3bff..b67722477e2 100644
--- a/py/config/Make.rules.mak
+++ b/py/config/Make.rules.mak
@@ -33,7 +33,7 @@ CPP_COMPILER = VC90
# Set PYTHON_HOME to your Python installation directory.
#
!if "$(PYTHON_HOME)" == ""
-PYTHON_HOME = C:\Python26
+PYTHON_HOME = C:\Python32
!endif
#
diff --git a/py/demo/Glacier2/callback/Client.py b/py/demo/Glacier2/callback/Client.py
index 93434ecee63..3ffb09dceba 100755
--- a/py/demo/Glacier2/callback/Client.py
+++ b/py/demo/Glacier2/callback/Client.py
@@ -13,7 +13,7 @@ Ice.loadSlice('Callback.ice')
import Demo
def menu():
- print """
+ print("""
usage:
t: send callback as twoway
o: send callback as oneway
@@ -25,31 +25,35 @@ s: shutdown server
r: restart the session
x: exit
?: help
-"""
+""")
class CallbackReceiverI(Demo.CallbackReceiver):
def callback(self, current=None):
- print "received callback"
+ print("received callback")
class Client(Glacier2.Application):
def createSession(self):
session = None
while True:
- print "This demo accepts any user-id / password combination."
- id = raw_input("user id: ")
- pw = raw_input("password: ")
+ print("This demo accepts any user-id / password combination.")
+ sys.stdout.write("user id: ")
+ sys.stdout.flush()
+ id = sys.stdin.readline().strip()
+ sys.stdout.write("password: ")
+ sys.stdout.flush()
+ pw = sys.stdin.readline().strip()
try:
session = self.router().createSession(id, pw)
break
- except Glacier2.PermissionDeniedException, ex:
- print "permission denied:\n" + ex.reason
- except Glacier2.CannotCreateSessionException, ex:
- print "cannot create session:\n" + ex.reason
+ except Glacier2.PermissionDeniedException as ex:
+ print("permission denied:\n" + ex.reason)
+ except Glacier2.CannotCreateSessionException as ex:
+ print("cannot create session:\n" + ex.reason)
return session
def runWithSession(self, args):
if len(args) > 1:
- print self.appName() + ": too many arguments"
+ print(self.appName() + ": too many arguments")
return 1
callbackReceiverIdent = self.createCallbackIdentity("callbackReceiver")
@@ -79,7 +83,9 @@ class Client(Glacier2.Application):
c = None
while c != 'x':
try:
- c = raw_input("==> ")
+ sys.stdout.write("==> ")
+ sys.stdout.flush()
+ c = sys.stdin.readline().strip()
if c == 't':
context = {}
context["_fwd"] = "t"
@@ -103,10 +109,10 @@ class Client(Glacier2.Application):
elif c == 'v':
if len(override) == 0:
override = "some_value"
- print "override context field is now `" + override + "'"
+ print("override context field is now `" + override + "'")
else:
override = ''
- print "override context field is empty"
+ print("override context field is empty")
elif c == 'F':
fake = not fake
@@ -125,7 +131,7 @@ class Client(Glacier2.Application):
elif c == '?':
menu()
else:
- print "unknown command `" + c + "'"
+ print("unknown command `" + c + "'")
menu()
except KeyboardInterrupt:
break
diff --git a/py/demo/Glacier2/callback/Server.py b/py/demo/Glacier2/callback/Server.py
index 1ad915750ec..0c43c3f80a6 100755
--- a/py/demo/Glacier2/callback/Server.py
+++ b/py/demo/Glacier2/callback/Server.py
@@ -15,20 +15,20 @@ import Demo
class CallbackI(Demo.Callback):
def initiateCallback(self, proxy, current=None):
- print "initiating callback to: " + current.adapter.getCommunicator().proxyToString(proxy)
+ print("initiating callback to: " + current.adapter.getCommunicator().proxyToString(proxy))
try:
proxy.callback()
except:
traceback.print_exc()
def shutdown(self, current=None):
- print "shutting down..."
+ print("shutting down...")
current.adapter.getCommunicator().shutdown()
class Server(Ice.Application):
def run(self, args):
if len(args) > 1:
- print self.appName() + ": too many arguments"
+ print(self.appName() + ": too many arguments")
return 1
adapter = self.communicator().createObjectAdapter("Callback.Server")
diff --git a/py/demo/Glacier2/callback/expect.py b/py/demo/Glacier2/callback/expect.py
index 30c5774ccb1..b36b80d1bc6 100755
--- a/py/demo/Glacier2/callback/expect.py
+++ b/py/demo/Glacier2/callback/expect.py
@@ -8,7 +8,7 @@
#
# **********************************************************************
-import sys, os
+import sys, os, signal
path = [ ".", "..", "../..", "../../..", "../../../.." ]
head = os.path.dirname(sys.argv[0])
@@ -16,10 +16,10 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "demoscript")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
-sys.path.append(path[0])
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0]))
-from demoscript import *
+from demoscript import Util
from demoscript.Glacier2 import callback
server = Util.spawn('Server.py --Ice.PrintAdapterReady')
diff --git a/py/demo/Ice/async/Client.py b/py/demo/Ice/async/Client.py
index 06a654a9613..f41fe3bc32c 100755
--- a/py/demo/Ice/async/Client.py
+++ b/py/demo/Ice/async/Client.py
@@ -19,30 +19,30 @@ class Callback:
def exception(self, ex):
if isinstance(ex, Demo.RequestCanceledException):
- print "Demo.RequestCanceledException"
+ print("Demo.RequestCanceledException")
else:
- print "sayHello AMI call failed:"
- print ex
+ print("sayHello AMI call failed:")
+ print(ex)
def menu():
- print """
+ print("""
usage:
i: send immediate greeting
d: send delayed greeting
s: shutdown server
x: exit
?: help
-"""
+""")
class Client(Ice.Application):
def run(self, args):
if len(args) > 1:
- print self.appName() + ": too many arguments"
+ print(self.appName() + ": too many arguments")
return 1
hello = Demo.HelloPrx.checkedCast(self.communicator().propertyToProxy('Hello.Proxy'))
if not hello:
- print args[0] + ": invalid proxy"
+ print(args[0] + ": invalid proxy")
return 1
menu()
@@ -50,7 +50,9 @@ class Client(Ice.Application):
c = None
while c != 'x':
try:
- c = raw_input("==> ")
+ sys.stdout.write("==> ")
+ sys.stdout.flush()
+ c = sys.stdin.readline().strip()
if c == 'i':
hello.sayHello(0)
elif c == 'd':
@@ -63,14 +65,14 @@ class Client(Ice.Application):
elif c == '?':
menu()
else:
- print "unknown command `" + c + "'"
+ print("unknown command `" + c + "'")
menu()
except EOFError:
break
except KeyboardInterrupt:
break
- except Ice.Exception, ex:
- print ex
+ except Ice.Exception as ex:
+ print(ex)
return 0
diff --git a/py/demo/Ice/async/Server.py b/py/demo/Ice/async/Server.py
index e1458be5d6f..fc011c0a1b8 100755
--- a/py/demo/Ice/async/Server.py
+++ b/py/demo/Ice/async/Server.py
@@ -37,7 +37,7 @@ class WorkQueue(threading.Thread):
self._cond.wait(self._callbacks[0].delay / 1000.0)
if not self._done:
- print "Belated Hello World!"
+ print("Belated Hello World!")
self._callbacks[0].cb.ice_response()
del self._callbacks[0]
@@ -75,7 +75,7 @@ class HelloI(Demo.Hello):
def sayHello_async(self, cb, delay, current=None):
if delay == 0:
- print "Hello World!"
+ print("Hello World!")
cb.ice_response()
else:
self._workQueue.add(cb, delay)
@@ -87,7 +87,7 @@ class HelloI(Demo.Hello):
class Server(Ice.Application):
def run(self, args):
if len(args) > 1:
- print self.appName() + ": too many arguments"
+ print(self.appName() + ": too many arguments")
return 1
self.callbackOnInterrupt()
diff --git a/py/demo/Ice/async/expect.py b/py/demo/Ice/async/expect.py
index 3eda015ea73..082b998d0c3 100755
--- a/py/demo/Ice/async/expect.py
+++ b/py/demo/Ice/async/expect.py
@@ -16,10 +16,11 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "demoscript")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
+ raise RuntimeError("can't find toplevel directory!")
sys.path.append(path[0])
+sys.path.append(os.path.join(path[0], "scripts"))
-from demoscript import *
+from demoscript import Util
from demoscript.Ice import async
server = Util.spawn('Server.py --Ice.PrintAdapterReady')
diff --git a/py/demo/Ice/bidir/Client.py b/py/demo/Ice/bidir/Client.py
index 9f54cc3a186..601b77e31f1 100755
--- a/py/demo/Ice/bidir/Client.py
+++ b/py/demo/Ice/bidir/Client.py
@@ -12,7 +12,7 @@ import os, sys, Ice
slice_dir = Ice.getSliceDir()
if not slice_dir:
- print sys.argv[0] + ': Slice directory not found.'
+ print(sys.argv[0] + ': Slice directory not found.')
sys.exit(1)
Ice.loadSlice("'-I" + slice_dir + "' Callback.ice")
@@ -20,17 +20,17 @@ import Demo
class CallbackReceiverI(Demo.CallbackReceiver):
def callback(self, num, current=None):
- print "received callback #" + str(num)
+ print("received callback #" + str(num))
class Client(Ice.Application):
def run(self, args):
if len(args) > 1:
- print self.appName() + ": too many arguments"
+ print(self.appName() + ": too many arguments")
return 1
server = Demo.CallbackSenderPrx.checkedCast(self.communicator().propertyToProxy('CallbackSender.Proxy'))
if not server:
- print self.appName() + ": invalid proxy"
+ print(self.appName() + ": invalid proxy")
return 1
adapter = self.communicator().createObjectAdapter("")
@@ -43,7 +43,6 @@ class Client(Ice.Application):
server.addClient(ident)
self.communicator().waitForShutdown()
- print "here"
return 0
app = Client()
diff --git a/py/demo/Ice/bidir/Server.py b/py/demo/Ice/bidir/Server.py
index 065585a1e8e..6b2e7fc38a4 100755
--- a/py/demo/Ice/bidir/Server.py
+++ b/py/demo/Ice/bidir/Server.py
@@ -12,7 +12,7 @@ import os, sys, traceback, threading, Ice
slice_dir = Ice.getSliceDir()
if not slice_dir:
- print sys.argv[0] + ': Slice directory not found.'
+ print(sys.argv[0] + ': Slice directory not found.')
sys.exit(1)
Ice.loadSlice("'-I" + slice_dir + "' Callback.ice")
@@ -29,7 +29,7 @@ class CallbackSenderI(Demo.CallbackSender, threading.Thread):
def destroy(self):
self._cond.acquire()
- print "destroying callback sender"
+ print("destroying callback sender")
self._destroy = True
try:
@@ -42,7 +42,7 @@ class CallbackSenderI(Demo.CallbackSender, threading.Thread):
def addClient(self, ident, current=None):
self._cond.acquire()
- print "adding client `" + self._communicator.identityToString(ident) + "'"
+ print("adding client `" + self._communicator.identityToString(ident) + "'")
client = Demo.CallbackReceiverPrx.uncheckedCast(current.con.createProxy(ident))
self._clients.append(client)
@@ -65,12 +65,12 @@ class CallbackSenderI(Demo.CallbackSender, threading.Thread):
if len(clients) > 0:
num = num + 1
-
+
for p in clients:
try:
p.callback(num)
except:
- print "removing client `" + self._communicator.identityToString(p.ice_getIdentity()) + "':"
+ print("removing client `" + self._communicator.identityToString(p.ice_getIdentity()) + "':")
traceback.print_exc()
self._cond.acquire()
@@ -79,11 +79,10 @@ class CallbackSenderI(Demo.CallbackSender, threading.Thread):
finally:
self._cond.release()
-
class Server(Ice.Application):
def run(self, args):
if len(args) > 1:
- print self.appName() + ": too many arguments"
+ print(self.appName() + ": too many arguments")
return 1
adapter = self.communicator().createObjectAdapter("Callback.Server")
diff --git a/py/demo/Ice/bidir/expect.py b/py/demo/Ice/bidir/expect.py
index e9afa31351f..9d9b23aad86 100755
--- a/py/demo/Ice/bidir/expect.py
+++ b/py/demo/Ice/bidir/expect.py
@@ -16,10 +16,11 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "demoscript")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
+ raise RuntimeError("can't find toplevel directory!")
sys.path.append(path[0])
+sys.path.append(os.path.join(path[0], "scripts"))
-from demoscript import *
+from demoscript import Util
from demoscript.Ice import bidir
server = Util.spawn('Server.py --Ice.PrintAdapterReady')
diff --git a/py/demo/Ice/callback/Client.py b/py/demo/Ice/callback/Client.py
index 6b8f2a3e403..be583c01edc 100755
--- a/py/demo/Ice/callback/Client.py
+++ b/py/demo/Ice/callback/Client.py
@@ -14,29 +14,29 @@ Ice.loadSlice('Callback.ice')
import Demo
def menu():
- print """
+ print("""
usage:
t: send callback
s: shutdown server
x: exit
?: help
-"""
+""")
class CallbackReceiverI(Demo.CallbackReceiver):
def callback(self, current=None):
- print "received callback"
+ print("received callback")
class Client(Ice.Application):
def run(self, args):
if len(args) > 1:
- print self.appName() + ": too many arguments"
+ print(self.appName() + ": too many arguments")
return 1
sender = Demo.CallbackSenderPrx.checkedCast(
self.communicator().propertyToProxy('CallbackSender.Proxy').
ice_twoway().ice_timeout(-1).ice_secure(False))
if not sender:
- print self.appName() + ": invalid proxy"
+ print(self.appName() + ": invalid proxy")
return 1
adapter = self.communicator().createObjectAdapter("Callback.Client")
@@ -51,7 +51,9 @@ class Client(Ice.Application):
c = None
while c != 'x':
try:
- c = raw_input("==> ")
+ sys.stdout.write("==> ")
+ sys.stdout.flush()
+ c = sys.stdin.readline().strip()
if c == 't':
sender.initiateCallback(receiver)
elif c == 's':
@@ -61,7 +63,7 @@ class Client(Ice.Application):
elif c == '?':
menu()
else:
- print "unknown command `" + c + "'"
+ print("unknown command `" + c + "'")
menu()
except EOFError:
break
diff --git a/py/demo/Ice/callback/Server.py b/py/demo/Ice/callback/Server.py
index f6e1cdac6aa..eeae0e9f03e 100755
--- a/py/demo/Ice/callback/Server.py
+++ b/py/demo/Ice/callback/Server.py
@@ -15,14 +15,14 @@ import Demo
class CallbackSenderI(Demo.CallbackSender):
def initiateCallback(self, proxy, current=None):
- print "initiating callback"
+ print("initiating callback")
try:
proxy.callback()
except:
traceback.print_exc()
def shutdown(self, current=None):
- print "Shutting down..."
+ print("Shutting down...")
try:
current.adapter.getCommunicator().shutdown()
except:
@@ -31,7 +31,7 @@ class CallbackSenderI(Demo.CallbackSender):
class Server(Ice.Application):
def run(self, args):
if len(args) > 1:
- print self.appName() + ": too many arguments"
+ print(self.appName() + ": too many arguments")
return 1
adapter = self.communicator().createObjectAdapter("Callback.Server")
diff --git a/py/demo/Ice/callback/expect.py b/py/demo/Ice/callback/expect.py
index d988294f9e1..ee73df8b7f4 100755
--- a/py/demo/Ice/callback/expect.py
+++ b/py/demo/Ice/callback/expect.py
@@ -16,10 +16,10 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "demoscript")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
+ raise RuntimeError("can't find toplevel directory!")
sys.path.append(path[0])
-from demoscript import *
+from demoscript import Util
from demoscript.Ice import callback
server = Util.spawn('Server.py --Ice.PrintAdapterReady')
diff --git a/py/demo/Ice/converter/Client.py b/py/demo/Ice/converter/Client.py
index 252b63a2f38..059cdaf12f3 100755
--- a/py/demo/Ice/converter/Client.py
+++ b/py/demo/Ice/converter/Client.py
@@ -14,14 +14,14 @@ Ice.loadSlice('Greet.ice')
import Demo
def menu():
- print """
+ print("""
usage:
t: send greeting with conversion
u: send greeting without conversion
s: shutdown server
x: exit
?: help
-"""
+""")
def decodeString(str):
ret = ""
@@ -39,17 +39,17 @@ communicator2 = None
class Client:
def run(self, args):
if len(args) > 1:
- print self.appName() + ": too many arguments"
+ print(self.appName() + ": too many arguments")
return 1
greet1 = Demo.GreetPrx.checkedCast(communicator1.propertyToProxy('Greet.Proxy'))
if not greet1:
- print args[0] + ": invalid proxy"
+ print(args[0] + ": invalid proxy")
return 1
greet2 = Demo.GreetPrx.checkedCast(communicator2.propertyToProxy('Greet.Proxy'))
if not greet2:
- print args[0] + ": invalid proxy"
+ print(args[0] + ": invalid proxy")
return 1
menu()
@@ -59,13 +59,15 @@ class Client:
c = None
while c != 'x':
try:
- c = raw_input("==> ")
+ sys.stdout.write("==> ")
+ sys.stdout.flush()
+ c = sys.stdin.readline().strip()
if c == 't':
ret = greet1.exchangeGreeting(greeting)
- print "Received: \"" + decodeString(ret) + "\""
+ print("Received: \"" + decodeString(ret) + "\"")
elif c == 'u':
ret = greet2.exchangeGreeting(greeting)
- print "Received: \"" + decodeString(ret) + "\""
+ print("Received: \"" + decodeString(ret) + "\"")
elif c == 's':
greet1.shutdown()
elif c == 'x':
@@ -73,14 +75,14 @@ class Client:
elif c == '?':
menu()
else:
- print "unknown command `" + c + "'"
+ print("unknown command `" + c + "'")
menu()
except KeyboardInterrupt:
break
except EOFError:
break
- except Ice.Exception, ex:
- print ex
+ except Ice.Exception as ex:
+ print(ex)
return 0
diff --git a/py/demo/Ice/converter/Server.py b/py/demo/Ice/converter/Server.py
index f105e8b4dfa..160ea560484 100755
--- a/py/demo/Ice/converter/Server.py
+++ b/py/demo/Ice/converter/Server.py
@@ -26,7 +26,7 @@ def decodeString(str):
class GreatI(Demo.Greet):
def exchangeGreeting(self, msg, current=None):
- print "Received (UTF-8): \"" + decodeString(msg) + "\""
+ print("Received (UTF-8): \"" + decodeString(msg) + "\"")
return "Bonne journ\303\251e"
def shutdown(self, current=None):
@@ -35,7 +35,7 @@ class GreatI(Demo.Greet):
class Server(Ice.Application):
def run(self, args):
if len(args) > 1:
- print self.appName() + ": too many arguments"
+ print(self.appName() + ": too many arguments")
return 1
adapter = self.communicator().createObjectAdapter("Greet")
diff --git a/py/demo/Ice/converter/expect.py b/py/demo/Ice/converter/expect.py
index 77372ec3d25..9b7531c3872 100755
--- a/py/demo/Ice/converter/expect.py
+++ b/py/demo/Ice/converter/expect.py
@@ -16,28 +16,37 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "demoscript")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
+ raise RuntimeError("can't find toplevel directory!")
sys.path.append(path[0])
-from demoscript import *
+from demoscript import Util
server = Util.spawn('Server.py --Ice.PrintAdapterReady')
server.expect('.* ready')
client = Util.spawn('Client.py')
client.expect('.*==>')
-print "testing with conversion...",
+sys.stdout.write("testing with conversion... ")
sys.stdout.flush()
client.sendline('u')
-server.expect('Received \\(UTF-8\\): "Bonne journ\\\\351e"')
-client.expect('Received: "Bonne journ\\\\303\\\\251e"')
-print "ok"
-
-print "testing without conversion...",
+if sys.version_info[0] == 2:
+ server.expect('Received \\(UTF-8\\): "Bonne journ\\\\351e"')
+ client.expect('Received: "Bonne journ\\\\303\\\\251e"')
+else:
+ server.expect('Received \\(UTF-8\\): "Bonne journ\\\\o351e"')
+ client.expect('Received: "Bonne journ\\\\o303\\\\o251e"')
+print("ok")
+
+sys.stdout.write("testing without conversion... ")
+sys.stdout.flush()
client.sendline('t')
-server.expect('Received \\(UTF-8\\): "Bonne journ\\\\303\\\\251e"')
-client.expect('Received: "Bonne journ\\\\351e"')
-print "ok"
+if sys.version_info[0] == 2:
+ server.expect('Received \\(UTF-8\\): "Bonne journ\\\\303\\\\251e"')
+ client.expect('Received: "Bonne journ\\\\351e"')
+else:
+ server.expect('Received \\(UTF-8\\): "Bonne journ\\\\o303\\\\o251e"')
+ client.expect('Received: "Bonne journ\\\\o351e"')
+print("ok")
client.sendline('s')
server.waitTestSuccess()
diff --git a/py/demo/Ice/hello/Client.py b/py/demo/Ice/hello/Client.py
index 8134c57a069..04ab665220c 100755
--- a/py/demo/Ice/hello/Client.py
+++ b/py/demo/Ice/hello/Client.py
@@ -14,7 +14,7 @@ Ice.loadSlice('Hello.ice')
import Demo
def menu():
- print """
+ print("""
usage:
t: send greeting as twoway
o: send greeting as oneway
@@ -28,18 +28,18 @@ S: switch secure mode on/off
s: shutdown server
x: exit
?: help
-"""
+""")
class Client(Ice.Application):
def run(self, args):
if len(args) > 1:
- print self.appName() + ": too many arguments"
+ print(self.appName() + ": too many arguments")
return 1
twoway = Demo.HelloPrx.checkedCast(\
self.communicator().propertyToProxy('Hello.Proxy').ice_twoway().ice_timeout(-1).ice_secure(False))
if not twoway:
- print args[0] + ": invalid proxy"
+ print(args[0] + ": invalid proxy")
return 1
oneway = Demo.HelloPrx.uncheckedCast(twoway.ice_oneway())
@@ -56,7 +56,9 @@ class Client(Ice.Application):
c = None
while c != 'x':
try:
- c = raw_input("==> ")
+ sys.stdout.write("==> ")
+ sys.stdout.flush()
+ c = sys.stdin.readline().strip()
if c == 't':
twoway.sayHello(delay)
elif c == 'o':
@@ -65,12 +67,12 @@ class Client(Ice.Application):
batchOneway.sayHello(delay)
elif c == 'd':
if secure:
- print "secure datagrams are not supported"
+ print("secure datagrams are not supported")
else:
datagram.sayHello(delay)
elif c == 'D':
if secure:
- print "secure datagrams are not supported"
+ print("secure datagrams are not supported")
else:
batchDatagram.sayHello(delay)
elif c == 'f':
@@ -86,9 +88,9 @@ class Client(Ice.Application):
batchOneway = Demo.HelloPrx.uncheckedCast(batchOneway.ice_timeout(timeout))
if timeout == -1:
- print "timeout is now switched off"
+ print("timeout is now switched off")
else:
- print "timeout is now set to 2000ms"
+ print("timeout is now set to 2000ms")
elif c == 'P':
if delay == 0:
delay = 2500
@@ -96,9 +98,9 @@ class Client(Ice.Application):
delay = 0
if delay == 0:
- print "server delay is now deactivated"
+ print("server delay is now deactivated")
else:
- print "server delay is now set to 2500ms"
+ print("server delay is now set to 2500ms")
elif c == 'S':
secure = not secure
@@ -109,9 +111,9 @@ class Client(Ice.Application):
batchDatagram = Demo.HelloPrx.uncheckedCast(batchDatagram.ice_secure(secure))
if secure:
- print "secure mode is now on"
+ print("secure mode is now on")
else:
- print "secure mode is now off"
+ print("secure mode is now off")
elif c == 's':
twoway.shutdown()
elif c == 'x':
@@ -119,14 +121,14 @@ class Client(Ice.Application):
elif c == '?':
menu()
else:
- print "unknown command `" + c + "'"
+ print("unknown command `" + c + "'")
menu()
except KeyboardInterrupt:
break
except EOFError:
break
- except Ice.Exception, ex:
- print ex
+ except Ice.Exception as ex:
+ print(ex)
return 0
diff --git a/py/demo/Ice/hello/Server.py b/py/demo/Ice/hello/Server.py
index 14a1afbd054..e03d6f724a8 100755
--- a/py/demo/Ice/hello/Server.py
+++ b/py/demo/Ice/hello/Server.py
@@ -11,13 +11,14 @@
import sys, traceback, time, Ice
Ice.loadSlice('Hello.ice')
+Ice.updateModules()
import Demo
class HelloI(Demo.Hello):
def sayHello(self, delay, current=None):
if delay != 0:
time.sleep(delay / 1000.0)
- print "Hello World!"
+ print("Hello World!")
def shutdown(self, current=None):
current.adapter.getCommunicator().shutdown()
@@ -25,7 +26,7 @@ class HelloI(Demo.Hello):
class Server(Ice.Application):
def run(self, args):
if len(args) > 1:
- print self.appName() + ": too many arguments"
+ print(self.appName() + ": too many arguments")
return 1
adapter = self.communicator().createObjectAdapter("Hello")
diff --git a/py/demo/Ice/hello/expect.py b/py/demo/Ice/hello/expect.py
index 2538d9c20a9..161ee904a6e 100755
--- a/py/demo/Ice/hello/expect.py
+++ b/py/demo/Ice/hello/expect.py
@@ -16,10 +16,11 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "demoscript")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
+ raise RuntimeError("can't find toplevel directory!")
sys.path.append(path[0])
+sys.path.append(os.path.join(path[0], "scripts"))
-from demoscript import *
+from demoscript import Util
from demoscript.Ice import hello
server = Util.spawn('Server.py --Ice.PrintAdapterReady --Ice.Warn.Connections=0')
diff --git a/py/demo/Ice/latency/Client.py b/py/demo/Ice/latency/Client.py
index 35201fcffd4..6cdc4a69234 100755
--- a/py/demo/Ice/latency/Client.py
+++ b/py/demo/Ice/latency/Client.py
@@ -16,19 +16,19 @@ import Demo
class Client(Ice.Application):
def run(self, args):
if len(args) > 1:
- print self.appName() + ": too many arguments"
+ print(self.appName() + ": too many arguments")
return 1
ping = Demo.PingPrx.checkedCast(self.communicator().propertyToProxy('Ping.Proxy'))
if not ping:
- print "invalid proxy"
+ print("invalid proxy")
return 1
# Initial ping to setup the connection.
ping.ice_ping();
repetitions = 100000
- print "pinging server " + str(repetitions) + " times (this may take a while)"
+ print("pinging server " + str(repetitions) + " times (this may take a while)")
tsec = time.time()
@@ -40,8 +40,8 @@ class Client(Ice.Application):
tsec = time.time() - tsec
tmsec = tsec * 1000.0
- print "time for %d pings: %.3fms" % (repetitions, tmsec)
- print "time per ping: %.3fms" % (tmsec / repetitions)
+ print("time for %d pings: %.3fms" % (repetitions, tmsec))
+ print("time per ping: %.3fms" % (tmsec / repetitions))
return 0
diff --git a/py/demo/Ice/latency/Server.py b/py/demo/Ice/latency/Server.py
index 768c78f3ed2..0ae8bb33f12 100755
--- a/py/demo/Ice/latency/Server.py
+++ b/py/demo/Ice/latency/Server.py
@@ -16,7 +16,7 @@ import Demo
class Server(Ice.Application):
def run(self, args):
if len(args) > 1:
- print self.appName() + ": too many arguments"
+ print(self.appName() + ": too many arguments")
return 1
adapter = self.communicator().createObjectAdapter("Latency")
diff --git a/py/demo/Ice/latency/expect.py b/py/demo/Ice/latency/expect.py
index 198b7634eda..d71e67602b1 100755
--- a/py/demo/Ice/latency/expect.py
+++ b/py/demo/Ice/latency/expect.py
@@ -8,7 +8,7 @@
#
# **********************************************************************
-import sys, os
+import sys, os, signal
path = [ ".", "..", "../..", "../../..", "../../../.." ]
head = os.path.dirname(sys.argv[0])
@@ -16,22 +16,21 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "demoscript")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
+ raise RuntimeError("can't find toplevel directory!")
sys.path.append(path[0])
-from demoscript import *
+from demoscript import Util
server = Util.spawn('Server.py --Ice.PrintAdapterReady')
server.expect('.* ready')
-print "testing ping... ",
+sys.stdout.write("testing ping... ")
sys.stdout.flush()
client = Util.spawn('Client.py')
client.waitTestSuccess(timeout=100)
-print "ok"
+print("ok")
-import signal
server.kill(signal.SIGINT)
server.waitTestSuccess()
-print client.before
+print(client.before)
diff --git a/py/demo/Ice/minimal/Server.py b/py/demo/Ice/minimal/Server.py
index 048d4f6a155..926c838d4cd 100755
--- a/py/demo/Ice/minimal/Server.py
+++ b/py/demo/Ice/minimal/Server.py
@@ -15,7 +15,7 @@ import Demo
class HelloI(Demo.Hello):
def sayHello(self, current=None):
- print "Hello World!"
+ print("Hello World!")
try:
communicator = Ice.initialize(sys.argv)
diff --git a/py/demo/Ice/minimal/expect.py b/py/demo/Ice/minimal/expect.py
index e0369ef3d23..63de5d4a87c 100755
--- a/py/demo/Ice/minimal/expect.py
+++ b/py/demo/Ice/minimal/expect.py
@@ -8,7 +8,7 @@
#
# **********************************************************************
-import sys, os
+import sys, os, signal
path = [ ".", "..", "../..", "../../..", "../../../.." ]
head = os.path.dirname(sys.argv[0])
@@ -16,21 +16,20 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "demoscript")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
+ raise RuntimeError("can't find toplevel directory!")
sys.path.append(path[0])
-from demoscript import *
+from demoscript import Util
server = Util.spawn('Server.py --Ice.PrintAdapterReady')
server.expect('.* ready')
-print "testing...",
+sys.stdout.write("testing... ")
sys.stdout.flush()
client = Util.spawn('Client.py')
client.waitTestSuccess()
server.expect('Hello World!')
-print "ok"
+print("ok")
-import signal
server.kill(signal.SIGTERM)
server.waitTestSuccess(-signal.SIGTERM)
diff --git a/py/demo/Ice/session/Client.py b/py/demo/Ice/session/Client.py
index 9076bb1c82f..9fcd9eaa163 100755
--- a/py/demo/Ice/session/Client.py
+++ b/py/demo/Ice/session/Client.py
@@ -30,7 +30,7 @@ class SessionRefreshThread(threading.Thread):
if not self._terminated:
try:
self._session.refresh()
- except Ice.LocalException, ex:
+ except Ice.LocalException as ex:
self._logger.warning("SessionRefreshThread: " + str(ex))
self._terminated = True
finally:
@@ -47,18 +47,20 @@ class SessionRefreshThread(threading.Thread):
class Client(Ice.Application):
def run(self, args):
if len(args) > 1:
- print self.appName() + ": too many arguments"
+ print(self.appName() + ": too many arguments")
return 1
while True:
- name = raw_input("Please enter your name ==> ").strip()
+ sys.stdout.write("Please enter your name ==> ")
+ sys.stdout.flush()
+ name = sys.stdin.readline().strip()
if len(name) != 0:
break
base = self.communicator().propertyToProxy('SessionFactory.Proxy')
factory = Demo.SessionFactoryPrx.checkedCast(base)
if not factory:
- print args[0] + ": invalid proxy"
+ print(args[0] + ": invalid proxy")
return 1
session = factory.create(name)
@@ -74,7 +76,9 @@ class Client(Ice.Application):
shutdown = False
while True:
try:
- c = raw_input("==> ")
+ sys.stdout.write("==> ")
+ sys.stdout.flush()
+ c = sys.stdin.readline().strip()
s = str(c)
if s.isdigit():
index = int(s)
@@ -82,11 +86,11 @@ class Client(Ice.Application):
hello = hellos[index]
hello.sayHello()
else:
- print "Index is too high. " + str(len(hellos)) + " hello objects exist so far.\n" +\
- "Use `c' to create a new hello object."
+ print("Index is too high. " + str(len(hellos)) + " hello objects exist so far.\n" +\
+ "Use `c' to create a new hello object.")
elif c == 'c':
hellos.append(session.createHello())
- print "Created hello object",len(hellos) - 1
+ print("Created hello object",len(hellos) - 1)
elif c == 's':
destroy = False
shutdown = True
@@ -99,7 +103,7 @@ class Client(Ice.Application):
elif c == '?':
self.menu()
else:
- print "unknown command `" + c + "'"
+ print("unknown command `" + c + "'")
self.menu()
except EOFError:
break
@@ -131,7 +135,7 @@ class Client(Ice.Application):
return 0
def menu(self):
- print """
+ print("""
usage:
c: create a new per-client hello object
0-9: send a greeting to a hello object
@@ -139,7 +143,7 @@ s: shutdown the server and exit
x: exit
t: exit without destroying the session
?: help
-"""
+""")
app = Client()
sys.exit(app.main(sys.argv, "config.client"))
diff --git a/py/demo/Ice/session/Server.py b/py/demo/Ice/session/Server.py
index 3ed1642b3a4..610778c90f4 100755
--- a/py/demo/Ice/session/Server.py
+++ b/py/demo/Ice/session/Server.py
@@ -19,8 +19,8 @@ class HelloI(Demo.Hello):
self._id = id
def sayHello(self, c):
- print "Hello object #" + str(self._id) + " for session `" + self._name + "' says:\n" + \
- "Hello " + self._name + "!"
+ print("Hello object #" + str(self._id) + " for session `" + self._name + "' says:\n" + \
+ "Hello " + self._name + "!")
class SessionI(Demo.Session):
def __init__(self, name):
@@ -31,8 +31,8 @@ class SessionI(Demo.Session):
self._nextId = 0 # The id of the next hello object. This is used for tracing purposes.
self._objs = [] # List of per-client allocated Hello objects.
- print "The session " + self._name + " is now created."
-
+ print("The session " + self._name + " is now created.")
+
def createHello(self, c):
self._lock.acquire()
try:
@@ -63,19 +63,19 @@ class SessionI(Demo.Session):
return self._name
finally:
self._lock.release()
-
+
def destroy(self, c):
self._lock.acquire()
try:
if self._destroy:
raise Ice.ObjectNotExistException()
self._destroy = True
- print "The session " + self._name + " is now destroyed."
+ print("The session " + self._name + " is now destroyed.")
try:
c.adapter.remove(c.id)
for p in self._objs:
c.adapter.remove(p.ice_getIdentity())
- except Ice.ObjectAdapterDeactivatedException, ex:
+ except Ice.ObjectAdapterDeactivatedException as ex:
# This method is called on shutdown of the server, in
# which case this exception is expected.
pass
@@ -91,7 +91,7 @@ class SessionI(Demo.Session):
return self._timestamp
finally:
self._lock.release()
-
+
class SessionProxyPair:
def __init__(self, p, s):
self.proxy = p
@@ -121,7 +121,7 @@ class ReapThread(threading.Thread):
if (time.time() - p.session.timestamp()) > self._timeout:
name = p.proxy.getName()
p.proxy.destroy()
- print "The session " + name + " has timed out."
+ print("The session " + name + " has timed out.")
self._sessions.remove(p)
except Ice.ObjectNotExistException:
self._sessions.remove(p)
@@ -161,13 +161,13 @@ class SessionFactoryI(Demo.SessionFactory):
self._lock.release()
def shutdown(self, c):
- print "Shutting down..."
+ print("Shutting down...")
c.adapter.getCommunicator().shutdown()
class Server(Ice.Application):
def run(self, args):
if len(args) > 1:
- print self.appName() + ": too many arguments"
+ print(self.appName() + ": too many arguments")
return 1
adapter = self.communicator().createObjectAdapter("SessionFactory")
diff --git a/py/demo/Ice/session/expect.py b/py/demo/Ice/session/expect.py
index f88d344c60a..22760d11d5a 100755
--- a/py/demo/Ice/session/expect.py
+++ b/py/demo/Ice/session/expect.py
@@ -16,10 +16,10 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "demoscript")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
+ raise RuntimeError("can't find toplevel directory!")
sys.path.append(path[0])
-from demoscript import *
+from demoscript import Util
from demoscript.Ice import session
server = Util.spawn('Server.py --Ice.PrintAdapterReady')
diff --git a/py/demo/Ice/throughput/Client.py b/py/demo/Ice/throughput/Client.py
index c90d78cd282..97fe7aa6b21 100755
--- a/py/demo/Ice/throughput/Client.py
+++ b/py/demo/Ice/throughput/Client.py
@@ -14,7 +14,7 @@ Ice.loadSlice('Throughput.ice')
import Demo
def menu():
- print """
+ print("""
usage:
toggle type of data to send:
@@ -33,24 +33,27 @@ other commands:
s: shutdown server
x: exit
?: help
-"""
+""")
class Client(Ice.Application):
def run(self, args):
if len(args) > 1:
- print self.appName() + ": too many arguments"
+ print(self.appName() + ": too many arguments")
return 1
throughput = Demo.ThroughputPrx.checkedCast(self.communicator().propertyToProxy('Throughput.Proxy'))
if not throughput:
- print args[0] + ": invalid proxy"
+ print(args[0] + ": invalid proxy")
return 1
throughputOneway = Demo.ThroughputPrx.uncheckedCast(throughput.ice_oneway())
- bytes = []
- bytes[0:Demo.ByteSeqSize] = range(0, Demo.ByteSeqSize)
- bytes = ['\x00' for x in bytes]
- byteSeq = ''.join(bytes)
+ if sys.version_info[0] == 2:
+ b = []
+ b[0:Demo.ByteSeqSize] = range(0, Demo.ByteSeqSize)
+ b = ['\x00' for x in b]
+ byteSeq = ''.join(b)
+ else:
+ byteSeq = bytes([0 for x in range(0, Demo.ByteSeqSize)])
stringSeq = []
stringSeq[0:Demo.StringSeqSize] = range(0, Demo.StringSeqSize)
@@ -86,7 +89,7 @@ class Client(Ice.Application):
emptyStructs = [ Demo.StringDouble() ]
emptyFixed = [ Demo.Fixed() ]
- print "warming up the server...",
+ print("warming up the server...",)
sys.stdout.flush()
for i in range(0, 10000):
throughput.sendByteSeq(emptyBytes)
@@ -106,7 +109,7 @@ class Client(Ice.Application):
throughput.endWarmup()
- print "ok"
+ print("ok")
else:
throughput.ice_ping() # Initial ping to setup the connection.
@@ -118,46 +121,48 @@ class Client(Ice.Application):
c = None
while c != 'x':
try:
- c = raw_input("==> ")
+ sys.stdout.write("==> ")
+ sys.stdout.flush()
+ c = sys.stdin.readline().strip()
repetitions = 100
if c == '1' or c == '2' or c == '3' or c == '4':
currentType = c
if c == '1':
- print "using byte sequences"
+ print("using byte sequences")
seqSize = Demo.ByteSeqSize
elif c == '2':
- print "using string sequences"
+ print("using string sequences")
seqSize = Demo.StringSeqSize
elif c == '3':
- print "using variable-length struct sequences"
+ print("using variable-length struct sequences")
seqSize = Demo.StringDoubleSeqSize
elif c == '4':
- print "using fixed-length struct sequences"
+ print("using fixed-length struct sequences")
seqSize = Demo.FixedSeqSize
elif c == 't' or c == 'o' or c == 'r' or c == 'e':
if c == 't' or c == 'o':
- print "sending",
+ sys.stdout.write("sending ")
elif c == 'r':
- print "receiving",
+ sys.stdout.write("receiving ")
elif c == 'e':
- print "sending and receiving",
+ sys.stdout.write("sending and receiving ")
- print repetitions,
+ sys.stdout.write(str(repetitions) + " ")
if currentType == '1':
- print "byte",
+ sys.stdout.write("byte ")
elif currentType == '2':
- print "string",
+ sys.stdout.write("string ")
elif currentType == '3':
- print "variable-length struct",
+ sys.stdout.write("variable-length struct ")
elif currentType == '4':
- print "fixed-length struct",
-
+ sys.stdout.write("fixed-length struct ")
+
if c == 'o':
- print "sequences of size %d as oneway..." % seqSize
+ print("sequences of size %d as oneway..." % seqSize)
else:
- print "sequences of size %d..." % seqSize
+ print("sequences of size %d..." % seqSize)
tsec = time.time()
@@ -201,8 +206,8 @@ class Client(Ice.Application):
tsec = time.time() - tsec
tmsec = tsec * 1000.0
- print "time for %d sequences: %.3fms" % (repetitions, tmsec)
- print "time per sequence: %.3fms" % (tmsec / repetitions)
+ print("time for %d sequences: %.3fms" % (repetitions, tmsec))
+ print("time per sequence: %.3fms" % (tmsec / repetitions))
wireSize = 0
if currentType == '1':
wireSize = 1
@@ -216,7 +221,7 @@ class Client(Ice.Application):
mbit = repetitions * seqSize * wireSize * 8.0 / tsec / 1000000.0
if c == 'e':
mbit = mbit * 2
- print "throughput: %.3fMbps" % mbit
+ print("throughput: %.3fMbps" % mbit)
elif c == 's':
throughput.shutdown()
elif c == 'x':
@@ -224,7 +229,7 @@ class Client(Ice.Application):
elif c == '?':
menu()
else:
- print "unknown command `" + c + "'"
+ print("unknown command `" + c + "'")
menu()
except EOFError:
break
diff --git a/py/demo/Ice/throughput/Server.py b/py/demo/Ice/throughput/Server.py
index 3d1eb775d7c..ff51e35cc26 100755
--- a/py/demo/Ice/throughput/Server.py
+++ b/py/demo/Ice/throughput/Server.py
@@ -17,10 +17,13 @@ class ThroughputI(Demo.Throughput):
def __init__(self):
warmup = False
- bytes = []
- bytes[0:Demo.ByteSeqSize] = range(0, Demo.ByteSeqSize)
- bytes = ['\x00' for x in bytes]
- self.byteSeq = ''.join(bytes)
+ if sys.version_info[0] == 2:
+ b = []
+ b[0:Demo.ByteSeqSize] = range(0, Demo.ByteSeqSize)
+ b = ['\x00' for x in b]
+ self.byteSeq = ''.join(b)
+ else:
+ self.byteSeq = bytes([0 for x in range(0, Demo.ByteSeqSize)])
self.stringSeq = []
self.stringSeq[0:Demo.StringSeqSize] = range(0, Demo.StringSeqSize)
@@ -105,7 +108,7 @@ class ThroughputI(Demo.Throughput):
class Server(Ice.Application):
def run(self, args):
if len(args) > 1:
- print self.appName() + ": too many arguments"
+ print(self.appName() + ": too many arguments")
return 1
adapter = self.communicator().createObjectAdapter("Throughput")
diff --git a/py/demo/Ice/throughput/expect.py b/py/demo/Ice/throughput/expect.py
index d6892753860..6f1c57aa68d 100755
--- a/py/demo/Ice/throughput/expect.py
+++ b/py/demo/Ice/throughput/expect.py
@@ -16,10 +16,10 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "demoscript")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
+ raise RuntimeError("can't find toplevel directory!")
sys.path.append(path[0])
-from demoscript import *
+from demoscript import Util
from demoscript.Ice import throughput
server = Util.spawn('Server.py --Ice.PrintAdapterReady')
diff --git a/py/demo/Ice/value/Client.py b/py/demo/Ice/value/Client.py
index 4ab969673d5..88720ea82b5 100755
--- a/py/demo/Ice/value/Client.py
+++ b/py/demo/Ice/value/Client.py
@@ -30,124 +30,127 @@ class ObjectFactory(Ice.ObjectFactory):
class Client(Ice.Application):
def run(self, args):
if len(args) > 1:
- print self.appName() + ": too many arguments"
+ print(self.appName() + ": too many arguments")
return 1
initial = Demo.InitialPrx.checkedCast(self.communicator().propertyToProxy('Initial.Proxy'))
if not initial:
- print args[0] + ": invalid proxy"
+ print(args[0] + ": invalid proxy")
return 1
- print '\n'\
+ print('\n'\
"Let's first transfer a simple object, for a class without\n"\
"operations, and print its contents. No factory is required\n"\
"for this.\n"\
- "[press enter]"
- raw_input()
+ "[press enter]")
+ sys.stdin.readline()
simple = initial.getSimple()
- print "==> " + simple.message
+ print("==> " + simple.message)
- print '\n'\
+ print('\n'\
"Yes, this worked. Now let's try to transfer an object for a class\n"\
"with operations as type ::Demo::Printer, without installing a factory\n"\
"first. This should give us a `no factory' exception.\n"\
- "[press enter]"
- raw_input()
+ "[press enter]")
+ sys.stdin.readline()
try:
printer, printerProxy = initial.getPrinter()
- print args[0] + ": Did not get the expected NoObjectFactoryException!"
+ print(args[0] + ": Did not get the expected NoObjectFactoryException!")
sys.exit(false)
- except Ice.NoObjectFactoryException, ex:
- print "==>", ex
+ except Ice.NoObjectFactoryException as ex:
+ print("==>", ex)
- print '\n'\
+ print('\n'\
"Yep, that's what we expected. Now let's try again, but with\n"\
"installing an appropriate factory first. If successful, we print\n"\
"the object's content.\n"\
- "[press enter]"
- raw_input()
+ "[press enter]")
+ sys.stdin.readline()
factory = ObjectFactory()
self.communicator().addObjectFactory(factory, Demo.Printer.ice_staticId())
printer, printerProxy = initial.getPrinter()
- print "==> " + printer.message
+ print("==> " + printer.message)
- print '\n'\
+ print('\n'\
"Cool, it worked! Let's try calling the printBackwards() method\n"\
"on the object we just received locally.\n"\
- "[press enter]"
- raw_input()
+ "[press enter]")
+ sys.stdin.readline()
- print "==>",
+ sys.stdout.write("==> ")
+ sys.stdout.flush()
printer.printBackwards()
- print '\n'\
+ print('\n'\
"Now we call the same method, but on the remote object. Watch the\n"\
"server's output.\n"\
- "[press enter]"
- raw_input()
+ "[press enter]")
+ sys.stdin.readline()
printerProxy.printBackwards()
- print '\n'\
+ print('\n'\
"Next, we transfer a derived object from the server as a base\n"\
"object. Since we haven't yet installed a factory for the derived\n"\
"class, the derived class (::Demo::DerivedPrinter) is sliced\n"\
"to its base class (::Demo::Printer).\n"\
- "[press enter]"
- raw_input()
+ "[press enter]")
+ sys.stdin.readline()
derivedAsBase = initial.getDerivedPrinter()
- print "==> The type ID of the received object is \"" + derivedAsBase.ice_id() + "\""
+ print("==> The type ID of the received object is \"" + derivedAsBase.ice_id() + "\"")
assert(derivedAsBase.ice_id() == Demo.Printer.ice_staticId())
- print '\n'\
+ print('\n'\
"Now we install a factory for the derived class, and try again.\n"\
"Because we receive the derived object as a base object, we\n"\
"we need to do a dynamic_cast<> to get from the base to the derived object.\n"\
- "[press enter]"
- raw_input()
+ "[press enter]")
+ sys.stdin.readline()
self.communicator().addObjectFactory(factory, Demo.DerivedPrinter.ice_staticId())
derived = initial.getDerivedPrinter()
- print "==> The type ID of the received object is \"" + derived.ice_id() + "\""
+ print("==> The type ID of the received object is \"" + derived.ice_id() + "\"")
- print '\n'\
+ print('\n'\
"Let's print the message contained in the derived object, and\n"\
"call the operation printUppercase() on the derived object\n"\
"locally.\n"\
- "[press enter]"
- raw_input()
+ "[press enter]")
+ sys.stdin.readline()
- print "==> " + derived.derivedMessage
- print "==>",
+ print("==> " + derived.derivedMessage)
+ sys.stdout.write("==> ")
+ sys.stdout.flush()
derived.printUppercase()
- print '\n'\
+ print('\n'\
"Finally, we try the same again, but instead of returning the\n"\
"derived object, we throw an exception containing the derived\n"\
"object.\n"\
- "[press enter]"
- raw_input()
+ "[press enter]")
+ sys.stdin.readline()
try:
initial.throwDerivedPrinter()
- print args[0] + "Did not get the expected DerivedPrinterException!"
+ print(args[0] + "Did not get the expected DerivedPrinterException!")
sys.exit(false)
- except Demo.DerivedPrinterException, ex:
+ except Demo.DerivedPrinterException as ex:
derived = ex.derived
assert(derived)
- print "==> " + derived.derivedMessage
- print "==>",
+ print("==> " + derived.derivedMessage)
+ sys.stdout.write("==> ")
+ sys.stdout.flush()
derived.printUppercase()
- print '\n'\
- "That's it for this demo. Have fun with Ice!"
+ print('\n'\
+ "That's it for this demo. Have fun with Ice!")
initial.shutdown()
diff --git a/py/demo/Ice/value/Printer.py b/py/demo/Ice/value/Printer.py
index 1d76f2e8af0..7b1e8e00c70 100755
--- a/py/demo/Ice/value/Printer.py
+++ b/py/demo/Ice/value/Printer.py
@@ -12,8 +12,8 @@ import Demo, string
class PrinterI(Demo.Printer):
def printBackwards(self, current=None):
- print self.message[::-1]
+ print(self.message[::-1])
class DerivedPrinterI(Demo.DerivedPrinter, PrinterI):
def printUppercase(self, current=None):
- print string.upper(self.derivedMessage)
+ print(self.derivedMessage.upper())
diff --git a/py/demo/Ice/value/Server.py b/py/demo/Ice/value/Server.py
index 7abec6d0315..399ad346960 100755
--- a/py/demo/Ice/value/Server.py
+++ b/py/demo/Ice/value/Server.py
@@ -47,7 +47,7 @@ class InitialI(Demo.Initial):
class Server(Ice.Application):
def run(self, args):
if len(args) > 1:
- print self.appName() + ": too many arguments"
+ print(self.appName() + ": too many arguments")
return 1
adapter = self.communicator().createObjectAdapter("Value")
diff --git a/py/demo/Ice/value/expect.py b/py/demo/Ice/value/expect.py
index 81793e544b7..2e68a040322 100755
--- a/py/demo/Ice/value/expect.py
+++ b/py/demo/Ice/value/expect.py
@@ -16,10 +16,10 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "demoscript")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
+ raise RuntimeError("can't find toplevel directory!")
sys.path.append(path[0])
-from demoscript import *
+from demoscript import Util
from demoscript.Ice import value
server = Util.spawn('Server.py --Ice.PrintAdapterReady')
diff --git a/py/demo/IceGrid/simple/Client.py b/py/demo/IceGrid/simple/Client.py
index 20a84e2e1f6..3a5c94ba044 100755
--- a/py/demo/IceGrid/simple/Client.py
+++ b/py/demo/IceGrid/simple/Client.py
@@ -15,18 +15,18 @@ import Demo
def menu():
- print """
+ print("""
usage:
t: send greeting as twoway
s: shutdown server
x: exit
?: help
-"""
+""")
class Client(Ice.Application):
def run(self, args):
if len(args) > 1:
- print self.appName() + ": too many arguments"
+ print(self.appName() + ": too many arguments")
return 1
hello = None
@@ -37,7 +37,7 @@ class Client(Ice.Application):
hello = Demo.HelloPrx.checkedCast(query.findObjectByType("::Demo::Hello"))
if not hello:
- print self.appName() + ": couldn't find a `::Demo::Hello' object."
+ print(self.appName() + ": couldn't find a `::Demo::Hello' object.")
return 1
menu()
@@ -45,7 +45,9 @@ class Client(Ice.Application):
c = None
while c != 'x':
try:
- c = raw_input("==> ")
+ sys.stdout.write("==> ")
+ sys.stdout.flush()
+ c = sys.stdin.readline().strip()
if c == 't':
hello.sayHello()
elif c == 's':
@@ -55,7 +57,7 @@ class Client(Ice.Application):
elif c == '?':
menu()
else:
- print "unknown command `" + c + "'"
+ print("unknown command `" + c + "'")
menu()
except EOFError:
break
diff --git a/py/demo/IceGrid/simple/Server.py b/py/demo/IceGrid/simple/Server.py
index 0dd15137918..eac5cb19c64 100755
--- a/py/demo/IceGrid/simple/Server.py
+++ b/py/demo/IceGrid/simple/Server.py
@@ -18,16 +18,16 @@ class HelloI(Demo.Hello):
self.name = name
def sayHello(self, current=None):
- print self.name + " says Hello World!"
+ print(self.name + " says Hello World!")
def shutdown(self, current=None):
- print self.name + " shutting down..."
+ print(self.name + " shutting down...")
current.adapter.getCommunicator().shutdown()
class Server(Ice.Application):
def run(self, args):
if len(args) > 1:
- print self.appName() + ": too many arguments"
+ print(self.appName() + ": too many arguments")
return 1
properties = self.communicator().getProperties()
diff --git a/py/demo/IceGrid/simple/expect.py b/py/demo/IceGrid/simple/expect.py
index f12d7722b5f..57c2b114b98 100755
--- a/py/demo/IceGrid/simple/expect.py
+++ b/py/demo/IceGrid/simple/expect.py
@@ -16,16 +16,19 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "demoscript")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
+ raise RuntimeError("can't find toplevel directory!")
sys.path.append(path[0])
-from demoscript import *
+from demoscript import Util
from demoscript.IceGrid import simple
def rewrite(namein, nameout):
fi = open(namein, "r")
fo = open(nameout, "w")
for l in fi:
+ if sys.version_info[0] == 3:
+ if l.find('exe="python"') != -1:
+ l = l.replace('exe="python"', 'exe="python3"')
if l.find('option') != -1:
fo.write('<option>-u</option>')
fo.write(l)
diff --git a/py/demo/IceStorm/clock/Publisher.py b/py/demo/IceStorm/clock/Publisher.py
index fa6ac657b9f..8c82fe7dca5 100755
--- a/py/demo/IceStorm/clock/Publisher.py
+++ b/py/demo/IceStorm/clock/Publisher.py
@@ -15,7 +15,7 @@ import Demo
class Publisher(Ice.Application):
def usage(self):
- print "Usage: " + self.appName() + " [--datagram|--twoway|--oneway] [topic]"
+ print("Usage: " + self.appName() + " [--datagram|--twoway|--oneway] [topic]")
def run(self, args):
try:
@@ -47,7 +47,7 @@ class Publisher(Ice.Application):
manager = IceStorm.TopicManagerPrx.checkedCast(self.communicator().propertyToProxy('TopicManager.Proxy'))
if not manager:
- print args[0] + ": invalid proxy"
+ print(args[0] + ": invalid proxy")
return 1
#
@@ -55,11 +55,11 @@ class Publisher(Ice.Application):
#
try:
topic = manager.retrieve(topicName)
- except IceStorm.NoSuchTopic, e:
+ except IceStorm.NoSuchTopic:
try:
topic = manager.create(topicName)
- except IceStorm.TopicExists, ex:
- print self.appName() + ": temporary error. try again"
+ except IceStorm.TopicExists:
+ print(self.appName() + ": temporary error. try again")
return 1
#
@@ -76,15 +76,15 @@ class Publisher(Ice.Application):
publisher = publisher.ice_oneway();
clock = Demo.ClockPrx.uncheckedCast(publisher)
- print "publishing tick events. Press ^C to terminate the application."
+ print("publishing tick events. Press ^C to terminate the application.")
try:
while 1:
clock.tick(time.strftime("%m/%d/%Y %H:%M:%S"))
time.sleep(1)
- except IOError, e:
+ except IOError:
# Ignore
pass
- except Ice.CommunicatorDestroyedException, e:
+ except Ice.CommunicatorDestroyedException:
# Ignore
pass
diff --git a/py/demo/IceStorm/clock/Subscriber.py b/py/demo/IceStorm/clock/Subscriber.py
index bc96d09c8e8..f350c0fa7d4 100755
--- a/py/demo/IceStorm/clock/Subscriber.py
+++ b/py/demo/IceStorm/clock/Subscriber.py
@@ -15,29 +15,29 @@ import Demo
class ClockI(Demo.Clock):
def tick(self, date, current=None):
- print date
+ print(date)
class Subscriber(Ice.Application):
def usage(self):
- print "Usage: " + self.appName() + \
- " [--batch] [--datagram|--twoway|--ordered|--oneway] [--retryCount count] [--id id] [topic]"
+ print("Usage: " + self.appName() + \
+ " [--batch] [--datagram|--twoway|--ordered|--oneway] [--retryCount count] [--id id] [topic]")
def run(self, args):
try:
opts, args = getopt.getopt(args[1:], '', ['datagram', 'twoway', 'oneway', 'ordered', 'batch',
- 'retryCount=', 'id='])
+ 'retryCount=', 'id='])
except getopt.GetoptError:
self.usage()
return 1
- batch = False
- option = "None"
+ batch = False
+ option = "None"
topicName = "time"
id = ""
retryCount = ""
for o, a in opts:
- oldoption = option
+ oldoption = option
if o == "--datagram":
option = "Datagram"
elif o =="--twoway":
@@ -45,38 +45,38 @@ class Subscriber(Ice.Application):
elif o =="--ordered":
option = "Ordered"
elif o =="--oneway":
- option = "Oneway"
+ option = "Oneway"
elif o =="--batch":
batch = True
- elif o == "--id":
- id = a
- elif o == "--retryCount":
- retryCount = a
- if oldoption != option and oldoption != "None":
- self.usage()
- return 1
+ elif o == "--id":
+ id = a
+ elif o == "--retryCount":
+ retryCount = a
+ if oldoption != option and oldoption != "None":
+ self.usage()
+ return 1
if len(args) > 1:
- self.usage()
- return 1
+ self.usage()
+ return 1
if len(args) > 0:
topicName = args[0]
- if len(retryCount) > 0:
- if option == "None":
- option = "Twoway"
- elif option != "Twoway" and option != "Ordered":
- print self.appName() + ": retryCount requires a twoway proxy"
- return 1
+ if len(retryCount) > 0:
+ if option == "None":
+ option = "Twoway"
+ elif option != "Twoway" and option != "Ordered":
+ print(self.appName() + ": retryCount requires a twoway proxy")
+ return 1
if batch and (option in ("Twoway", "Ordered")):
- print self.appName() + ": batch can only be set with oneway or datagram"
+ print(self.appName() + ": batch can only be set with oneway or datagram")
return 1
manager = IceStorm.TopicManagerPrx.checkedCast(self.communicator().propertyToProxy('TopicManager.Proxy'))
if not manager:
- print args[0] + ": invalid proxy"
+ print(args[0] + ": invalid proxy")
return 1
#
@@ -84,41 +84,41 @@ class Subscriber(Ice.Application):
#
try:
topic = manager.retrieve(topicName)
- except IceStorm.NoSuchTopic, e:
+ except IceStorm.NoSuchTopic as e:
try:
topic = manager.create(topicName)
- except IceStorm.TopicExists, ex:
- print self.appName() + ": temporary error. try again"
+ except IceStorm.TopicExists as ex:
+ print(self.appName() + ": temporary error. try again")
return 1
adapter = self.communicator().createObjectAdapter("Clock.Subscriber")
- #
- # Add a servant for the Ice object. If --id is used the identity
- # comes from the command line, otherwise a UUID is used.
- #
- # id is not directly altered since it is used below to detect
- # whether subscribeAndGetPublisher can raise AlreadySubscribed.
- #
-
- subId = Ice.Identity()
- subId.name = id
- if len(subId.name) == 0:
- subId.name = Ice.generateUUID()
+ #
+ # Add a servant for the Ice object. If --id is used the identity
+ # comes from the command line, otherwise a UUID is used.
+ #
+ # id is not directly altered since it is used below to detect
+ # whether subscribeAndGetPublisher can raise AlreadySubscribed.
+ #
+
+ subId = Ice.Identity()
+ subId.name = id
+ if len(subId.name) == 0:
+ subId.name = Ice.generateUUID()
subscriber = adapter.add(ClockI(), subId)
qos = {}
- if len(retryCount) > 0:
- qos["retryCount"] = retryCount
+ if len(retryCount) > 0:
+ qos["retryCount"] = retryCount
- #
- # Set up the proxy.
- #
+ #
+ # Set up the proxy.
+ #
if option == "Datagram":
- if batch:
- subscriber = subscriber.ice_batchDatagram()
- else:
- subscriber = subscriber.ice_datagram()
+ if batch:
+ subscriber = subscriber.ice_batchDatagram()
+ else:
+ subscriber = subscriber.ice_datagram()
elif option == "Twoway":
# Do nothing to the subscriber proxy. Its already twoway.
pass
@@ -126,18 +126,18 @@ class Subscriber(Ice.Application):
# Do nothing to the subscriber proxy. Its already twoway.
qos["reliability"] = "ordered"
elif option == "Oneway" or option == "None":
- if batch:
- subscriber = subscriber.ice_batchOneway()
- else:
- subscriber = subscriber.ice_oneway()
-
- try:
- topic.subscribeAndGetPublisher(qos, subscriber)
- except IceStorm.AlreadySubscribed, ex:
- # If we're manually setting the subscriber id ignore.
- if len(id) == 0:
- raise
- print "reactivating persistent subscriber"
+ if batch:
+ subscriber = subscriber.ice_batchOneway()
+ else:
+ subscriber = subscriber.ice_oneway()
+
+ try:
+ topic.subscribeAndGetPublisher(qos, subscriber)
+ except IceStorm.AlreadySubscribed as ex:
+ # If we're manually setting the subscriber id ignore.
+ if len(id) == 0:
+ raise
+ print("reactivating persistent subscriber")
adapter.activate()
@@ -148,7 +148,7 @@ class Subscriber(Ice.Application):
# Unsubscribe all subscribed objects.
#
topic.unsubscribe(subscriber)
-
+
return 0
app = Subscriber()
diff --git a/py/demo/IceStorm/clock/expect.py b/py/demo/IceStorm/clock/expect.py
index e6172aa1ecd..02332c30a31 100755
--- a/py/demo/IceStorm/clock/expect.py
+++ b/py/demo/IceStorm/clock/expect.py
@@ -16,10 +16,10 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "demoscript")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
+ raise RuntimeError("can't find toplevel directory!")
sys.path.append(path[0])
-from demoscript import *
+from demoscript import Util
from demoscript.IceStorm import clock
clock.run('Subscriber.py', 'Publisher.py')
diff --git a/py/demo/book/printer/Server.py b/py/demo/book/printer/Server.py
index fba7f0973a6..24ac6c85b23 100755
--- a/py/demo/book/printer/Server.py
+++ b/py/demo/book/printer/Server.py
@@ -15,7 +15,7 @@ import Demo
class PrinterI(Demo.Printer):
def printString(self, s, current=None):
- print s
+ print(s)
status = 0
ice = None
diff --git a/py/demo/book/printer/expect.py b/py/demo/book/printer/expect.py
index 7522533afc9..23854359e52 100755
--- a/py/demo/book/printer/expect.py
+++ b/py/demo/book/printer/expect.py
@@ -8,7 +8,7 @@
#
# **********************************************************************
-import sys, os
+import sys, os, signal
path = [ ".", "..", "../..", "../../..", "../../../.." ]
head = os.path.dirname(sys.argv[0])
@@ -16,20 +16,18 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "demoscript")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
+ raise RuntimeError("can't find toplevel directory!")
sys.path.append(path[0])
-
-from demoscript import *
-import signal
+from demoscript import Util
server = Util.spawn('Server.py --Ice.PrintAdapterReady')
server.expect('.* ready')
-print "testing...",
+sys.stdout.write("testing... ")
sys.stdout.flush()
client = Util.spawn('Client.py')
client.waitTestSuccess()
server.expect('Hello World!')
server.kill(signal.SIGTERM)
server.waitTestSuccess(-signal.SIGTERM)
-print "ok"
+print("ok")
diff --git a/py/demo/book/simple_filesystem/Client.py b/py/demo/book/simple_filesystem/Client.py
index 7d3fb0cb7c6..23caad1fb21 100755
--- a/py/demo/book/simple_filesystem/Client.py
+++ b/py/demo/book/simple_filesystem/Client.py
@@ -29,15 +29,15 @@ def listRecursive(dir, depth):
for node in contents:
subdir = Filesystem.DirectoryPrx.checkedCast(node)
file = Filesystem.FilePrx.uncheckedCast(node)
- print indent + node.name(),
+ sys.stdout.write(indent + node.name() + " ")
if subdir:
- print "(directory):"
+ print("(directory):")
listRecursive(subdir, depth)
else:
- print "(file):"
+ print("(file):")
text = file.read()
for line in text:
- print indent + "\t" + line
+ print(indent + "\t" + line)
status = 0
ic = None
@@ -56,7 +56,7 @@ try:
# Recursively list the contents of the root directory
#
- print "Contents of root directory:"
+ print("Contents of root directory:")
listRecursive(rootDir, 0)
except:
traceback.print_exc()
diff --git a/py/demo/book/simple_filesystem/Server.py b/py/demo/book/simple_filesystem/Server.py
index 14561ca1fa0..266f3a39667 100755
--- a/py/demo/book/simple_filesystem/Server.py
+++ b/py/demo/book/simple_filesystem/Server.py
@@ -94,7 +94,7 @@ class Server(Ice.Application):
# Create an object adapter
#
adapter = self.communicator().createObjectAdapterWithEndpoints(
- "SimpleFileSystem", "default -h localhost -p 10000")
+ "SimpleFileSystem", "default -h localhost -p 10000")
# Create the root directory (with name "/" and no parent)
#
@@ -107,8 +107,8 @@ class Server(Ice.Application):
text = [ "This file system contains a collection of poetry." ]
try:
file.write(text)
- except Filesystem.GenericError, e:
- print e.reason
+ except Filesystem.GenericError as e:
+ print(e.reason)
file.activate(adapter)
# Create a directory called "Coleridge" in the root directory
@@ -126,8 +126,8 @@ class Server(Ice.Application):
"Down to a sunless sea." ]
try:
file.write(text)
- except Filesystem.GenericError, e:
- print e.reason
+ except Filesystem.GenericError as e:
+ print(e.reason)
file.activate(adapter)
# All objects are created, allow client requests now
@@ -139,7 +139,7 @@ class Server(Ice.Application):
self.communicator().waitForShutdown()
if self.interrupted():
- print self.appName() + ": terminating"
+ print(self.appName() + ": terminating")
return 0
diff --git a/py/demo/book/simple_filesystem/expect.py b/py/demo/book/simple_filesystem/expect.py
index 0a5b93a08cc..606df3ed297 100755
--- a/py/demo/book/simple_filesystem/expect.py
+++ b/py/demo/book/simple_filesystem/expect.py
@@ -8,7 +8,7 @@
#
# **********************************************************************
-import sys, os
+import sys, os, signal
path = [ ".", "..", "../..", "../../..", "../../../.." ]
head = os.path.dirname(sys.argv[0])
@@ -16,20 +16,18 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "demoscript")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
+ raise RuntimeError("can't find toplevel directory!")
sys.path.append(path[0])
-
-from demoscript import *
-import signal
+from demoscript import Util
server = Util.spawn('Server.py --Ice.PrintAdapterReady')
server.expect('.* ready')
-print "testing...",
+sys.stdout.write("testing... ")
sys.stdout.flush()
client = Util.spawn('Client.py')
client.expect('Contents of root directory:\n.*Down to a sunless sea.')
client.waitTestSuccess()
server.kill(signal.SIGINT)
server.waitTestSuccess()
-print "ok"
+print("ok")
diff --git a/py/modules/IcePy/Communicator.cpp b/py/modules/IcePy/Communicator.cpp
index ca5a4392b1a..a51fc516576 100644
--- a/py/modules/IcePy/Communicator.cpp
+++ b/py/modules/IcePy/Communicator.cpp
@@ -63,9 +63,10 @@ struct CommunicatorObject
extern "C"
#endif
static CommunicatorObject*
-communicatorNew(PyObject* /*arg*/)
+communicatorNew(PyTypeObject* type, PyObject* /*args*/, PyObject* /*kwds*/)
{
- CommunicatorObject* self = PyObject_New(CommunicatorObject, &CommunicatorType);
+ assert(type && type->tp_alloc);
+ CommunicatorObject* self = reinterpret_cast<CommunicatorObject*>(type->tp_alloc(type, 0));
if(!self)
{
return 0;
@@ -286,7 +287,7 @@ communicatorDealloc(CommunicatorObject* self)
delete self->communicator;
delete self->shutdownMonitor;
delete self->shutdownThread;
- PyObject_Del(self);
+ Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
#ifdef WIN32
@@ -1441,8 +1442,7 @@ PyTypeObject CommunicatorType =
{
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
- PyObject_HEAD_INIT(0)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT(0, 0)
STRCAST("IcePy.Communicator"), /* tp_name */
sizeof(CommunicatorObject), /* tp_basicsize */
0, /* tp_itemsize */
@@ -1451,7 +1451,7 @@ PyTypeObject CommunicatorType =
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
- 0, /* tp_compare */
+ 0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
@@ -1523,7 +1523,7 @@ IcePy::createCommunicator(const Ice::CommunicatorPtr& communicator)
return p->second;
}
- CommunicatorObject* obj = communicatorNew(0);
+ CommunicatorObject* obj = communicatorNew(&CommunicatorType, 0, 0);
if(obj)
{
obj->communicator = new Ice::CommunicatorPtr(communicator);
diff --git a/py/modules/IcePy/Config.h b/py/modules/IcePy/Config.h
index 6339ed0f04c..a8700b66cb4 100644
--- a/py/modules/IcePy/Config.h
+++ b/py/modules/IcePy/Config.h
@@ -32,12 +32,4 @@
#endif
#define STRCAST(s) const_cast<char*>(s)
-//
-// Python 2.5 compatibility.
-//
-#if PY_VERSION_HEX < 0x02050000
- typedef int Py_ssize_t;
-# define ICEPY_OLD_EXCEPTIONS
-#endif
-
#endif
diff --git a/py/modules/IcePy/Connection.cpp b/py/modules/IcePy/Connection.cpp
index 31478d04ab7..f50e591a16a 100644
--- a/py/modules/IcePy/Connection.cpp
+++ b/py/modules/IcePy/Connection.cpp
@@ -41,9 +41,10 @@ struct ConnectionObject
extern "C"
#endif
static ConnectionObject*
-connectionNew(PyObject* /*arg*/)
+connectionNew(PyTypeObject* type, PyObject* /*args*/, PyObject* /*kwds*/)
{
- ConnectionObject* self = PyObject_New(ConnectionObject, &ConnectionType);
+ assert(type && type->tp_alloc);
+ ConnectionObject* self = reinterpret_cast<ConnectionObject*>(type->tp_alloc(type, 0));
if(!self)
{
return 0;
@@ -61,27 +62,63 @@ connectionDealloc(ConnectionObject* self)
{
delete self->connection;
delete self->communicator;
- PyObject_Del(self);
+ Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
#ifdef WIN32
extern "C"
#endif
-static int
-connectionCompare(ConnectionObject* c1, ConnectionObject* c2)
+static PyObject*
+connectionCompare(ConnectionObject* c1, PyObject* other, int op)
{
- if(*c1->connection < *c2->connection)
- {
- return -1;
- }
- else if(*c1->connection == *c2->connection)
+ bool result;
+
+ if(PyObject_TypeCheck(other, &ConnectionType))
{
- return 0;
+ ConnectionObject* c2 = reinterpret_cast<ConnectionObject*>(other);
+
+ switch(op)
+ {
+ case Py_EQ:
+ result = *c1->connection == *c2->connection;
+ break;
+ case Py_NE:
+ result = *c1->connection != *c2->connection;
+ break;
+ case Py_LE:
+ result = *c1->connection <= *c2->connection;
+ break;
+ case Py_GE:
+ result = *c1->connection >= *c2->connection;
+ break;
+ case Py_LT:
+ result = *c1->connection < *c2->connection;
+ break;
+ case Py_GT:
+ result = *c1->connection > *c2->connection;
+ break;
+ }
}
else
{
- return 1;
+ if(op == Py_EQ)
+ {
+ result = false;
+ }
+ else if(op == Py_NE)
+ {
+ result = true;
+ }
+ else
+ {
+ PyErr_Format(PyExc_TypeError, "can't compare %s to %s", Py_TYPE(c1)->tp_name, Py_TYPE(other)->tp_name);
+ return 0;
+ }
}
+
+ PyObject* r = result ? getTrue() : getFalse();
+ Py_INCREF(r);
+ return r;
}
#ifdef WIN32
@@ -361,7 +398,7 @@ connectionTimeout(ConnectionObject* self)
return 0;
}
- return PyInt_FromLong(timeout);
+ return PyLong_FromLong(timeout);
}
#ifdef WIN32
@@ -459,8 +496,7 @@ PyTypeObject ConnectionType =
{
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
- PyObject_HEAD_INIT(0)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT(0, 0)
STRCAST("IcePy.Connection"), /* tp_name */
sizeof(ConnectionObject), /* tp_basicsize */
0, /* tp_itemsize */
@@ -469,7 +505,7 @@ PyTypeObject ConnectionType =
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
- reinterpret_cast<cmpfunc>(connectionCompare), /* tp_compare */
+ 0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
@@ -480,11 +516,16 @@ PyTypeObject ConnectionType =
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
+#if PY_VERSION_HEX >= 0x03000000
Py_TPFLAGS_DEFAULT, /* tp_flags */
+#else
+ Py_TPFLAGS_DEFAULT |
+ Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
+#endif
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
- 0, /* tp_richcompare */
+ reinterpret_cast<richcmpfunc>(connectionCompare), /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
@@ -524,7 +565,7 @@ IcePy::initConnection(PyObject* module)
PyObject*
IcePy::createConnection(const Ice::ConnectionPtr& connection, const Ice::CommunicatorPtr& communicator)
{
- ConnectionObject* obj = connectionNew(0);
+ ConnectionObject* obj = connectionNew(&ConnectionType, 0, 0);
if(obj)
{
obj->connection = new Ice::ConnectionPtr(connection);
diff --git a/py/modules/IcePy/ConnectionInfo.cpp b/py/modules/IcePy/ConnectionInfo.cpp
index 080d6d45e2a..ad917c5790f 100644
--- a/py/modules/IcePy/ConnectionInfo.cpp
+++ b/py/modules/IcePy/ConnectionInfo.cpp
@@ -32,9 +32,9 @@ struct ConnectionInfoObject
extern "C"
#endif
static ConnectionInfoObject*
-connectionInfoNew(PyObject* /*arg*/)
+connectionInfoNew(PyTypeObject* /*type*/, PyObject* /*args*/, PyObject* /*kwds*/)
{
- PyErr_Format(PyExc_RuntimeError, STRCAST("An connection info cannot be created directly"));
+ PyErr_Format(PyExc_RuntimeError, STRCAST("A connection info cannot be created directly"));
return 0;
}
@@ -45,7 +45,7 @@ static void
connectionInfoDealloc(ConnectionInfoObject* self)
{
delete self->connectionInfo;
- PyObject_Del(self);
+ Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
#ifdef WIN32
@@ -87,7 +87,7 @@ ipConnectionInfoGetLocalPort(ConnectionInfoObject* self)
{
Ice::IPConnectionInfoPtr info = Ice::IPConnectionInfoPtr::dynamicCast(*self->connectionInfo);
assert(info);
- return PyInt_FromLong(info->localPort);
+ return PyLong_FromLong(info->localPort);
}
#ifdef WIN32
@@ -109,7 +109,7 @@ ipConnectionInfoGetRemotePort(ConnectionInfoObject* self)
{
Ice::IPConnectionInfoPtr info = Ice::IPConnectionInfoPtr::dynamicCast(*self->connectionInfo);
assert(info);
- return PyInt_FromLong(info->remotePort);
+ return PyLong_FromLong(info->remotePort);
}
#ifdef WIN32
@@ -131,7 +131,7 @@ udpConnectionInfoGetMcastPort(ConnectionInfoObject* self, void* member)
{
Ice::UDPConnectionInfoPtr info = Ice::UDPConnectionInfoPtr::dynamicCast(*self->connectionInfo);
assert(info);
- return PyInt_FromLong(info->mcastPort);
+ return PyLong_FromLong(info->mcastPort);
}
static PyGetSetDef ConnectionInfoGetters[] =
@@ -172,8 +172,7 @@ PyTypeObject ConnectionInfoType =
{
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
- PyObject_HEAD_INIT(0)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT(0, 0)
STRCAST("IcePy.ConnectionInfo"), /* tp_name */
sizeof(ConnectionInfoObject), /* tp_basicsize */
0, /* tp_itemsize */
@@ -182,7 +181,7 @@ PyTypeObject ConnectionInfoType =
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
- 0, /* tp_compare */
+ 0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
@@ -220,8 +219,7 @@ PyTypeObject IPConnectionInfoType =
{
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
- PyObject_HEAD_INIT(0)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT(0, 0)
STRCAST("IcePy.IPConnectionInfo"), /* tp_name */
sizeof(ConnectionInfoObject), /* tp_basicsize */
0, /* tp_itemsize */
@@ -230,7 +228,7 @@ PyTypeObject IPConnectionInfoType =
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
- 0, /* tp_compare */
+ 0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
@@ -268,8 +266,7 @@ PyTypeObject TCPConnectionInfoType =
{
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
- PyObject_HEAD_INIT(0)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT(0, 0)
STRCAST("IcePy.TCPConnectionInfo"),/* tp_name */
sizeof(ConnectionInfoObject), /* tp_basicsize */
0, /* tp_itemsize */
@@ -278,7 +275,7 @@ PyTypeObject TCPConnectionInfoType =
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
- 0, /* tp_compare */
+ 0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
@@ -316,8 +313,7 @@ PyTypeObject UDPConnectionInfoType =
{
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
- PyObject_HEAD_INIT(0)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT(0, 0)
STRCAST("IcePy.UDPConnectionInfo"),/* tp_name */
sizeof(ConnectionInfoObject), /* tp_basicsize */
0, /* tp_itemsize */
@@ -326,7 +322,7 @@ PyTypeObject UDPConnectionInfoType =
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
- 0, /* tp_compare */
+ 0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
@@ -440,7 +436,7 @@ IcePy::createConnectionInfo(const Ice::ConnectionInfoPtr& connectionInfo)
type = &ConnectionInfoType;
}
- ConnectionInfoObject* obj = PyObject_New(ConnectionInfoObject, type);
+ ConnectionInfoObject* obj = reinterpret_cast<ConnectionInfoObject*>(type->tp_alloc(type, 0));
if(!obj)
{
return 0;
diff --git a/py/modules/IcePy/Current.cpp b/py/modules/IcePy/Current.cpp
index 860be1a5100..6ec6c15e73b 100644
--- a/py/modules/IcePy/Current.cpp
+++ b/py/modules/IcePy/Current.cpp
@@ -55,9 +55,9 @@ const Py_ssize_t CURRENT_REQUEST_ID = 7;
extern "C"
#endif
static CurrentObject*
-currentNew(PyObject* /*arg*/)
+currentNew(PyTypeObject* type, PyObject* /*args*/, PyObject* /*kwds*/)
{
- CurrentObject* self = PyObject_New(CurrentObject, &CurrentType);
+ CurrentObject* self = reinterpret_cast<CurrentObject*>(type->tp_alloc(type, 0));
if(!self)
{
return 0;
@@ -91,7 +91,7 @@ currentDealloc(CurrentObject* self)
Py_XDECREF(self->ctx);
Py_XDECREF(self->requestId);
delete self->current;
- PyObject_Del(self);
+ Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
#ifdef WIN32
@@ -216,7 +216,7 @@ currentGetter(CurrentObject* self, void* closure)
{
if(!self->requestId)
{
- self->requestId = PyInt_FromLong(self->current->requestId);
+ self->requestId = PyLong_FromLong(self->current->requestId);
assert(self->requestId);
}
Py_INCREF(self->requestId);
@@ -256,8 +256,7 @@ PyTypeObject CurrentType =
{
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
- PyObject_HEAD_INIT(0)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT(0, 0)
STRCAST("IcePy.Current"), /* tp_name */
sizeof(CurrentObject), /* tp_basicsize */
0, /* tp_itemsize */
@@ -266,7 +265,7 @@ PyTypeObject CurrentType =
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
- 0, /* tp_compare */
+ 0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
@@ -324,7 +323,7 @@ IcePy::createCurrent(const Ice::Current& current)
//
// Return an instance of IcePy.Current to hold the current information.
//
- CurrentObject* obj = currentNew(0);
+ CurrentObject* obj = currentNew(&CurrentType, 0, 0);
if(obj)
{
*obj->current = current;
diff --git a/py/modules/IcePy/Endpoint.cpp b/py/modules/IcePy/Endpoint.cpp
index 979193fa7fd..84d0c725cf9 100644
--- a/py/modules/IcePy/Endpoint.cpp
+++ b/py/modules/IcePy/Endpoint.cpp
@@ -32,7 +32,7 @@ struct EndpointObject
extern "C"
#endif
static EndpointObject*
-endpointNew(PyObject* /*arg*/)
+endpointNew(PyTypeObject* /*type*/, PyObject* /*args*/, PyObject* /*kwds*/)
{
PyErr_Format(PyExc_RuntimeError, STRCAST("An endpoint cannot be created directly"));
return 0;
@@ -45,27 +45,63 @@ static void
endpointDealloc(EndpointObject* self)
{
delete self->endpoint;
- PyObject_Del(self);
+ Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
#ifdef WIN32
extern "C"
#endif
-static int
-endpointCompare(EndpointObject* p1, EndpointObject* p2)
+static PyObject*
+endpointCompare(EndpointObject* p1, PyObject* other, int op)
{
- if(*p1->endpoint < *p2->endpoint)
- {
- return -1;
- }
- else if(*p1->endpoint == *p2->endpoint)
+ bool result;
+
+ if(PyObject_TypeCheck(other, &EndpointType))
{
- return 0;
+ EndpointObject* p2 = reinterpret_cast<EndpointObject*>(other);
+
+ switch(op)
+ {
+ case Py_EQ:
+ result = *p1->endpoint == *p2->endpoint;
+ break;
+ case Py_NE:
+ result = *p1->endpoint != *p2->endpoint;
+ break;
+ case Py_LE:
+ result = *p1->endpoint <= *p2->endpoint;
+ break;
+ case Py_GE:
+ result = *p1->endpoint >= *p2->endpoint;
+ break;
+ case Py_LT:
+ result = *p1->endpoint < *p2->endpoint;
+ break;
+ case Py_GT:
+ result = *p1->endpoint > *p2->endpoint;
+ break;
+ }
}
else
{
- return 1;
+ if(op == Py_EQ)
+ {
+ result = false;
+ }
+ else if(op == Py_NE)
+ {
+ result = true;
+ }
+ else
+ {
+ PyErr_Format(PyExc_TypeError, "can't compare %s to %s", Py_TYPE(p1)->tp_name, Py_TYPE(other)->tp_name);
+ return 0;
+ }
}
+
+ PyObject* r = result ? getTrue() : getFalse();
+ Py_INCREF(r);
+ return r;
}
#ifdef WIN32
@@ -131,18 +167,17 @@ PyTypeObject EndpointType =
{
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
- PyObject_HEAD_INIT(0)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT(0, 0)
STRCAST("IcePy.Endpoint"), /* tp_name */
sizeof(EndpointObject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
- (destructor)endpointDealloc, /* tp_dealloc */
+ reinterpret_cast<destructor>(endpointDealloc), /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
- (cmpfunc)endpointCompare, /* tp_compare */
- (reprfunc)endpointRepr, /* tp_repr */
+ 0, /* tp_reserved */
+ reinterpret_cast<reprfunc>(endpointRepr), /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
@@ -152,11 +187,18 @@ PyTypeObject EndpointType =
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+#if PY_VERSION_HEX >= 0x03000000
+ Py_TPFLAGS_DEFAULT |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+#else
+ Py_TPFLAGS_DEFAULT |
+ Py_TPFLAGS_BASETYPE |
+ Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
+#endif
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
- 0, /* tp_richcompare */
+ reinterpret_cast<richcmpfunc>(endpointCompare), /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
@@ -170,7 +212,7 @@ PyTypeObject EndpointType =
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
- (newfunc)endpointNew, /* tp_new */
+ reinterpret_cast<newfunc>(endpointNew), /* tp_new */
0, /* tp_free */
0, /* tp_is_gc */
};
@@ -204,7 +246,7 @@ IcePy::getEndpoint(PyObject* obj)
PyObject*
IcePy::createEndpoint(const Ice::EndpointPtr& endpoint)
{
- EndpointObject* obj = PyObject_New(EndpointObject, &EndpointType);
+ EndpointObject* obj = reinterpret_cast<EndpointObject*>(EndpointType.tp_alloc(&EndpointType, 0));
if(!obj)
{
return 0;
diff --git a/py/modules/IcePy/EndpointInfo.cpp b/py/modules/IcePy/EndpointInfo.cpp
index 46df1510902..c096ed77006 100644
--- a/py/modules/IcePy/EndpointInfo.cpp
+++ b/py/modules/IcePy/EndpointInfo.cpp
@@ -31,7 +31,7 @@ struct EndpointInfoObject
extern "C"
#endif
static EndpointInfoObject*
-endpointInfoNew(PyObject* /*arg*/)
+endpointInfoNew(PyTypeObject* /*type*/, PyObject* /*args*/, PyObject* /*kwds*/)
{
PyErr_Format(PyExc_RuntimeError, STRCAST("An endpoint info cannot be created directly"));
return 0;
@@ -44,7 +44,7 @@ static void
endpointInfoDealloc(EndpointInfoObject* self)
{
delete self->endpointInfo;
- PyObject_Del(self);
+ Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
//
@@ -60,7 +60,7 @@ endpointInfoType(EndpointInfoObject* self)
try
{
Ice::Short type = (*self->endpointInfo)->type();
- return PyInt_FromLong(type);
+ return PyLong_FromLong(type);
}
catch(const Ice::Exception& ex)
{
@@ -125,7 +125,7 @@ extern "C"
static PyObject*
endpointInfoGetTimeout(EndpointInfoObject* self)
{
- return PyInt_FromLong((*self->endpointInfo)->timeout);
+ return PyLong_FromLong((*self->endpointInfo)->timeout);
}
#ifdef WIN32
@@ -158,7 +158,7 @@ ipEndpointInfoGetPort(EndpointInfoObject* self)
{
Ice::IPEndpointInfoPtr info = Ice::IPEndpointInfoPtr::dynamicCast(*self->endpointInfo);
assert(info);
- return PyInt_FromLong(info->port);
+ return PyLong_FromLong(info->port);
}
#ifdef WIN32
@@ -169,7 +169,7 @@ udpEndpointInfoGetProtocolMajor(EndpointInfoObject* self)
{
Ice::UDPEndpointInfoPtr info = Ice::UDPEndpointInfoPtr::dynamicCast(*self->endpointInfo);
assert(info);
- return PyInt_FromLong(info->protocolMajor);
+ return PyLong_FromLong(info->protocolMajor);
}
#ifdef WIN32
@@ -180,7 +180,7 @@ udpEndpointInfoGetProtocolMinor(EndpointInfoObject* self)
{
Ice::UDPEndpointInfoPtr info = Ice::UDPEndpointInfoPtr::dynamicCast(*self->endpointInfo);
assert(info);
- return PyInt_FromLong(info->protocolMinor);
+ return PyLong_FromLong(info->protocolMinor);
}
#ifdef WIN32
@@ -191,7 +191,7 @@ udpEndpointInfoGetEncodingMajor(EndpointInfoObject* self)
{
Ice::UDPEndpointInfoPtr info = Ice::UDPEndpointInfoPtr::dynamicCast(*self->endpointInfo);
assert(info);
- return PyInt_FromLong(info->encodingMajor);
+ return PyLong_FromLong(info->encodingMajor);
}
#ifdef WIN32
@@ -202,7 +202,7 @@ udpEndpointInfoGetEncodingMinor(EndpointInfoObject* self)
{
Ice::UDPEndpointInfoPtr info = Ice::UDPEndpointInfoPtr::dynamicCast(*self->endpointInfo);
assert(info);
- return PyInt_FromLong(info->encodingMinor);
+ return PyLong_FromLong(info->encodingMinor);
}
#ifdef WIN32
@@ -224,7 +224,7 @@ udpEndpointInfoGetMcastTtl(EndpointInfoObject* self)
{
Ice::UDPEndpointInfoPtr info = Ice::UDPEndpointInfoPtr::dynamicCast(*self->endpointInfo);
assert(info);
- return PyInt_FromLong(info->mcastTtl);
+ return PyLong_FromLong(info->mcastTtl);
}
#ifdef WIN32
@@ -235,8 +235,13 @@ opaqueEndpointInfoGetRawBytes(EndpointInfoObject* self)
{
Ice::OpaqueEndpointInfoPtr info = Ice::OpaqueEndpointInfoPtr::dynamicCast(*self->endpointInfo);
assert(info);
+#if PY_VERSION_HEX >= 0x03000000
+ return PyBytes_FromStringAndSize(reinterpret_cast<const char*>(&info->rawBytes[0]),
+ static_cast<int>(info->rawBytes.size()));
+#else
return PyString_FromStringAndSize(reinterpret_cast<const char*>(&info->rawBytes[0]),
static_cast<int>(info->rawBytes.size()));
+#endif
}
static PyMethodDef EndpointInfoMethods[] =
@@ -299,17 +304,16 @@ PyTypeObject EndpointInfoType =
{
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
- PyObject_HEAD_INIT(0)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT(0, 0)
STRCAST("IcePy.EndpointInfo"), /* tp_name */
sizeof(EndpointInfoObject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
- (destructor)endpointInfoDealloc, /* tp_dealloc */
+ reinterpret_cast<destructor>(endpointInfoDealloc), /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
- 0, /* tp_compare */
+ 0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
@@ -338,7 +342,7 @@ PyTypeObject EndpointInfoType =
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
- (newfunc)endpointInfoNew, /* tp_new */
+ reinterpret_cast<newfunc>(endpointInfoNew), /* tp_new */
0, /* tp_free */
0, /* tp_is_gc */
};
@@ -347,17 +351,16 @@ PyTypeObject IPEndpointInfoType =
{
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
- PyObject_HEAD_INIT(0)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT(0, 0)
STRCAST("IcePy.IPEndpointInfo"), /* tp_name */
sizeof(EndpointInfoObject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
- (destructor)endpointInfoDealloc, /* tp_dealloc */
+ reinterpret_cast<destructor>(endpointInfoDealloc), /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
- 0, /* tp_compare */
+ 0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
@@ -386,7 +389,7 @@ PyTypeObject IPEndpointInfoType =
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
- (newfunc)endpointInfoNew, /* tp_new */
+ reinterpret_cast<newfunc>(endpointInfoNew), /* tp_new */
0, /* tp_free */
0, /* tp_is_gc */
};
@@ -395,17 +398,16 @@ PyTypeObject TCPEndpointInfoType =
{
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
- PyObject_HEAD_INIT(0)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT(0, 0)
STRCAST("IcePy.TCPEndpointInfo"),/* tp_name */
sizeof(EndpointInfoObject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
- (destructor)endpointInfoDealloc, /* tp_dealloc */
+ reinterpret_cast<destructor>(endpointInfoDealloc), /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
- 0, /* tp_compare */
+ 0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
@@ -434,7 +436,7 @@ PyTypeObject TCPEndpointInfoType =
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
- (newfunc)endpointInfoNew, /* tp_new */
+ reinterpret_cast<newfunc>(endpointInfoNew), /* tp_new */
0, /* tp_free */
0, /* tp_is_gc */
};
@@ -443,17 +445,16 @@ PyTypeObject UDPEndpointInfoType =
{
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
- PyObject_HEAD_INIT(0)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT(0, 0)
STRCAST("IcePy.UDPEndpointInfo"),/* tp_name */
sizeof(EndpointInfoObject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
- (destructor)endpointInfoDealloc, /* tp_dealloc */
+ reinterpret_cast<destructor>(endpointInfoDealloc), /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
- 0, /* tp_compare */
+ 0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
@@ -482,7 +483,7 @@ PyTypeObject UDPEndpointInfoType =
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
- (newfunc)endpointInfoNew, /* tp_new */
+ reinterpret_cast<newfunc>(endpointInfoNew), /* tp_new */
0, /* tp_free */
0, /* tp_is_gc */
};
@@ -491,17 +492,16 @@ PyTypeObject OpaqueEndpointInfoType =
{
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
- PyObject_HEAD_INIT(0)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT(0, 0)
STRCAST("IcePy.OpaqueEndpointInfo"),/* tp_name */
sizeof(EndpointInfoObject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
- (destructor)endpointInfoDealloc, /* tp_dealloc */
+ reinterpret_cast<destructor>(endpointInfoDealloc), /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
- 0, /* tp_compare */
+ 0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
@@ -530,7 +530,7 @@ PyTypeObject OpaqueEndpointInfoType =
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
- (newfunc)endpointInfoNew, /* tp_new */
+ reinterpret_cast<newfunc>(endpointInfoNew), /* tp_new */
0, /* tp_free */
0, /* tp_is_gc */
};
@@ -630,7 +630,7 @@ IcePy::createEndpointInfo(const Ice::EndpointInfoPtr& endpointInfo)
type = &EndpointInfoType;
}
- EndpointInfoObject* obj = PyObject_New(EndpointInfoObject, type);
+ EndpointInfoObject* obj = reinterpret_cast<EndpointInfoObject*>(type->tp_alloc(type, 0));
if(!obj)
{
return 0;
diff --git a/py/modules/IcePy/ImplicitContext.cpp b/py/modules/IcePy/ImplicitContext.cpp
index d60a216411e..5ceae0f6ea6 100644
--- a/py/modules/IcePy/ImplicitContext.cpp
+++ b/py/modules/IcePy/ImplicitContext.cpp
@@ -36,9 +36,9 @@ struct ImplicitContextObject
extern "C"
#endif
static ImplicitContextObject*
-implicitContextNew(PyObject* /*arg*/)
+implicitContextNew(PyTypeObject* type, PyObject* /*args*/, PyObject* /*kwds*/)
{
- ImplicitContextObject* self = PyObject_New(ImplicitContextObject, &ImplicitContextType);
+ ImplicitContextObject* self = reinterpret_cast<ImplicitContextObject*>(type->tp_alloc(type, 0));
if(!self)
{
return 0;
@@ -54,27 +54,63 @@ static void
implicitContextDealloc(ImplicitContextObject* self)
{
delete self->implicitContext;
- PyObject_Del(self);
+ Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
#ifdef WIN32
extern "C"
#endif
-static int
-implicitContextCompare(ImplicitContextObject* c1, ImplicitContextObject* c2)
+static PyObject*
+implicitContextCompare(ImplicitContextObject* c1, PyObject* other, int op)
{
- if(*c1->implicitContext < *c2->implicitContext)
+ bool result;
+
+ if(PyObject_TypeCheck(other, &ImplicitContextType))
{
- return -1;
- }
- else if(*c1->implicitContext == *c2->implicitContext)
- {
- return 0;
+ ImplicitContextObject* c2 = reinterpret_cast<ImplicitContextObject*>(other);
+
+ switch(op)
+ {
+ case Py_EQ:
+ result = *c1->implicitContext == *c2->implicitContext;
+ break;
+ case Py_NE:
+ result = *c1->implicitContext != *c2->implicitContext;
+ break;
+ case Py_LE:
+ result = *c1->implicitContext <= *c2->implicitContext;
+ break;
+ case Py_GE:
+ result = *c1->implicitContext >= *c2->implicitContext;
+ break;
+ case Py_LT:
+ result = *c1->implicitContext < *c2->implicitContext;
+ break;
+ case Py_GT:
+ result = *c1->implicitContext > *c2->implicitContext;
+ break;
+ }
}
else
{
- return 1;
+ if(op == Py_EQ)
+ {
+ result = false;
+ }
+ else if(op == Py_NE)
+ {
+ result = true;
+ }
+ else
+ {
+ PyErr_Format(PyExc_TypeError, "can't compare %s to %s", Py_TYPE(c1)->tp_name, Py_TYPE(other)->tp_name);
+ return 0;
+ }
}
+
+ PyObject* r = result ? getTrue() : getFalse();
+ Py_INCREF(r);
+ return r;
}
#ifdef WIN32
@@ -278,8 +314,7 @@ PyTypeObject ImplicitContextType =
{
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
- PyObject_HEAD_INIT(0)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT(0, 0)
STRCAST("IcePy.ImplicitContext"), /* tp_name */
sizeof(ImplicitContextObject), /* tp_basicsize */
0, /* tp_itemsize */
@@ -288,7 +323,7 @@ PyTypeObject ImplicitContextType =
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
- reinterpret_cast<cmpfunc>(implicitContextCompare), /* tp_compare */
+ 0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
@@ -299,15 +334,20 @@ PyTypeObject ImplicitContextType =
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
+#if PY_VERSION_HEX >= 0x03000000
Py_TPFLAGS_DEFAULT, /* tp_flags */
+#else
+ Py_TPFLAGS_DEFAULT |
+ Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
+#endif
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
- 0, /* tp_richcompare */
+ reinterpret_cast<richcmpfunc>(implicitContextCompare), /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
- ImplicitContextMethods, /* tp_methods */
+ ImplicitContextMethods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
@@ -343,7 +383,7 @@ IcePy::initImplicitContext(PyObject* module)
PyObject*
IcePy::createImplicitContext(const Ice::ImplicitContextPtr& implicitContext)
{
- ImplicitContextObject* obj = implicitContextNew(0);
+ ImplicitContextObject* obj = implicitContextNew(&ImplicitContextType, 0, 0);
if(obj)
{
obj->implicitContext = new Ice::ImplicitContextPtr(implicitContext);
diff --git a/py/modules/IcePy/Init.cpp b/py/modules/IcePy/Init.cpp
index eec84a7d4f0..c5b383d9fc2 100644
--- a/py/modules/IcePy/Init.cpp
+++ b/py/modules/IcePy/Init.cpp
@@ -73,14 +73,41 @@ static PyMethodDef methods[] =
{ 0, 0 } /* sentinel */
};
+#if PY_VERSION_HEX >= 0x03000000
+
+# define INIT_RETURN return(0)
+
+static struct PyModuleDef iceModule =
+{
+ PyModuleDef_HEAD_INIT,
+ "IcePy",
+ "The Internet Communications Engine.",
+ -1,
+ methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+};
+
+#else
+
+# define INIT_RETURN return
+
PyDoc_STRVAR(moduleDoc, "The Internet Communications Engine.");
+#endif
+
#if defined(__SUNPRO_CC) && (__SUNPRO_CC >= 0x550)
extern "C" __global void
#else
PyMODINIT_FUNC
#endif
+#if PY_VERSION_HEX >= 0x03000000
+PyInit_IcePy(void)
+#else
initIcePy(void)
+#endif
{
PyObject* module;
@@ -89,64 +116,75 @@ initIcePy(void)
//
PyEval_InitThreads();
+#if PY_VERSION_HEX >= 0x03000000
+ //
+ // Create the module.
+ //
+ module = PyModule_Create(&iceModule);
+#else
//
// Initialize the module.
//
module = Py_InitModule3(STRCAST("IcePy"), methods, moduleDoc);
+#endif
//
// Install built-in Ice types.
//
if(!initProxy(module))
{
- return;
+ INIT_RETURN;
}
if(!initTypes(module))
{
- return;
+ INIT_RETURN;
}
if(!initProperties(module))
{
- return;
+ INIT_RETURN;
}
if(!initCommunicator(module))
{
- return;
+ INIT_RETURN;
}
if(!initCurrent(module))
{
- return;
+ INIT_RETURN;
}
if(!initObjectAdapter(module))
{
- return;
+ INIT_RETURN;
}
if(!initOperation(module))
{
- return;
+ INIT_RETURN;
}
if(!initLogger(module))
{
- return;
+ INIT_RETURN;
}
if(!initConnection(module))
{
- return;
+ INIT_RETURN;
}
if(!initConnectionInfo(module))
{
- return;
+ INIT_RETURN;
}
if(!initImplicitContext(module))
{
- return;
+ INIT_RETURN;
}
if(!initEndpoint(module))
{
- return;
+ INIT_RETURN;
}
if(!initEndpointInfo(module))
{
- return;
+ INIT_RETURN;
}
+
+#if PY_VERSION_HEX >= 0x03000000
+ return module;
+#endif
}
diff --git a/py/modules/IcePy/Logger.cpp b/py/modules/IcePy/Logger.cpp
index 3d7bca5d895..bacf5c45395 100644
--- a/py/modules/IcePy/Logger.cpp
+++ b/py/modules/IcePy/Logger.cpp
@@ -108,9 +108,9 @@ IcePy::LoggerWrapper::getObject()
extern "C"
#endif
static LoggerObject*
-loggerNew(PyObject* /*arg*/)
+loggerNew(PyTypeObject* type, PyObject* /*args*/, PyObject* /*kwds*/)
{
- LoggerObject* self = PyObject_New(LoggerObject, &LoggerType);
+ LoggerObject* self = reinterpret_cast<LoggerObject*>(type->tp_alloc(type, 0));
if(!self)
{
return 0;
@@ -126,7 +126,7 @@ static void
loggerDealloc(LoggerObject* self)
{
delete self->logger;
- PyObject_Del(self);
+ Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
#ifdef WIN32
@@ -338,8 +338,7 @@ PyTypeObject LoggerType =
{
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
- PyObject_HEAD_INIT(0)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT(0, 0)
STRCAST("IcePy.Logger"), /* tp_name */
sizeof(LoggerObject), /* tp_basicsize */
0, /* tp_itemsize */
@@ -348,7 +347,7 @@ PyTypeObject LoggerType =
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
- 0, /* tp_compare */
+ 0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
@@ -403,7 +402,7 @@ IcePy::initLogger(PyObject* module)
PyObject*
IcePy::createLogger(const Ice::LoggerPtr& logger)
{
- LoggerObject* obj = loggerNew(0);
+ LoggerObject* obj = loggerNew(&LoggerType, 0, 0);
if(obj)
{
obj->logger = new Ice::LoggerPtr(logger);
diff --git a/py/modules/IcePy/ObjectAdapter.cpp b/py/modules/IcePy/ObjectAdapter.cpp
index 5e55ff3fc91..a45274bca62 100644
--- a/py/modules/IcePy/ObjectAdapter.cpp
+++ b/py/modules/IcePy/ObjectAdapter.cpp
@@ -269,7 +269,7 @@ IcePy::ServantLocatorWrapper::Cookie::~Cookie()
extern "C"
#endif
static ObjectAdapterObject*
-adapterNew(PyObject* /*arg*/)
+adapterNew(PyTypeObject* /*type*/, PyObject* /*args*/, PyObject* /*kwds*/)
{
PyErr_Format(PyExc_RuntimeError, STRCAST("Use communicator.createObjectAdapter to create an adapter"));
return 0;
@@ -294,7 +294,7 @@ adapterDealloc(ObjectAdapterObject* self)
delete self->deactivateThread;
delete self->holdMonitor;
delete self->holdThread;
- PyObject_Del(self);
+ Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
#ifdef WIN32
@@ -1661,8 +1661,7 @@ PyTypeObject ObjectAdapterType =
{
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
- PyObject_HEAD_INIT(0)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT(0, 0)
STRCAST("IcePy.ObjectAdapter"), /* tp_name */
sizeof(ObjectAdapterObject), /* tp_basicsize */
0, /* tp_itemsize */
@@ -1671,7 +1670,7 @@ PyTypeObject ObjectAdapterType =
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
- 0, /* tp_compare */
+ 0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
@@ -1728,7 +1727,8 @@ IcePy::initObjectAdapter(PyObject* module)
PyObject*
IcePy::createObjectAdapter(const Ice::ObjectAdapterPtr& adapter)
{
- ObjectAdapterObject* obj = PyObject_New(ObjectAdapterObject, &ObjectAdapterType);
+ ObjectAdapterObject* obj =
+ reinterpret_cast<ObjectAdapterObject*>(ObjectAdapterType.tp_alloc(&ObjectAdapterType, 0));
if(obj)
{
obj->adapter = new Ice::ObjectAdapterPtr(adapter);
diff --git a/py/modules/IcePy/Operation.cpp b/py/modules/IcePy/Operation.cpp
index 8d8c1b8e6e2..4a14afcb137 100644
--- a/py/modules/IcePy/Operation.cpp
+++ b/py/modules/IcePy/Operation.cpp
@@ -480,9 +480,9 @@ callSent(PyObject* callback, const string& method, bool sentSynchronously, bool
extern "C"
#endif
static OperationObject*
-operationNew(PyObject* /*arg*/)
+operationNew(PyTypeObject* type, PyObject* /*args*/, PyObject* /*kwds*/)
{
- OperationObject* self = PyObject_New(OperationObject, &OperationType);
+ OperationObject* self = reinterpret_cast<OperationObject*>(type->tp_alloc(type, 0));
if(!self)
{
return 0;
@@ -528,7 +528,7 @@ static void
operationDealloc(OperationObject* self)
{
delete self->op;
- PyObject_Del(self);
+ Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
#ifdef WIN32
@@ -642,9 +642,9 @@ operationDeprecate(OperationObject* self, PyObject* args)
extern "C"
#endif
static AMDCallbackObject*
-amdCallbackNew(PyObject* /*arg*/)
+amdCallbackNew(PyTypeObject* type, PyObject* /*args*/, PyObject* /*kwds*/)
{
- AMDCallbackObject* self = PyObject_New(AMDCallbackObject, &AMDCallbackType);
+ AMDCallbackObject* self = reinterpret_cast<AMDCallbackObject*>(type->tp_alloc(type, 0));
if(!self)
{
return 0;
@@ -660,7 +660,7 @@ static void
amdCallbackDealloc(AMDCallbackObject* self)
{
delete self->upcall;
- PyObject_Del(self);
+ Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
#ifdef WIN32
@@ -724,9 +724,9 @@ amdCallbackIceException(AMDCallbackObject* self, PyObject* args)
extern "C"
#endif
static AsyncResultObject*
-asyncResultNew(PyObject* /*arg*/)
+asyncResultNew(PyTypeObject* type, PyObject* /*args*/, PyObject* /*kwds*/)
{
- AsyncResultObject* self = PyObject_New(AsyncResultObject, &AsyncResultType);
+ AsyncResultObject* self = reinterpret_cast<AsyncResultObject*>(type->tp_alloc(type, 0));
if(!self)
{
return 0;
@@ -750,7 +750,7 @@ asyncResultDealloc(AsyncResultObject* self)
Py_XDECREF(self->proxy);
Py_XDECREF(self->connection);
Py_XDECREF(self->communicator);
- PyObject_Del(self);
+ Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
#ifdef WIN32
@@ -992,15 +992,15 @@ IcePy::Operation::Operation(const char* n, PyObject* m, PyObject* sm, int amdFla
// mode
//
PyObjectHandle modeValue = PyObject_GetAttrString(m, STRCAST("value"));
- assert(PyInt_Check(modeValue.get()));
- mode = (Ice::OperationMode)static_cast<int>(PyInt_AS_LONG(modeValue.get()));
+ mode = (Ice::OperationMode)static_cast<int>(PyLong_AsLong(modeValue.get()));
+ assert(!PyErr_Occurred());
//
// sendMode
//
PyObjectHandle sendModeValue = PyObject_GetAttrString(sm, STRCAST("value"));
- assert(PyInt_Check(sendModeValue.get()));
- sendMode = (Ice::OperationMode)static_cast<int>(PyInt_AS_LONG(sendModeValue.get()));
+ sendMode = (Ice::OperationMode)static_cast<int>(PyLong_AsLong(sendModeValue.get()));
+ assert(!PyErr_Occurred());
//
// amd
@@ -1169,8 +1169,7 @@ PyTypeObject OperationType =
{
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
- PyObject_HEAD_INIT(0)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT(0, 0)
STRCAST("IcePy.Operation"), /* tp_name */
sizeof(OperationObject), /* tp_basicsize */
0, /* tp_itemsize */
@@ -1179,7 +1178,7 @@ PyTypeObject OperationType =
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
- 0, /* tp_compare */
+ 0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
@@ -1217,8 +1216,7 @@ PyTypeObject AMDCallbackType =
{
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
- PyObject_HEAD_INIT(0)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT(0, 0)
STRCAST("IcePy.AMDCallback"), /* tp_name */
sizeof(AMDCallbackObject), /* tp_basicsize */
0, /* tp_itemsize */
@@ -1227,7 +1225,7 @@ PyTypeObject AMDCallbackType =
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
- 0, /* tp_compare */
+ 0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
@@ -1265,8 +1263,7 @@ PyTypeObject AsyncResultType =
{
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
- PyObject_HEAD_INIT(0)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT(0, 0)
STRCAST("IcePy.AsyncResult"), /* tp_name */
sizeof(AsyncResultObject), /* tp_basicsize */
0, /* tp_itemsize */
@@ -1275,7 +1272,7 @@ PyTypeObject AsyncResultType =
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
- 0, /* tp_compare */
+ 0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
@@ -1651,7 +1648,8 @@ IcePy::SyncTypedInvocation::invoke(PyObject* args, PyObject* /* kwds */)
//
// Unmarshal a user exception.
//
- pair<const Ice::Byte*, const Ice::Byte*> rb(static_cast<const Ice::Byte*>(0),static_cast<const Ice::Byte*>(0));
+ pair<const Ice::Byte*, const Ice::Byte*> rb(static_cast<const Ice::Byte*>(0),
+ static_cast<const Ice::Byte*>(0));
if(!result.empty())
{
rb.first = &result[0];
@@ -1671,7 +1669,8 @@ IcePy::SyncTypedInvocation::invoke(PyObject* args, PyObject* /* kwds */)
// Unmarshal the results. If there is more than one value to be returned, then return them
// in a tuple of the form (result, outParam1, ...). Otherwise just return the value.
//
- pair<const Ice::Byte*, const Ice::Byte*> rb(static_cast<const Ice::Byte*>(0),static_cast<const Ice::Byte*>(0));
+ pair<const Ice::Byte*, const Ice::Byte*> rb(static_cast<const Ice::Byte*>(0),
+ static_cast<const Ice::Byte*>(0));
if(!result.empty())
{
rb.first = &result[0];
@@ -1886,7 +1885,7 @@ IcePy::AsyncTypedInvocation::invoke(PyObject* args, PyObject* /* kwds */)
}
assert(result);
- AsyncResultObject* obj = asyncResultNew(0);
+ AsyncResultObject* obj = asyncResultNew(&AsyncResultType, 0, 0);
if(!obj)
{
return 0;
@@ -2266,31 +2265,48 @@ IcePy::SyncBlobjectInvocation::invoke(PyObject* args, PyObject* /* kwds */)
PyObject* inParams;
PyObject* operationModeType = lookupType("Ice.OperationMode");
PyObject* ctx = 0;
+#if PY_VERSION_HEX >= 0x03000000
+ if(!PyArg_ParseTuple(args, STRCAST("sO!O!|O"), &operation, operationModeType, &mode, &PyBytes_Type, &inParams,
+ &ctx))
+ {
+ return 0;
+ }
+#else
if(!PyArg_ParseTuple(args, STRCAST("sO!O!|O"), &operation, operationModeType, &mode, &PyBuffer_Type, &inParams,
&ctx))
{
return 0;
}
+#endif
PyObjectHandle modeValue = PyObject_GetAttrString(mode, STRCAST("value"));
- Ice::OperationMode sendMode = (Ice::OperationMode)static_cast<int>(PyInt_AS_LONG(modeValue.get()));
+ Ice::OperationMode sendMode = (Ice::OperationMode)static_cast<int>(PyLong_AsLong(modeValue.get()));
+ assert(!PyErr_Occurred());
+#if PY_VERSION_HEX >= 0x03000000
+ Py_ssize_t sz = PyBytes_GET_SIZE(inParams);
+ pair<const ::Ice::Byte*, const ::Ice::Byte*> in(static_cast<const Ice::Byte*>(0),
+ static_cast<const Ice::Byte*>(0));
+ if(sz > 0)
+ {
+ in.first = reinterpret_cast<Ice::Byte*>(PyBytes_AS_STRING(inParams));
+ in.second = in.first + sz;
+ }
+#else
//
// Use the array API to avoid copying the data.
//
-#if PY_VERSION_HEX < 0x02050000
- const char* charBuf = 0;
-#else
char* charBuf = 0;
-#endif
Py_ssize_t sz = inParams->ob_type->tp_as_buffer->bf_getcharbuffer(inParams, 0, &charBuf);
const Ice::Byte* mem = reinterpret_cast<const Ice::Byte*>(charBuf);
- pair<const ::Ice::Byte*, const ::Ice::Byte*> in(static_cast<const Ice::Byte*>(0),static_cast<const Ice::Byte*>(0));
+ pair<const ::Ice::Byte*, const ::Ice::Byte*> in(static_cast<const Ice::Byte*>(0),
+ static_cast<const Ice::Byte*>(0));
if(sz > 0)
{
in.first = mem;
in.second = mem + sz;
}
+#endif
try
{
@@ -2328,11 +2344,26 @@ IcePy::SyncBlobjectInvocation::invoke(PyObject* args, PyObject* /* kwds */)
throwPythonException();
}
+#if PY_VERSION_HEX >= 0x03000000
+ PyObjectHandle op;
+ if(out.empty())
+ {
+ op = PyBytes_FromString("");
+ }
+ else
+ {
+ op = PyBytes_FromStringAndSize(reinterpret_cast<const char*>(&out[0]), out.size());
+ }
+ if(!op.get())
+ {
+ throwPythonException();
+ }
+#else
//
// Create the output buffer and copy in the outParams.
//
- PyObjectHandle ip = PyBuffer_New(out.size());
- if(!ip.get())
+ PyObjectHandle op = PyBuffer_New(out.size());
+ if(!op.get())
{
throwPythonException();
}
@@ -2340,18 +2371,19 @@ IcePy::SyncBlobjectInvocation::invoke(PyObject* args, PyObject* /* kwds */)
{
void* buf;
Py_ssize_t sz;
- if(PyObject_AsWriteBuffer(ip.get(), &buf, &sz))
+ if(PyObject_AsWriteBuffer(op.get(), &buf, &sz))
{
throwPythonException();
}
memcpy(buf, &out[0], sz);
}
+#endif
- if(PyTuple_SET_ITEM(result.get(), 1, ip.get()) < 0)
+ if(PyTuple_SET_ITEM(result.get(), 1, op.get()) < 0)
{
throwPythonException();
}
- ip.release(); // PyTuple_SET_ITEM steals a reference.
+ op.release(); // PyTuple_SET_ITEM steals a reference.
return result.release();
}
@@ -2403,16 +2435,25 @@ IcePy::AsyncBlobjectInvocation::invoke(PyObject* args, PyObject* kwds)
PyObject* ex = Py_None;
PyObject* sent = Py_None;
PyObject* pyctx = Py_None;
+#if PY_VERSION_HEX >= 0x03000000
+ if(!PyArg_ParseTupleAndKeywords(args, kwds, STRCAST("sO!O!|OOOO"), argNames, &operation, operationModeType, &mode,
+ &PyBytes_Type, &inParams, &response, &ex, &sent, &pyctx))
+ {
+ return 0;
+ }
+#else
if(!PyArg_ParseTupleAndKeywords(args, kwds, STRCAST("sO!O!|OOOO"), argNames, &operation, operationModeType, &mode,
&PyBuffer_Type, &inParams, &response, &ex, &sent, &pyctx))
{
return 0;
}
+#endif
_op = operation;
PyObjectHandle modeValue = PyObject_GetAttrString(mode, STRCAST("value"));
- Ice::OperationMode sendMode = (Ice::OperationMode)static_cast<int>(PyInt_AS_LONG(modeValue.get()));
+ Ice::OperationMode sendMode = (Ice::OperationMode)static_cast<int>(PyLong_AsLong(modeValue.get()));
+ assert(!PyErr_Occurred());
if(PyCallable_Check(response))
{
@@ -2460,22 +2501,30 @@ IcePy::AsyncBlobjectInvocation::invoke(PyObject* args, PyObject* kwds)
return 0;
}
+#if PY_VERSION_HEX >= 0x03000000
+ Py_ssize_t sz = PyBytes_GET_SIZE(inParams);
+ pair<const ::Ice::Byte*, const ::Ice::Byte*> in(static_cast<const Ice::Byte*>(0),
+ static_cast<const Ice::Byte*>(0));
+ if(sz > 0)
+ {
+ in.first = reinterpret_cast<Ice::Byte*>(PyBytes_AS_STRING(inParams));
+ in.second = in.first + sz;
+ }
+#else
//
// Use the array API to avoid copying the data.
//
-#if PY_VERSION_HEX < 0x02050000
- const char* charBuf = 0;
-#else
char* charBuf = 0;
-#endif
Py_ssize_t sz = inParams->ob_type->tp_as_buffer->bf_getcharbuffer(inParams, 0, &charBuf);
const Ice::Byte* mem = reinterpret_cast<const Ice::Byte*>(charBuf);
- pair<const ::Ice::Byte*, const ::Ice::Byte*> in(static_cast<const Ice::Byte*>(0),static_cast<const Ice::Byte*>(0));
+ pair<const ::Ice::Byte*, const ::Ice::Byte*> in(static_cast<const Ice::Byte*>(0),
+ static_cast<const Ice::Byte*>(0));
if(sz > 0)
{
in.first = mem;
in.second = mem + sz;
}
+#endif
Ice::AsyncResultPtr result;
try
@@ -2536,7 +2585,7 @@ IcePy::AsyncBlobjectInvocation::invoke(PyObject* args, PyObject* kwds)
}
assert(result);
- AsyncResultObject* obj = asyncResultNew(0);
+ AsyncResultObject* obj = asyncResultNew(&AsyncResultType, 0, 0);
if(!obj)
{
return 0;
@@ -2576,29 +2625,46 @@ IcePy::AsyncBlobjectInvocation::end(const Ice::ObjectPrx& proxy, const Ice::Asyn
return 0;
}
+#if PY_VERSION_HEX >= 0x03000000
+ Py_ssize_t sz = results.second - results.first;
+ PyObjectHandle op;
+ if(sz == 0)
+ {
+ op = PyBytes_FromString("");
+ }
+ else
+ {
+ op = PyBytes_FromStringAndSize(reinterpret_cast<const char*>(results.first), sz);
+ }
+ if(!op.get())
+ {
+ return 0;
+ }
+#else
//
// Create the output buffer and copy in the outParams.
//
- PyObjectHandle ip = PyBuffer_New(results.second - results.first);
- if(!ip.get())
+ PyObjectHandle op = PyBuffer_New(results.second - results.first);
+ if(!op.get())
{
return 0;
}
void* buf;
Py_ssize_t sz;
- if(PyObject_AsWriteBuffer(ip.get(), &buf, &sz))
+ if(PyObject_AsWriteBuffer(op.get(), &buf, &sz))
{
return 0;
}
assert(sz == results.second - results.first);
memcpy(buf, results.first, sz);
+#endif
- if(PyTuple_SET_ITEM(args.get(), 1, ip.get()) < 0)
+ if(PyTuple_SET_ITEM(args.get(), 1, op.get()) < 0)
{
return 0;
}
- ip.release(); // PyTuple_SET_ITEM steals a reference.
+ op.release(); // PyTuple_SET_ITEM steals a reference.
return args.release();
}
@@ -2644,11 +2710,29 @@ IcePy::AsyncBlobjectInvocation::response(bool ok, const pair<const Ice::Byte*, c
return;
}
+#if PY_VERSION_HEX >= 0x03000000
+ Py_ssize_t sz = results.second - results.first;
+ PyObjectHandle op;
+ if(sz == 0)
+ {
+ op = PyBytes_FromString("");
+ }
+ else
+ {
+ op = PyBytes_FromStringAndSize(reinterpret_cast<const char*>(results.first), sz);
+ }
+ if(!op.get())
+ {
+ assert(PyErr_Occurred());
+ PyErr_Print();
+ return;
+ }
+#else
//
// Create the output buffer and copy in the outParams.
//
- PyObjectHandle ip = PyBuffer_New(results.second - results.first);
- if(!ip.get())
+ PyObjectHandle op = PyBuffer_New(results.second - results.first);
+ if(!op.get())
{
assert(PyErr_Occurred());
PyErr_Print();
@@ -2657,7 +2741,7 @@ IcePy::AsyncBlobjectInvocation::response(bool ok, const pair<const Ice::Byte*, c
void* buf;
Py_ssize_t sz;
- if(PyObject_AsWriteBuffer(ip.get(), &buf, &sz))
+ if(PyObject_AsWriteBuffer(op.get(), &buf, &sz))
{
assert(PyErr_Occurred());
PyErr_Print();
@@ -2665,14 +2749,15 @@ IcePy::AsyncBlobjectInvocation::response(bool ok, const pair<const Ice::Byte*, c
}
assert(sz == results.second - results.first);
memcpy(buf, results.first, sz);
+#endif
- if(PyTuple_SET_ITEM(args.get(), 1, ip.get()) < 0)
+ if(PyTuple_SET_ITEM(args.get(), 1, op.get()) < 0)
{
assert(PyErr_Occurred());
PyErr_Print();
return;
}
- ip.release(); // PyTuple_SET_ITEM steals a reference.
+ op.release(); // PyTuple_SET_ITEM steals a reference.
PyObjectHandle tmp = PyObject_Call(_response, args.get(), 0);
if(PyErr_Occurred())
@@ -2723,34 +2808,51 @@ IcePy::OldAsyncBlobjectInvocation::invoke(PyObject* args, PyObject* /* kwds */)
PyObject* inParams;
PyObject* operationModeType = lookupType("Ice.OperationMode");
PyObject* ctx = 0;
+#if PY_VERSION_HEX >= 0x03000000
+ if(!PyArg_ParseTuple(args, STRCAST("OsO!O!|O"), &_callback, &operation, operationModeType, &mode,
+ &PyBytes_Type, &inParams, &ctx))
+ {
+ return 0;
+ }
+#else
if(!PyArg_ParseTuple(args, STRCAST("OsO!O!|O"), &_callback, &operation, operationModeType, &mode,
&PyBuffer_Type, &inParams, &ctx))
{
return 0;
}
+#endif
Py_INCREF(_callback);
_op = operation;
PyObjectHandle modeValue = PyObject_GetAttrString(mode, STRCAST("value"));
- Ice::OperationMode sendMode = (Ice::OperationMode)static_cast<int>(PyInt_AS_LONG(modeValue.get()));
+ Ice::OperationMode sendMode = (Ice::OperationMode)static_cast<int>(PyLong_AsLong(modeValue.get()));
+ assert(!PyErr_Occurred());
+#if PY_VERSION_HEX >= 0x03000000
+ Py_ssize_t sz = PyBytes_GET_SIZE(inParams);
+ pair<const ::Ice::Byte*, const ::Ice::Byte*> in(static_cast<const Ice::Byte*>(0),
+ static_cast<const Ice::Byte*>(0));
+ if(sz > 0)
+ {
+ in.first = reinterpret_cast<Ice::Byte*>(PyBytes_AS_STRING(inParams));
+ in.second = in.first + sz;
+ }
+#else
//
// Use the array API to avoid copying the data.
//
-#if PY_VERSION_HEX < 0x02050000
- const char* charBuf = 0;
-#else
char* charBuf = 0;
-#endif
Py_ssize_t sz = inParams->ob_type->tp_as_buffer->bf_getcharbuffer(inParams, 0, &charBuf);
const Ice::Byte* mem = reinterpret_cast<const Ice::Byte*>(charBuf);
- pair<const ::Ice::Byte*, const ::Ice::Byte*> in(static_cast<const Ice::Byte*>(0), static_cast<const Ice::Byte*>(0));
+ pair<const ::Ice::Byte*, const ::Ice::Byte*> in(static_cast<const Ice::Byte*>(0),
+ static_cast<const Ice::Byte*>(0));
if(sz > 0)
{
in.first = mem;
in.second = mem + sz;
}
+#endif
bool sentSynchronously = false;
try
@@ -2824,11 +2926,29 @@ IcePy::OldAsyncBlobjectInvocation::response(bool ok, const pair<const Ice::Byte*
return;
}
+#if PY_VERSION_HEX >= 0x03000000
+ Py_ssize_t sz = results.second - results.first;
+ PyObjectHandle op;
+ if(sz == 0)
+ {
+ op = PyBytes_FromString("");
+ }
+ else
+ {
+ op = PyBytes_FromStringAndSize(reinterpret_cast<const char*>(results.first), sz);
+ }
+ if(!op.get())
+ {
+ assert(PyErr_Occurred());
+ PyErr_Print();
+ return;
+ }
+#else
//
// Create the output buffer and copy in the outParams.
//
- PyObjectHandle ip = PyBuffer_New(results.second - results.first);
- if(!ip.get())
+ PyObjectHandle op = PyBuffer_New(results.second - results.first);
+ if(!op.get())
{
assert(PyErr_Occurred());
PyErr_Print();
@@ -2837,7 +2957,7 @@ IcePy::OldAsyncBlobjectInvocation::response(bool ok, const pair<const Ice::Byte*
void* buf;
Py_ssize_t sz;
- if(PyObject_AsWriteBuffer(ip.get(), &buf, &sz))
+ if(PyObject_AsWriteBuffer(op.get(), &buf, &sz))
{
assert(PyErr_Occurred());
PyErr_Print();
@@ -2845,14 +2965,15 @@ IcePy::OldAsyncBlobjectInvocation::response(bool ok, const pair<const Ice::Byte*
}
assert(sz == results.second - results.first);
memcpy(buf, results.first, sz);
+#endif
- if(PyTuple_SET_ITEM(args.get(), 1, ip.get()) < 0)
+ if(PyTuple_SET_ITEM(args.get(), 1, op.get()) < 0)
{
assert(PyErr_Occurred());
PyErr_Print();
return;
}
- ip.release(); // PyTuple_SET_ITEM steals a reference.
+ op.release(); // PyTuple_SET_ITEM steals a reference.
const string methodName = "ice_response";
if(!PyObject_HasAttrString(_callback, STRCAST(methodName.c_str())))
@@ -2967,7 +3088,7 @@ IcePy::TypedUpcall::dispatch(PyObject* servant, const pair<const Ice::Byte*, con
//
// Create the callback object and pass it as the first argument.
//
- AMDCallbackObject* obj = amdCallbackNew(0);
+ AMDCallbackObject* obj = amdCallbackNew(&AMDCallbackType, 0, 0);
if(!obj)
{
throwPythonException();
@@ -3109,7 +3230,8 @@ IcePy::TypedUpcall::response(PyObject* args)
Ice::ByteSeq bytes;
os->finished(bytes);
- pair<const Ice::Byte*, const Ice::Byte*> ob(static_cast<const Ice::Byte*>(0), static_cast<const Ice::Byte*>(0));
+ pair<const Ice::Byte*, const Ice::Byte*> ob(static_cast<const Ice::Byte*>(0),
+ static_cast<const Ice::Byte*>(0));
if(!bytes.empty())
{
ob.first = &bytes[0];
@@ -3188,7 +3310,8 @@ IcePy::TypedUpcall::exception(PyException& ex)
Ice::ByteSeq bytes;
os->finished(bytes);
- pair<const Ice::Byte*, const Ice::Byte*> ob(static_cast<const Ice::Byte*>(0),static_cast<const Ice::Byte*>(0));
+ pair<const Ice::Byte*, const Ice::Byte*> ob(static_cast<const Ice::Byte*>(0),
+ static_cast<const Ice::Byte*>(0));
if(!bytes.empty())
{
ob.first = &bytes[0];
@@ -3259,12 +3382,23 @@ IcePy::BlobjectUpcall::dispatch(PyObject* servant, const pair<const Ice::Byte*,
throwPythonException();
}
+ PyObjectHandle ip;
+
+#if PY_VERSION_HEX >= 0x03000000
+ if(inBytes.second == inBytes.first)
+ {
+ ip = PyBytes_FromString("");
+ }
+ else
+ {
+ ip = PyBytes_FromStringAndSize(reinterpret_cast<const char*>(inBytes.first), inBytes.second - inBytes.first);
+ }
+#else
//
// If using AMD we need to copy the bytes since the bytes may be
// accessed after this method is over, otherwise
// PyBuffer_FromMemory can be used which doesn't do a copy.
//
- PyObjectHandle ip;
if(!_amd)
{
ip = PyBuffer_FromMemory((void*)inBytes.first, inBytes.second - inBytes.first);
@@ -3289,6 +3423,7 @@ IcePy::BlobjectUpcall::dispatch(PyObject* servant, const pair<const Ice::Byte*,
assert(sz == inBytes.second - inBytes.first);
memcpy(buf, inBytes.first, sz);
}
+#endif
if(PyTuple_SET_ITEM(args.get(), start, ip.get()) < 0)
{
@@ -3315,7 +3450,7 @@ IcePy::BlobjectUpcall::dispatch(PyObject* servant, const pair<const Ice::Byte*,
//
// Create the callback object and pass it as the first argument.
//
- AMDCallbackObject* obj = amdCallbackNew(0);
+ AMDCallbackObject* obj = amdCallbackNew(&AMDCallbackType, 0, 0);
if(!obj)
{
throwPythonException();
@@ -3377,7 +3512,7 @@ IcePy::BlobjectUpcall::response(PyObject* args)
_finished = true;
//
- // The return value is a tuple of (bool, PyBuffer).
+ // The return value is a tuple of (bool, results).
//
if(!PyTuple_Check(args) || PyTuple_GET_SIZE(args) != 2)
{
@@ -3397,7 +3532,9 @@ IcePy::BlobjectUpcall::response(PyObject* args)
int isTrue = PyObject_IsTrue(arg);
arg = PyTuple_GET_ITEM(args, 1);
- if(!PyBuffer_Check(arg))
+
+#if PY_VERSION_HEX >= 0x03000000
+ if(!PyBytes_Check(arg))
{
ostringstream ostr;
ostr << "invalid return value for operation `ice_invoke'";
@@ -3406,17 +3543,31 @@ IcePy::BlobjectUpcall::response(PyObject* args)
throw Ice::MarshalException(__FILE__, __LINE__);
}
-#if PY_VERSION_HEX < 0x02050000
- const char* charBuf = 0;
+ Py_ssize_t sz = PyBytes_GET_SIZE(arg);
+ pair<const ::Ice::Byte*, const ::Ice::Byte*> r(static_cast<const Ice::Byte*>(0),static_cast<const Ice::Byte*>(0));
+ if(sz > 0)
+ {
+ r.first = reinterpret_cast<Ice::Byte*>(PyBytes_AS_STRING(arg));
+ r.second = r.first + sz;
+ }
#else
+ if(!PyBuffer_Check(arg))
+ {
+ ostringstream ostr;
+ ostr << "invalid return value for operation `ice_invoke'";
+ string str = ostr.str();
+ PyErr_Warn(PyExc_RuntimeWarning, const_cast<char*>(str.c_str()));
+ throw Ice::MarshalException(__FILE__, __LINE__);
+ }
+
char* charBuf = 0;
-#endif
Py_ssize_t sz = arg->ob_type->tp_as_buffer->bf_getcharbuffer(arg, 0, &charBuf);
const Ice::Byte* mem = reinterpret_cast<const Ice::Byte*>(charBuf);
- const pair<const ::Ice::Byte*, const ::Ice::Byte*> bytes(mem, mem + sz);
+ const pair<const ::Ice::Byte*, const ::Ice::Byte*> r(mem, mem + sz);
+#endif
AllowThreads allowThreads; // Release Python's global interpreter lock during blocking calls.
- _callback->ice_response(isTrue, bytes);
+ _callback->ice_response(isTrue, r);
}
void
@@ -3564,7 +3715,7 @@ IcePy::endIceInvoke(PyObject* proxy, PyObject* args)
PyObject*
IcePy::createAsyncResult(const Ice::AsyncResultPtr& r, PyObject* proxy, PyObject* connection, PyObject* communicator)
{
- AsyncResultObject* obj = asyncResultNew(0);
+ AsyncResultObject* obj = asyncResultNew(&AsyncResultType, 0, 0);
if(!obj)
{
return 0;
diff --git a/py/modules/IcePy/Properties.cpp b/py/modules/IcePy/Properties.cpp
index 039df377b75..77d68c664da 100644
--- a/py/modules/IcePy/Properties.cpp
+++ b/py/modules/IcePy/Properties.cpp
@@ -33,9 +33,9 @@ struct PropertiesObject
extern "C"
#endif
static PropertiesObject*
-propertiesNew(PyObject* /*arg*/)
+propertiesNew(PyTypeObject* type, PyObject* /*args*/, PyObject* /*kwds*/)
{
- PropertiesObject* self = PyObject_New(PropertiesObject, &PropertiesType);
+ PropertiesObject* self = reinterpret_cast<PropertiesObject*>(type->tp_alloc(type, 0));
if(!self)
{
return 0;
@@ -138,7 +138,7 @@ static void
propertiesDealloc(PropertiesObject* self)
{
delete self->properties;
- PyObject_Del(self);
+ Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
#ifdef WIN32
@@ -275,7 +275,7 @@ propertiesGetPropertyAsInt(PropertiesObject* self, PyObject* args)
return 0;
}
- return PyInt_FromLong(value);
+ return PyLong_FromLong(value);
}
#ifdef WIN32
@@ -309,7 +309,7 @@ propertiesGetPropertyAsIntWithDefault(PropertiesObject* self, PyObject* args)
return 0;
}
- return PyInt_FromLong(value);
+ return PyLong_FromLong(value);
}
#ifdef WIN32
@@ -709,8 +709,7 @@ PyTypeObject PropertiesType =
{
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
- PyObject_HEAD_INIT(0)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT(0, 0)
STRCAST("IcePy.Properties"), /* tp_name */
sizeof(PropertiesObject), /* tp_basicsize */
0, /* tp_itemsize */
@@ -719,7 +718,7 @@ PyTypeObject PropertiesType =
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
- 0, /* tp_compare */
+ 0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
@@ -774,7 +773,7 @@ IcePy::initProperties(PyObject* module)
PyObject*
IcePy::createProperties(const Ice::PropertiesPtr& props)
{
- PropertiesObject* obj = propertiesNew(0);
+ PropertiesObject* obj = propertiesNew(&PropertiesType, 0, 0);
if(obj)
{
obj->properties = new Ice::PropertiesPtr(props);
diff --git a/py/modules/IcePy/Proxy.cpp b/py/modules/IcePy/Proxy.cpp
index f7c67609c06..90df0035ad8 100644
--- a/py/modules/IcePy/Proxy.cpp
+++ b/py/modules/IcePy/Proxy.cpp
@@ -72,7 +72,7 @@ allocateProxy(const Ice::ObjectPrx& proxy, const Ice::CommunicatorPtr& communica
extern "C"
#endif
static ProxyObject*
-proxyNew(PyObject* /*arg*/)
+proxyNew(PyTypeObject* /*type*/, PyObject* /*args*/, PyObject* /*kwds*/)
{
PyErr_Format(PyExc_RuntimeError, STRCAST("A proxy cannot be created directly"));
return 0;
@@ -86,27 +86,63 @@ proxyDealloc(ProxyObject* self)
{
delete self->proxy;
delete self->communicator;
- self->ob_type->tp_free(self);
+ Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
#ifdef WIN32
extern "C"
#endif
-static int
-proxyCompare(ProxyObject* p1, ProxyObject* p2)
+static PyObject*
+proxyCompare(ProxyObject* p1, PyObject* other, int op)
{
- if(*p1->proxy < *p2->proxy)
- {
- return -1;
- }
- else if(*p1->proxy == *p2->proxy)
+ bool result;
+
+ if(PyObject_TypeCheck(other, &ProxyType))
{
- return 0;
+ ProxyObject* p2 = reinterpret_cast<ProxyObject*>(other);
+
+ switch(op)
+ {
+ case Py_EQ:
+ result = *p1->proxy == *p2->proxy;
+ break;
+ case Py_NE:
+ result = *p1->proxy != *p2->proxy;
+ break;
+ case Py_LE:
+ result = *p1->proxy <= *p2->proxy;
+ break;
+ case Py_GE:
+ result = *p1->proxy >= *p2->proxy;
+ break;
+ case Py_LT:
+ result = *p1->proxy < *p2->proxy;
+ break;
+ case Py_GT:
+ result = *p1->proxy > *p2->proxy;
+ break;
+ }
}
else
{
- return 1;
+ if(op == Py_EQ)
+ {
+ result = false;
+ }
+ else if(op == Py_NE)
+ {
+ result = true;
+ }
+ else
+ {
+ PyErr_Format(PyExc_TypeError, "can't compare %s to %s", Py_TYPE(p1)->tp_name, Py_TYPE(other)->tp_name);
+ return 0;
+ }
}
+
+ PyObject* r = result ? getTrue() : getFalse();
+ Py_INCREF(r);
+ return r;
}
#ifdef WIN32
@@ -504,7 +540,7 @@ proxyIceContext(ProxyObject* self, PyObject* args)
return 0;
}
- return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(self->ob_type));
+ return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(Py_TYPE(self)));
}
#ifdef WIN32
@@ -616,7 +652,7 @@ proxyIceAdapterId(ProxyObject* self, PyObject* args)
return 0;
}
- return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(self->ob_type));
+ return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(Py_TYPE(self)));
}
#ifdef WIN32
@@ -704,7 +740,7 @@ proxyIceEndpoints(ProxyObject* self, PyObject* args)
return 0;
}
- return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(self->ob_type));
+ return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(Py_TYPE(self)));
}
#ifdef WIN32
@@ -718,7 +754,7 @@ proxyIceGetLocatorCacheTimeout(ProxyObject* self)
try
{
Ice::Int timeout = (*self->proxy)->ice_getLocatorCacheTimeout();
- return PyInt_FromLong(timeout);
+ return PyLong_FromLong(timeout);
}
catch(const Ice::Exception& ex)
{
@@ -772,7 +808,7 @@ proxyIceLocatorCacheTimeout(ProxyObject* self, PyObject* args)
return 0;
}
- return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(self->ob_type));
+ return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(Py_TYPE(self)));
}
#ifdef WIN32
@@ -829,7 +865,7 @@ proxyIceConnectionCached(ProxyObject* self, PyObject* args)
return 0;
}
- return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(self->ob_type));
+ return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(Py_TYPE(self)));
}
#ifdef WIN32
@@ -917,7 +953,7 @@ proxyIceEndpointSelection(ProxyObject* self, PyObject* args)
return 0;
}
- return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(self->ob_type));
+ return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(Py_TYPE(self)));
}
#ifdef WIN32
@@ -974,8 +1010,7 @@ proxyIceSecure(ProxyObject* self, PyObject* args)
return 0;
}
- PyTypeObject* type = self->ob_type; // Necessary to prevent GCC's strict-alias warnings.
- return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(type));
+ return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(Py_TYPE(self)));
}
#ifdef WIN32
@@ -1032,7 +1067,7 @@ proxyIcePreferSecure(ProxyObject* self, PyObject* args)
return 0;
}
- return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(self->ob_type));
+ return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(Py_TYPE(self)));
}
#ifdef WIN32
@@ -1098,7 +1133,7 @@ proxyIceRouter(ProxyObject* self, PyObject* args)
return 0;
}
- return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(self->ob_type));
+ return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(Py_TYPE(self)));
}
#ifdef WIN32
@@ -1164,7 +1199,7 @@ proxyIceLocator(ProxyObject* self, PyObject* args)
return 0;
}
- return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(self->ob_type));
+ return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(Py_TYPE(self)));
}
#ifdef WIN32
@@ -1186,7 +1221,7 @@ proxyIceTwoway(ProxyObject* self)
return 0;
}
- return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(self->ob_type));
+ return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(Py_TYPE(self)));
}
#ifdef WIN32
@@ -1231,7 +1266,7 @@ proxyIceOneway(ProxyObject* self)
return 0;
}
- return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(self->ob_type));
+ return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(Py_TYPE(self)));
}
#ifdef WIN32
@@ -1276,7 +1311,7 @@ proxyIceBatchOneway(ProxyObject* self)
return 0;
}
- return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(self->ob_type));
+ return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(Py_TYPE(self)));
}
#ifdef WIN32
@@ -1321,7 +1356,7 @@ proxyIceDatagram(ProxyObject* self)
return 0;
}
- return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(self->ob_type));
+ return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(Py_TYPE(self)));
}
#ifdef WIN32
@@ -1366,7 +1401,7 @@ proxyIceBatchDatagram(ProxyObject* self)
return 0;
}
- return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(self->ob_type));
+ return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(Py_TYPE(self)));
}
#ifdef WIN32
@@ -1423,7 +1458,7 @@ proxyIceCompress(ProxyObject* self, PyObject* args)
return 0;
}
- return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(self->ob_type));
+ return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(Py_TYPE(self)));
}
#ifdef WIN32
@@ -1451,7 +1486,7 @@ proxyIceTimeout(ProxyObject* self, PyObject* args)
return 0;
}
- return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(self->ob_type));
+ return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(Py_TYPE(self)));
}
// NOTE: ice_collocationOptimized is not currently supported.
@@ -1487,7 +1522,7 @@ proxyIceConnectionId(ProxyObject* self, PyObject* args)
return 0;
}
- return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(self->ob_type));
+ return createProxy(newProxy, *self->communicator, reinterpret_cast<PyObject*>(Py_TYPE(self)));
}
#ifdef WIN32
@@ -1901,7 +1936,7 @@ proxyIceCheckedCast(PyObject* type, PyObject* args)
PyObject* facet = 0;
- if(PyString_Check(facetOrCtx))
+ if(checkString(facetOrCtx))
{
facet = facetOrCtx;
}
@@ -2013,7 +2048,7 @@ proxyCheckedCast(PyObject* /*self*/, PyObject* args)
if(arg1 != 0)
{
- if(!PyString_Check(arg1))
+ if(!checkString(arg1))
{
PyErr_Format(PyExc_ValueError, STRCAST("facet argument to checkedCast must be a string"));
return 0;
@@ -2030,7 +2065,7 @@ proxyCheckedCast(PyObject* /*self*/, PyObject* args)
}
else if(arg1 != 0 && arg1 != Py_None)
{
- if(PyString_Check(arg1))
+ if(checkString(arg1))
{
facet = arg1;
}
@@ -2238,33 +2273,37 @@ PyTypeObject ProxyType =
{
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
- PyObject_HEAD_INIT(0)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT(0, 0)
STRCAST("IcePy.ObjectPrx"), /* tp_name */
sizeof(ProxyObject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
- (destructor)proxyDealloc, /* tp_dealloc */
+ reinterpret_cast<destructor>(proxyDealloc), /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
- (cmpfunc)proxyCompare, /* tp_compare */
- (reprfunc)proxyRepr, /* tp_repr */
+ 0, /* tp_reserved */
+ reinterpret_cast<reprfunc>(proxyRepr), /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
- (hashfunc)proxyHash, /* tp_hash */
+ reinterpret_cast<hashfunc>(proxyHash), /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
+#if PY_VERSION_HEX >= 0x03000000
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+#else
Py_TPFLAGS_BASETYPE |
+ Py_TPFLAGS_HAVE_RICHCOMPARE |
Py_TPFLAGS_HAVE_CLASS, /* tp_flags */
+#endif
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
- 0, /* tp_richcompare */
+ reinterpret_cast<richcmpfunc>(proxyCompare), /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
@@ -2278,7 +2317,7 @@ PyTypeObject ProxyType =
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
- (newfunc)proxyNew, /* tp_new */
+ reinterpret_cast<newfunc>(proxyNew), /* tp_new */
0, /* tp_free */
0, /* tp_is_gc */
};
diff --git a/py/modules/IcePy/Slice.cpp b/py/modules/IcePy/Slice.cpp
index 7eb6b4b03aa..5d5575093ea 100644
--- a/py/modules/IcePy/Slice.cpp
+++ b/py/modules/IcePy/Slice.cpp
@@ -185,7 +185,11 @@ IcePy_loadSlice(PyObject* /*self*/, PyObject* args)
}
PyDict_SetItemString(globals.get(), "__builtins__", PyEval_GetBuiltins());
+#if PY_VERSION_HEX >= 0x03000000
+ PyObjectHandle val = PyEval_EvalCode(src.get(), globals.get(), 0);
+#else
PyObjectHandle val = PyEval_EvalCode(reinterpret_cast<PyCodeObject*>(src.get()), globals.get(), 0);
+#endif
if(!val.get())
{
return 0;
diff --git a/py/modules/IcePy/Types.cpp b/py/modules/IcePy/Types.cpp
index 2a491a75549..dfd043ebc47 100644
--- a/py/modules/IcePy/Types.cpp
+++ b/py/modules/IcePy/Types.cpp
@@ -82,11 +82,11 @@ writeString(PyObject* p, const Ice::OutputStreamPtr& os)
{
os->write(string());
}
- else if(PyString_Check(p))
+ else if(checkString(p))
{
- os->write(string(PyString_AS_STRING(p), PyString_GET_SIZE(p)));
+ os->write(getString(p));
}
-#ifdef Py_USING_UNICODE
+#if defined(Py_USING_UNICODE) && PY_VERSION_HEX < 0x03000000
else if(PyUnicode_Check(p))
{
//
@@ -98,7 +98,7 @@ writeString(PyObject* p, const Ice::OutputStreamPtr& os)
{
return false;
}
- os->write(string(PyString_AS_STRING(h.get()), PyString_GET_SIZE(h.get())), false);
+ os->write(getString(h.get()), false);
}
#endif
else
@@ -115,9 +115,9 @@ writeString(PyObject* p, const Ice::OutputStreamPtr& os)
extern "C"
#endif
static TypeInfoObject*
-typeInfoNew(PyObject* /*arg*/)
+typeInfoNew(PyTypeObject* type, PyObject* /*args*/, PyObject* /*kwds*/)
{
- TypeInfoObject* self = PyObject_New(TypeInfoObject, &TypeInfoType);
+ TypeInfoObject* self = reinterpret_cast<TypeInfoObject*>(type->tp_alloc(type, 0));
if(!self)
{
return 0;
@@ -133,16 +133,16 @@ static void
typeInfoDealloc(TypeInfoObject* self)
{
delete self->info;
- PyObject_Del(self);
+ Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
#ifdef WIN32
extern "C"
#endif
static ExceptionInfoObject*
-exceptionInfoNew(PyObject* /*arg*/)
+exceptionInfoNew(PyTypeObject* type, PyObject* /*args*/, PyObject* /*kwds*/)
{
- ExceptionInfoObject* self = PyObject_New(ExceptionInfoObject, &ExceptionInfoType);
+ ExceptionInfoObject* self = reinterpret_cast<ExceptionInfoObject*>(type->tp_alloc(type, 0));
if(!self)
{
return 0;
@@ -158,7 +158,7 @@ static void
exceptionInfoDealloc(ExceptionInfoObject* self)
{
delete self->info;
- PyObject_Del(self);
+ Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
//
@@ -306,25 +306,7 @@ IcePy::PrimitiveInfo::validate(PyObject* p)
}
case PrimitiveInfo::KindByte:
{
- long val;
- PyObjectHandle n = PyNumber_Int(p);
- if(n.get())
- {
- p = n.get();
- }
-
- if(PyInt_Check(p))
- {
- val = PyInt_AS_LONG(p);
- }
- else if(PyLong_Check(p))
- {
- val = PyLong_AsLong(p);
- }
- else
- {
- return false;
- }
+ long val = PyLong_AsLong(p);
if(PyErr_Occurred() || val < 0 || val > 255)
{
@@ -334,25 +316,7 @@ IcePy::PrimitiveInfo::validate(PyObject* p)
}
case PrimitiveInfo::KindShort:
{
- long val;
- PyObjectHandle n = PyNumber_Int(p);
- if(n.get())
- {
- p = n.get();
- }
-
- if(PyInt_Check(p))
- {
- val = PyInt_AS_LONG(p);
- }
- else if(PyLong_Check(p))
- {
- val = PyLong_AsLong(p);
- }
- else
- {
- return false;
- }
+ long val = PyLong_AsLong(p);
if(PyErr_Occurred() || val < SHRT_MIN || val > SHRT_MAX)
{
@@ -362,25 +326,7 @@ IcePy::PrimitiveInfo::validate(PyObject* p)
}
case PrimitiveInfo::KindInt:
{
- long val;
- PyObjectHandle n = PyNumber_Int(p);
- if(n.get())
- {
- p = n.get();
- }
-
- if(PyInt_Check(p))
- {
- val = PyInt_AS_LONG(p);
- }
- else if(PyLong_Check(p))
- {
- val = PyLong_AsLong(p);
- }
- else
- {
- return false;
- }
+ long val = PyLong_AsLong(p);
if(PyErr_Occurred() || val < INT_MIN || val > INT_MAX)
{
@@ -390,18 +336,8 @@ IcePy::PrimitiveInfo::validate(PyObject* p)
}
case PrimitiveInfo::KindLong:
{
- PyObjectHandle n = PyNumber_Long(p);
- if(n.get())
- {
- p = n.get();
- }
-
- if(PyErr_Occurred() || (!PyInt_Check(p) && !PyLong_Check(p)))
- {
- return false;
- }
+ PyLong_AsLongLong(p); // Just to see if it raises an error.
- PyLong_AsLongLong(p);
if(PyErr_Occurred())
{
return false;
@@ -412,24 +348,36 @@ IcePy::PrimitiveInfo::validate(PyObject* p)
case PrimitiveInfo::KindFloat:
case PrimitiveInfo::KindDouble:
{
- PyObjectHandle n = PyNumber_Float(p);
- if(n.get())
+ if(!PyFloat_Check(p))
{
- p = n.get();
+ if(PyLong_Check(p))
+ {
+ PyLong_AsDouble(p); // Just to see if it raises an error.
+ if(PyErr_Occurred())
+ {
+ return false;
+ }
+ }
+#if PY_VERSION_HEX < 0x03000000
+ else if(PyInt_Check(p))
+ {
+ return true;
+ }
+#endif
+ else
+ {
+ return false;
+ }
}
- if(!PyInt_Check(p) && !PyLong_Check(p) && !PyFloat_Check(p))
- {
- return false;
- }
break;
}
case PrimitiveInfo::KindString:
{
-#ifdef Py_USING_UNICODE
- if(p != Py_None && !PyString_Check(p) && !PyUnicode_Check(p))
+#if defined(Py_USING_UNICODE) && PY_VERSION_HEX < 0x03000000
+ if(p != Py_None && !checkString(p) && !PyUnicode_Check(p))
#else
- if(p != Py_None && !PyString_Check(p))
+ if(p != Py_None && !checkString(p))
#endif
{
return false;
@@ -458,26 +406,7 @@ IcePy::PrimitiveInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, Objec
}
case PrimitiveInfo::KindByte:
{
- long val = 0;
- PyObjectHandle n = PyNumber_Int(p);
- if(n.get())
- {
- p = n.get();
- }
-
- if(PyInt_Check(p))
- {
- val = PyInt_AS_LONG(p);
- }
- else if(PyLong_Check(p))
- {
- val = PyLong_AsLong(p);
- }
- else
- {
- assert(false); // validate() should have caught this.
- }
-
+ long val = PyLong_AsLong(p);
assert(!PyErr_Occurred()); // validate() should have caught this.
assert(val >= 0 && val <= 255); // validate() should have caught this.
os->write(static_cast<Ice::Byte>(val));
@@ -485,26 +414,7 @@ IcePy::PrimitiveInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, Objec
}
case PrimitiveInfo::KindShort:
{
- long val = 0;
- PyObjectHandle n = PyNumber_Int(p);
- if(n.get())
- {
- p = n.get();
- }
-
- if(PyInt_Check(p))
- {
- val = PyInt_AS_LONG(p);
- }
- else if(PyLong_Check(p))
- {
- val = PyLong_AsLong(p);
- }
- else
- {
- assert(false); // validate() should have caught this.
- }
-
+ long val = PyLong_AsLong(p);
assert(!PyErr_Occurred()); // validate() should have caught this.
assert(val >= SHRT_MIN && val <= SHRT_MAX); // validate() should have caught this.
os->write(static_cast<Ice::Short>(val));
@@ -512,26 +422,7 @@ IcePy::PrimitiveInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, Objec
}
case PrimitiveInfo::KindInt:
{
- long val = 0;
- PyObjectHandle n = PyNumber_Int(p);
- if(n.get())
- {
- p = n.get();
- }
-
- if(PyInt_Check(p))
- {
- val = PyInt_AS_LONG(p);
- }
- else if(PyLong_Check(p))
- {
- val = PyLong_AsLong(p);
- }
- else
- {
- assert(false); // validate() should have caught this.
- }
-
+ long val = PyLong_AsLong(p);
assert(!PyErr_Occurred()); // validate() should have caught this.
assert(val >= INT_MIN && val <= INT_MAX); // validate() should have caught this.
os->write(static_cast<Ice::Int>(val));
@@ -539,54 +430,17 @@ IcePy::PrimitiveInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, Objec
}
case PrimitiveInfo::KindLong:
{
- Ice::Long val = 0;
- PyObjectHandle n = PyNumber_Long(p);
- if(n.get())
- {
- p = n.get();
- }
-
- if(PyInt_Check(p))
- {
- val = PyInt_AS_LONG(p);
- }
- else if(PyLong_Check(p))
- {
- val = PyLong_AsLongLong(p);
- }
- else
- {
- assert(false); // validate() should have caught this.
- }
-
+ Ice::Long val = PyLong_AsLongLong(p);
assert(!PyErr_Occurred()); // validate() should have caught this.
os->write(val);
break;
}
case PrimitiveInfo::KindFloat:
{
- float val = 0;
- PyObjectHandle n = PyNumber_Float(p);
- if(n.get())
- {
- p = n.get();
- }
-
- if(PyFloat_Check(p))
- {
- val = static_cast<float>(PyFloat_AS_DOUBLE(p));
- }
- else if(PyInt_Check(p))
- {
- val = static_cast<float>(PyInt_AS_LONG(p));
- }
- else if(PyLong_Check(p))
- {
- val = static_cast<float>(PyLong_AsLongLong(p));
- }
- else
+ float val = static_cast<float>(PyFloat_AsDouble(p)); // Attempts to perform conversion.
+ if(PyErr_Occurred())
{
- assert(false); // validate() should have caught this.
+ throw AbortMarshaling();
}
os->write(val);
@@ -594,28 +448,10 @@ IcePy::PrimitiveInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, Objec
}
case PrimitiveInfo::KindDouble:
{
- double val = 0;
- PyObjectHandle n = PyNumber_Float(p);
- if(n.get())
- {
- p = n.get();
- }
-
- if(PyFloat_Check(p))
- {
- val = PyFloat_AS_DOUBLE(p);
- }
- else if(PyInt_Check(p))
- {
- val = static_cast<double>(PyInt_AS_LONG(p));
- }
- else if(PyLong_Check(p))
- {
- val = static_cast<double>(PyLong_AsLongLong(p));
- }
- else
+ double val = PyFloat_AsDouble(p); // Attempts to perform conversion.
+ if(PyErr_Occurred())
{
- assert(false);
+ throw AbortMarshaling();
}
os->write(val);
@@ -657,7 +493,7 @@ IcePy::PrimitiveInfo::unmarshal(const Ice::InputStreamPtr& is, const UnmarshalCa
{
Ice::Byte val;
is->read(val);
- PyObjectHandle p = PyInt_FromLong(val);
+ PyObjectHandle p = PyLong_FromLong(val);
cb->unmarshaled(p.get(), target, closure);
break;
}
@@ -665,7 +501,7 @@ IcePy::PrimitiveInfo::unmarshal(const Ice::InputStreamPtr& is, const UnmarshalCa
{
Ice::Short val;
is->read(val);
- PyObjectHandle p = PyInt_FromLong(val);
+ PyObjectHandle p = PyLong_FromLong(val);
cb->unmarshaled(p.get(), target, closure);
break;
}
@@ -673,7 +509,7 @@ IcePy::PrimitiveInfo::unmarshal(const Ice::InputStreamPtr& is, const UnmarshalCa
{
Ice::Int val;
is->read(val);
- PyObjectHandle p = PyInt_FromLong(val);
+ PyObjectHandle p = PyLong_FromLong(val);
cb->unmarshaled(p.get(), target, closure);
break;
}
@@ -705,7 +541,7 @@ IcePy::PrimitiveInfo::unmarshal(const Ice::InputStreamPtr& is, const UnmarshalCa
{
string val;
is->read(val);
- PyObjectHandle p = PyString_FromStringAndSize(val.c_str(), static_cast<Py_ssize_t>(val.size()));
+ PyObjectHandle p = createString(val);
cb->unmarshaled(p.get(), target, closure);
break;
}
@@ -725,8 +561,8 @@ IcePy::PrimitiveInfo::print(PyObject* value, IceUtilInternal::Output& out, Print
{
return;
}
- assert(PyString_Check(p.get()));
- out << PyString_AS_STRING(p.get());
+ assert(checkString(p.get()));
+ out << getString(p.get());
}
//
@@ -758,12 +594,16 @@ IcePy::EnumInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, ObjectMap*
assert(PyErr_Occurred());
throw AbortMarshaling();
}
+#if PY_VERSION_HEX >= 0x03000000
+ if(!PyLong_Check(val.get()))
+#else
if(!PyInt_Check(val.get()))
+#endif
{
PyErr_Format(PyExc_ValueError, STRCAST("value for enum %s is not an int"), id.c_str());
throw AbortMarshaling();
}
- Ice::Int ival = static_cast<Ice::Int>(PyInt_AsLong(val.get()));
+ Ice::Int ival = static_cast<Ice::Int>(PyLong_AsLong(val.get()));
Ice::Int count = static_cast<Ice::Int>(enumerators.size());
if(ival < 0 || ival >= count)
{
@@ -832,8 +672,8 @@ IcePy::EnumInfo::print(PyObject* value, IceUtilInternal::Output& out, PrintObjec
{
return;
}
- assert(PyString_Check(p.get()));
- out << PyString_AS_STRING(p.get());
+ assert(checkString(p.get()));
+ out << getString(p.get());
}
//
@@ -1192,10 +1032,23 @@ IcePy::SequenceInfo::marshalPrimitiveSequence(const PrimitiveInfoPtr& pi, PyObje
{
if(pi->kind == PrimitiveInfo::KindByte)
{
+#if PY_VERSION_HEX >= 0x03000000
//
- // Accept a string or a sequence for sequence<byte>.
+ // For sequence<byte>, accept a bytes object or a sequence.
//
- if(!PyString_Check(p))
+ if(!PyBytes_Check(p))
+ {
+ fs = PySequence_Fast(p, STRCAST("expected a bytes, sequence, or buffer value"));
+ if(!fs.get())
+ {
+ return;
+ }
+ }
+#else
+ //
+ // For sequence<byte>, accept a string or a sequence.
+ //
+ if(!checkString(p))
{
fs = PySequence_Fast(p, STRCAST("expected a string, sequence, or buffer value"));
if(!fs.get())
@@ -1203,6 +1056,7 @@ IcePy::SequenceInfo::marshalPrimitiveSequence(const PrimitiveInfoPtr& pi, PyObje
return;
}
}
+#endif
}
else
{
@@ -1244,10 +1098,17 @@ IcePy::SequenceInfo::marshalPrimitiveSequence(const PrimitiveInfoPtr& pi, PyObje
{
if(!fs.get())
{
+#if PY_VERSION_HEX >= 0x03000000
+ assert(PyBytes_Check(p));
+ char* str;
+ PyBytes_AsStringAndSize(p, &str, &sz);
+ os->write(reinterpret_cast<const Ice::Byte*>(str), reinterpret_cast<const Ice::Byte*>(str + sz));
+#else
assert(PyString_Check(p));
- const char* str = PyString_AS_STRING(p);
- sz = PyString_GET_SIZE(p);
+ char* str;
+ PyString_AsStringAndSize(p, &str, &sz);
os->write(reinterpret_cast<const Ice::Byte*>(str), reinterpret_cast<const Ice::Byte*>(str + sz));
+#endif
}
else
{
@@ -1262,21 +1123,7 @@ IcePy::SequenceInfo::marshalPrimitiveSequence(const PrimitiveInfoPtr& pi, PyObje
throw AbortMarshaling();
}
- long val = -1;
- PyObjectHandle n = PyNumber_Int(item);
- if(n.get())
- {
- item = n.get();
- }
-
- if(PyInt_Check(item))
- {
- val = PyInt_AS_LONG(item);
- }
- else if(PyLong_Check(item))
- {
- val = PyLong_AsLong(item);
- }
+ long val = PyLong_AsLong(item);
if(PyErr_Occurred() || val < 0 || val > 255)
{
@@ -1303,21 +1150,7 @@ IcePy::SequenceInfo::marshalPrimitiveSequence(const PrimitiveInfoPtr& pi, PyObje
throw AbortMarshaling();
}
- long val = SHRT_MIN - 1;
- PyObjectHandle n = PyNumber_Int(item);
- if(n.get())
- {
- item = n.get();
- }
-
- if(PyInt_Check(item))
- {
- val = PyInt_AS_LONG(item);
- }
- else if(PyLong_Check(item))
- {
- val = PyLong_AsLong(item);
- }
+ long val = PyLong_AsLong(item);
if(PyErr_Occurred() || val < SHRT_MIN || val > SHRT_MAX)
{
@@ -1343,27 +1176,7 @@ IcePy::SequenceInfo::marshalPrimitiveSequence(const PrimitiveInfoPtr& pi, PyObje
throw AbortMarshaling();
}
- long val;
- PyObjectHandle n = PyNumber_Int(item);
- if(n.get())
- {
- item = n.get();
- }
-
- if(PyInt_Check(item))
- {
- val = PyInt_AS_LONG(item);
- }
- else if(PyLong_Check(item))
- {
- val = PyLong_AsLong(item);
- }
- else
- {
- PyErr_Format(PyExc_ValueError, STRCAST("invalid value for element %d of sequence<int>"),
- static_cast<int>(i));
- throw AbortMarshaling();
- }
+ long val = PyLong_AsLong(item);
if(PyErr_Occurred() || val < INT_MIN || val > INT_MAX)
{
@@ -1389,27 +1202,7 @@ IcePy::SequenceInfo::marshalPrimitiveSequence(const PrimitiveInfoPtr& pi, PyObje
throw AbortMarshaling();
}
- Ice::Long val;
- PyObjectHandle n = PyNumber_Long(item);
- if(n.get())
- {
- item = n.get();
- }
-
- if(PyInt_Check(item))
- {
- val = PyInt_AS_LONG(item);
- }
- else if(PyLong_Check(item))
- {
- val = PyLong_AsLongLong(item);
- }
- else
- {
- PyErr_Format(PyExc_ValueError, STRCAST("invalid value for element %d of sequence<long>"),
- static_cast<int>(i));
- throw AbortMarshaling();
- }
+ Ice::Long val = PyLong_AsLongLong(item);
if(PyErr_Occurred())
{
@@ -1435,26 +1228,8 @@ IcePy::SequenceInfo::marshalPrimitiveSequence(const PrimitiveInfoPtr& pi, PyObje
throw AbortMarshaling();
}
- float val;
- PyObjectHandle n = PyNumber_Float(item);
- if(n.get())
- {
- item = n.get();
- }
-
- if(PyFloat_Check(item))
- {
- val = static_cast<float>(PyFloat_AS_DOUBLE(item));
- }
- else if(PyInt_Check(item))
- {
- val = static_cast<float>(PyInt_AS_LONG(item));
- }
- else if(PyLong_Check(item))
- {
- val = static_cast<float>(PyLong_AsLongLong(item));
- }
- else
+ float val = static_cast<float>(PyFloat_AsDouble(item));
+ if(PyErr_Occurred())
{
PyErr_Format(PyExc_ValueError, STRCAST("invalid value for element %d of sequence<float>"),
static_cast<int>(i));
@@ -1479,26 +1254,8 @@ IcePy::SequenceInfo::marshalPrimitiveSequence(const PrimitiveInfoPtr& pi, PyObje
throw AbortMarshaling();
}
- double val;
- PyObjectHandle n = PyNumber_Float(item);
- if(n.get())
- {
- item = n.get();
- }
-
- if(PyFloat_Check(item))
- {
- val = PyFloat_AS_DOUBLE(item);
- }
- else if(PyInt_Check(item))
- {
- val = static_cast<double>(PyInt_AS_LONG(item));
- }
- else if(PyLong_Check(item))
- {
- val = static_cast<double>(PyLong_AsLongLong(item));
- }
- else
+ double val = PyFloat_AsDouble(item);
+ if(PyErr_Occurred())
{
PyErr_Format(PyExc_ValueError, STRCAST("invalid value for element %d of sequence<double>"),
static_cast<int>(i));
@@ -1523,10 +1280,10 @@ IcePy::SequenceInfo::marshalPrimitiveSequence(const PrimitiveInfoPtr& pi, PyObje
throw AbortMarshaling();
}
-#ifdef Py_USING_UNICODE
- if(item != Py_None && !PyString_Check(item) && !PyUnicode_Check(item))
+#if defined(Py_USING_UNICODE) && PY_VERSION_HEX < 0x03000000
+ if(item != Py_None && !checkString(item) && !PyUnicode_Check(item))
#else
- if(item != Py_None && !PyString_Check(item))
+ if(item != Py_None && !checkString(item))
#endif
{
PyErr_Format(PyExc_ValueError, STRCAST("invalid value for element %d of sequence<string>"),
@@ -1580,7 +1337,11 @@ IcePy::SequenceInfo::unmarshalPrimitiveSequence(const PrimitiveInfoPtr& pi, cons
int sz = static_cast<int>(p.second - p.first);
if(sm->type == SequenceMapping::SEQ_DEFAULT)
{
+#if PY_VERSION_HEX >= 0x03000000
+ result = PyBytes_FromStringAndSize(reinterpret_cast<const char*>(p.first), sz);
+#else
result = PyString_FromStringAndSize(reinterpret_cast<const char*>(p.first), sz);
+#endif
if(!result.get())
{
assert(PyErr_Occurred());
@@ -1598,7 +1359,7 @@ IcePy::SequenceInfo::unmarshalPrimitiveSequence(const PrimitiveInfoPtr& pi, cons
for(int i = 0; i < sz; ++i)
{
- PyObjectHandle item = PyInt_FromLong(p.first[i]);
+ PyObjectHandle item = PyLong_FromLong(p.first[i]);
if(!item.get())
{
assert(PyErr_Occurred());
@@ -1624,7 +1385,7 @@ IcePy::SequenceInfo::unmarshalPrimitiveSequence(const PrimitiveInfoPtr& pi, cons
for(int i = 0; i < sz; ++i)
{
- PyObjectHandle item = PyInt_FromLong(p.first[i]);
+ PyObjectHandle item = PyLong_FromLong(p.first[i]);
if(!item.get())
{
assert(PyErr_Occurred());
@@ -1649,7 +1410,7 @@ IcePy::SequenceInfo::unmarshalPrimitiveSequence(const PrimitiveInfoPtr& pi, cons
for(int i = 0; i < sz; ++i)
{
- PyObjectHandle item = PyInt_FromLong(p.first[i]);
+ PyObjectHandle item = PyLong_FromLong(p.first[i]);
if(!item.get())
{
assert(PyErr_Occurred());
@@ -1748,7 +1509,7 @@ IcePy::SequenceInfo::unmarshalPrimitiveSequence(const PrimitiveInfoPtr& pi, cons
for(int i = 0; i < sz; ++i)
{
- PyObjectHandle item = PyString_FromStringAndSize(seq[i].c_str(), static_cast<Py_ssize_t>(seq[i].size()));
+ PyObjectHandle item = createString(seq[i]);
if(!item.get())
{
assert(PyErr_Occurred());
@@ -1895,9 +1656,14 @@ IcePy::CustomInfo::marshal(PyObject* p, const Ice::OutputStreamPtr& os, ObjectMa
throw AbortMarshaling();
}
- assert(PyString_Check(obj.get()));
- const char* str = PyString_AS_STRING(obj.get());
- Py_ssize_t sz = PyString_GET_SIZE(obj.get());
+ assert(checkString(obj.get()));
+ char* str;
+ Py_ssize_t sz;
+#if PY_VERSION_HEX >= 0x03000000
+ PyBytes_AsStringAndSize(obj.get(), &str, &sz);
+#else
+ PyString_AsStringAndSize(obj.get(), &str, &sz);
+#endif
os->write(reinterpret_cast<const Ice::Byte*>(str), reinterpret_cast<const Ice::Byte*>(str + sz));
}
@@ -1942,7 +1708,11 @@ IcePy::CustomInfo::unmarshal(const Ice::InputStreamPtr& is, const UnmarshalCallb
//
// Convert the seq to a string.
//
+#if PY_VERSION_HEX >= 0x03000000
+ obj = PyBytes_FromStringAndSize(reinterpret_cast<const char*>(seq.first), sz);
+#else
obj = PyString_FromStringAndSize(reinterpret_cast<const char*>(seq.first), sz);
+#endif
if(!obj.get())
{
assert(PyErr_Occurred());
@@ -2417,8 +2187,8 @@ IcePy::ProxyInfo::print(PyObject* value, IceUtilInternal::Output& out, PrintObje
{
return;
}
- assert(PyString_Check(p.get()));
- out << PyString_AS_STRING(p.get());
+ assert(checkString(p.get()));
+ out << getString(p.get());
}
}
@@ -2859,17 +2629,16 @@ PyTypeObject TypeInfoType =
{
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
- PyObject_HEAD_INIT(0)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT(0, 0)
STRCAST("IcePy.TypeInfo"), /* tp_name */
sizeof(TypeInfoObject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
- (destructor)typeInfoDealloc, /* tp_dealloc */
+ reinterpret_cast<destructor>(typeInfoDealloc), /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
- 0, /* tp_compare */
+ 0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
@@ -2898,7 +2667,7 @@ PyTypeObject TypeInfoType =
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
- (newfunc)typeInfoNew, /* tp_new */
+ reinterpret_cast<newfunc>(typeInfoNew), /* tp_new */
0, /* tp_free */
0, /* tp_is_gc */
};
@@ -2907,17 +2676,16 @@ PyTypeObject ExceptionInfoType =
{
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
- PyObject_HEAD_INIT(0)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT(0, 0)
STRCAST("IcePy.ExceptionInfo"), /* tp_name */
sizeof(ExceptionInfoObject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
- (destructor)exceptionInfoDealloc,/* tp_dealloc */
+ reinterpret_cast<destructor>(exceptionInfoDealloc), /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
- 0, /* tp_compare */
+ 0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
@@ -2946,7 +2714,7 @@ PyTypeObject ExceptionInfoType =
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
- (newfunc)exceptionInfoNew, /* tp_new */
+ reinterpret_cast<newfunc>(exceptionInfoNew), /* tp_new */
0, /* tp_free */
0, /* tp_is_gc */
};
@@ -3062,7 +2830,7 @@ IcePy::getType(PyObject* obj)
PyObject*
IcePy::createType(const TypeInfoPtr& info)
{
- TypeInfoObject* obj = typeInfoNew(0);
+ TypeInfoObject* obj = typeInfoNew(&TypeInfoType, 0, 0);
if(obj)
{
obj->info = new IcePy::TypeInfoPtr(info);
@@ -3081,7 +2849,7 @@ IcePy::getException(PyObject* obj)
PyObject*
IcePy::createException(const ExceptionInfoPtr& info)
{
- ExceptionInfoObject* obj = exceptionInfoNew(0);
+ ExceptionInfoObject* obj = exceptionInfoNew(&ExceptionInfoType, 0, 0);
if(obj)
{
obj->info = new IcePy::ExceptionInfoPtr(info);
@@ -3134,7 +2902,7 @@ convertDataMembers(PyObject* members, DataMemberList& l)
assert(PyTuple_GET_SIZE(m) == 3);
PyObject* name = PyTuple_GET_ITEM(m, 0); // Member name.
- assert(PyString_Check(name));
+ assert(checkString(name));
PyObject* meta = PyTuple_GET_ITEM(m, 1); // Member metadata.
assert(PyTuple_Check(meta));
PyObject* t = PyTuple_GET_ITEM(m, 2); // Member type.
diff --git a/py/modules/IcePy/Util.cpp b/py/modules/IcePy/Util.cpp
index ed611029b5c..24d0ab25354 100644
--- a/py/modules/IcePy/Util.cpp
+++ b/py/modules/IcePy/Util.cpp
@@ -24,12 +24,23 @@ using namespace Slice::Python;
string
IcePy::getString(PyObject* p)
{
- assert(p == Py_None || PyString_Check(p));
+ assert(p == Py_None || checkString(p));
string str;
if(p != Py_None)
{
+#if PY_VERSION_HEX >= 0x03000000
+ PyObjectHandle bytes = PyUnicode_AsUTF8String(p);
+ if(bytes.get())
+ {
+ char* s;
+ Py_ssize_t sz;
+ PyBytes_AsStringAndSize(bytes.get(), &s, &sz);
+ str.assign(s, sz);
+ }
+#else
str.assign(PyString_AS_STRING(p), PyString_GET_SIZE(p));
+#endif
}
return str;
}
@@ -37,7 +48,7 @@ IcePy::getString(PyObject* p)
bool
IcePy::getStringArg(PyObject* p, const string& arg, string& val)
{
- if(PyString_Check(p))
+ if(checkString(p))
{
val = getString(p);
}
@@ -185,9 +196,13 @@ IcePy::PyException::raise()
ostr << getTypeName();
IcePy::PyObjectHandle msg = PyObject_Str(ex.get());
- if(msg.get() && strlen(PyString_AsString(msg.get())) > 0)
+ if(msg.get())
{
- ostr << ": " << PyString_AsString(msg.get());
+ string s = getString(msg.get());
+ if(!s.empty())
+ {
+ ostr << ": " << s;
+ }
}
e.unknown = ostr.str();
@@ -238,13 +253,12 @@ IcePy::PyException::raiseLocalException()
IcePy::getIdentity(member.get(), e.id);
}
member = PyObject_GetAttrString(ex.get(), STRCAST("facet"));
- if(member.get() && PyString_Check(member.get()))
+ if(member.get() && checkString(member.get()))
{
- // TODO: Support unicode for the facet name.
e.facet = getString(member.get());
}
member = PyObject_GetAttrString(ex.get(), STRCAST("operation"));
- if(member.get() && PyString_Check(member.get()))
+ if(member.get() && checkString(member.get()))
{
e.operation = getString(member.get());
}
@@ -270,7 +284,7 @@ IcePy::PyException::raiseLocalException()
{
IcePy::PyObjectHandle member;
member = PyObject_GetAttrString(ex.get(), STRCAST("unknown"));
- if(member.get() && PyString_Check(member.get()))
+ if(member.get() && checkString(member.get()))
{
e.unknown = getString(member.get());
}
@@ -304,7 +318,7 @@ IcePy::PyException::getTraceback()
// import traceback
// list = traceback.format_exception(type, ex, tb)
//
- PyObjectHandle str = PyString_FromString("traceback");
+ PyObjectHandle str = createString("traceback");
PyObjectHandle mod = PyImport_Import(str.get());
assert(mod.get()); // Unable to import traceback module - Python installation error?
PyObject* d = PyModule_GetDict(mod.get());
@@ -316,7 +330,8 @@ IcePy::PyException::getTraceback()
string result;
for(Py_ssize_t i = 0; i < PyList_GET_SIZE(list.get()); ++i)
{
- result += PyString_AsString(PyList_GetItem(list.get(), i));
+ string s = getString(PyList_GetItem(list.get(), i));
+ result += s;
}
return result;
@@ -334,9 +349,9 @@ IcePy::PyException::getTypeName()
assert(name.get());
PyObjectHandle mod = PyObject_GetAttrString(cls, "__module__");
assert(mod.get());
- string result = PyString_AsString(mod.get());
+ string result = getString(mod.get());
result += ".";
- result += PyString_AsString(name.get());
+ result += getString(name.get());
return result;
}
@@ -374,7 +389,7 @@ IcePy::listToStringSeq(PyObject* l, Ice::StringSeq& seq)
return false;
}
string str;
- if(PyString_Check(item))
+ if(checkString(item))
{
str = getString(item);
}
@@ -428,7 +443,7 @@ IcePy::tupleToStringSeq(PyObject* t, Ice::StringSeq& seq)
return false;
}
string str;
- if(PyString_Check(item))
+ if(checkString(item))
{
str = getString(item);
}
@@ -454,7 +469,7 @@ IcePy::dictionaryToContext(PyObject* dict, Ice::Context& context)
while(PyDict_Next(dict, &pos, &key, &value))
{
string keystr;
- if(PyString_Check(key))
+ if(checkString(key))
{
keystr = getString(key);
}
@@ -465,7 +480,7 @@ IcePy::dictionaryToContext(PyObject* dict, Ice::Context& context)
}
string valuestr;
- if(PyString_Check(value))
+ if(checkString(value))
{
valuestr = getString(value);
}
@@ -650,20 +665,20 @@ convertLocalException(const Ice::LocalException& ex, PyObject* p)
}
catch(const Ice::FileException& e)
{
- IcePy::PyObjectHandle m = PyInt_FromLong(e.error);
+ IcePy::PyObjectHandle m = PyLong_FromLong(e.error);
PyObject_SetAttrString(p, STRCAST("error"), m.get());
m = IcePy::createString(e.path);
PyObject_SetAttrString(p, STRCAST("path"), m.get());
}
catch(const Ice::SyscallException& e) // This must appear after all subclasses of SyscallException.
{
- IcePy::PyObjectHandle m = PyInt_FromLong(e.error);
+ IcePy::PyObjectHandle m = PyLong_FromLong(e.error);
PyObject_SetAttrString(p, STRCAST("error"), m.get());
}
catch(const Ice::DNSException& e)
{
IcePy::PyObjectHandle m;
- m = PyInt_FromLong(e.error);
+ m = PyLong_FromLong(e.error);
PyObject_SetAttrString(p, STRCAST("error"), m.get());
m = IcePy::createString(e.host);
PyObject_SetAttrString(p, STRCAST("host"), m.get());
@@ -671,25 +686,25 @@ convertLocalException(const Ice::LocalException& ex, PyObject* p)
catch(const Ice::UnsupportedProtocolException& e)
{
IcePy::PyObjectHandle m;
- m = PyInt_FromLong(e.badMajor);
+ m = PyLong_FromLong(e.badMajor);
PyObject_SetAttrString(p, STRCAST("badMajor"), m.get());
- m = PyInt_FromLong(e.badMinor);
+ m = PyLong_FromLong(e.badMinor);
PyObject_SetAttrString(p, STRCAST("badMinor"), m.get());
- m = PyInt_FromLong(e.major);
+ m = PyLong_FromLong(e.major);
PyObject_SetAttrString(p, STRCAST("major"), m.get());
- m = PyInt_FromLong(e.minor);
+ m = PyLong_FromLong(e.minor);
PyObject_SetAttrString(p, STRCAST("minor"), m.get());
}
catch(const Ice::UnsupportedEncodingException& e)
{
IcePy::PyObjectHandle m;
- m = PyInt_FromLong(e.badMajor);
+ m = PyLong_FromLong(e.badMajor);
PyObject_SetAttrString(p, STRCAST("badMajor"), m.get());
- m = PyInt_FromLong(e.badMinor);
+ m = PyLong_FromLong(e.badMinor);
PyObject_SetAttrString(p, STRCAST("badMinor"), m.get());
- m = PyInt_FromLong(e.major);
+ m = PyLong_FromLong(e.major);
PyObject_SetAttrString(p, STRCAST("major"), m.get());
- m = PyInt_FromLong(e.minor);
+ m = PyLong_FromLong(e.minor);
PyObject_SetAttrString(p, STRCAST("minor"), m.get());
}
catch(const Ice::NoObjectFactoryException& e)
@@ -852,9 +867,9 @@ IcePy::handleSystemExit(PyObject* ex)
}
int status;
- if(PyInt_Check(code.get()))
+ if(PyLong_Check(code.get()))
{
- status = static_cast<int>(PyInt_AsLong(code.get()));
+ status = static_cast<int>(PyLong_AsLong(code.get()));
}
else
{
@@ -919,23 +934,21 @@ IcePy::getIdentity(PyObject* p, Ice::Identity& ident)
PyObjectHandle category = PyObject_GetAttrString(p, STRCAST("category"));
if(name.get())
{
- char* s = PyString_AsString(name.get());
- if(!s)
+ if(!checkString(name.get()))
{
PyErr_Format(PyExc_ValueError, STRCAST("identity name must be a string"));
return false;
}
- ident.name = s;
+ ident.name = getString(name.get());
}
if(category.get())
{
- char* s = PyString_AsString(category.get());
- if(!s)
+ if(!checkString(category.get()))
{
PyErr_Format(PyExc_ValueError, STRCAST("identity category must be a string"));
return false;
}
- ident.category = s;
+ ident.category = getString(category.get());
}
return true;
}
@@ -952,7 +965,7 @@ extern "C"
PyObject*
IcePy_intVersion(PyObject* /*self*/)
{
- return PyInt_FromLong(ICE_INT_VERSION);
+ return PyLong_FromLong(ICE_INT_VERSION);
}
extern "C"
diff --git a/py/modules/IcePy/Util.h b/py/modules/IcePy/Util.h
index 5520c1f07d9..5d390ccf88c 100644
--- a/py/modules/IcePy/Util.h
+++ b/py/modules/IcePy/Util.h
@@ -36,8 +36,13 @@ namespace IcePy
//
inline PyObject* getFalse()
{
+#if PY_VERSION_HEX >= 0x03000000
+ PyLongObject* i = &_Py_FalseStruct;
+ return reinterpret_cast<PyObject*>(i);
+#else
PyIntObject* i = &_Py_ZeroStruct;
return reinterpret_cast<PyObject*>(i);
+#endif
}
//
@@ -45,13 +50,28 @@ inline PyObject* getFalse()
//
inline PyObject* getTrue()
{
+#if PY_VERSION_HEX >= 0x03000000
+ PyLongObject* i = &_Py_TrueStruct;
+ return reinterpret_cast<PyObject*>(i);
+#else
PyIntObject* i = &_Py_TrueStruct;
return reinterpret_cast<PyObject*>(i);
+#endif
}
+//
+// Create a string object.
+//
inline PyObject* createString(const std::string& str)
{
+#if PY_VERSION_HEX >= 0x03000000
+ //
+ // PyUnicode_FromStringAndSize interprets the argument as UTF-8.
+ //
+ return PyUnicode_FromStringAndSize(str.c_str(), static_cast<Py_ssize_t>(str.size()));
+#else
return PyString_FromStringAndSize(str.c_str(), static_cast<Py_ssize_t>(str.size()));
+#endif
}
//
@@ -60,6 +80,18 @@ inline PyObject* createString(const std::string& str)
std::string getString(PyObject*);
//
+// Verify that the object is a string; None is NOT legal.
+//
+inline bool checkString(PyObject* p)
+{
+#if PY_VERSION_HEX >= 0x03000000
+ return PyUnicode_Check(p) ? true : false;
+#else
+ return PyString_Check(p) ? true : false;
+#endif
+}
+
+//
// Validate and retrieve a string argument; None is also legal.
//
bool getStringArg(PyObject*, const std::string&, std::string&);
diff --git a/py/python/Ice.py b/py/python/Ice.py
index 2bfb3123004..95f1e4c16f4 100644
--- a/py/python/Ice.py
+++ b/py/python/Ice.py
@@ -11,7 +11,7 @@
Ice module
"""
-import sys, exceptions, string, imp, os, threading, warnings, datetime
+import sys, string, imp, os, threading, warnings, datetime
#
# RTTI problems can occur in C++ code unless we modify Python's dlopen flags.
@@ -157,7 +157,7 @@ object.
#
# Exceptions.
#
-class Exception(exceptions.Exception):
+class Exception(Exception): # Derives from built-in base 'Exception' class.
'''The base class for all Ice exceptions.'''
def __str__(self):
return self.__class__.__name__
@@ -218,9 +218,10 @@ def getSliceDir():
_pendingModules = {}
def openModule(name):
- if sys.modules.has_key(name):
+ global _pendingModules
+ if name in sys.modules:
result = sys.modules[name]
- elif _pendingModules.has_key(name):
+ elif name in _pendingModules:
result = _pendingModules[name]
else:
result = createModule(name)
@@ -228,16 +229,17 @@ def openModule(name):
return result
def createModule(name):
- l = string.split(name, ".")
+ global _pendingModules
+ l = name.split(".")
curr = ''
mod = None
for s in l:
curr = curr + s
- if sys.modules.has_key(curr):
+ if curr in sys.modules:
mod = sys.modules[curr]
- elif _pendingModules.has_key(curr):
+ elif curr in _pendingModules:
mod = _pendingModules[curr]
else:
nmod = imp.new_module(curr)
@@ -249,19 +251,21 @@ def createModule(name):
return mod
def updateModule(name):
- if _pendingModules.has_key(name):
+ global _pendingModules
+ if name in _pendingModules:
pendingModule = _pendingModules[name]
mod = sys.modules[name]
mod.__dict__.update(pendingModule.__dict__)
del _pendingModules[name]
def updateModules():
+ global _pendingModules
for name in _pendingModules.keys():
- if sys.modules.has_key(name):
+ if name in sys.modules:
sys.modules[name].__dict__.update(_pendingModules[name].__dict__)
else:
sys.modules[name] = _pendingModules[name]
- del _pendingModules[name]
+ _pendingModules = {}
def createTempClass():
class __temp: pass
@@ -795,9 +799,9 @@ class CtrlCHandler(threading.Thread):
#
# Setup and install signal handlers
#
- if signal.__dict__.has_key('SIGHUP'):
+ if 'SIGHUP' in signal.__dict__:
signal.signal(signal.SIGHUP, CtrlCHandler.signalHandler)
- if signal.__dict__.has_key('SIGBREAK'):
+ if 'SIGBREAK' in signal.__dict__:
signal.signal(signal.SIGBREAK, CtrlCHandler.signalHandler)
signal.signal(signal.SIGINT, CtrlCHandler.signalHandler)
signal.signal(signal.SIGTERM, CtrlCHandler.signalHandler)
@@ -832,9 +836,9 @@ class CtrlCHandler(threading.Thread):
#
# Cleanup any state set by the CtrlCHandler.
#
- if signal.__dict__.has_key('SIGHUP'):
+ if 'SIGHUP' in signal.__dict__:
signal.signal(signal.SIGHUP, signal.SIG_DFL)
- if signal.__dict__.has_key('SIGBREAK'):
+ if 'SIGBREAK' in signal.__dict__:
signal.signal(signal.SIGBREAK, signal.SIG_DFL)
signal.signal(signal.SIGINT, signal.SIG_DFL)
signal.signal(signal.SIGTERM, signal.SIG_DFL)
@@ -1326,13 +1330,15 @@ def proxyIdentityCompare(lhs, rhs):
if (lhs and not isinstance(lhs, ObjectPrx)) or (rhs and not isinstance(rhs, ObjectPrx)):
raise ValueError('argument is not a proxy')
if not lhs and not rhs:
- return True
+ return 0
elif not lhs and rhs:
return -1
elif lhs and not rhs:
return 1
else:
- return cmp(lhs.ice_getIdentity(), rhs.ice_getIdentity())
+ lid = lhs.ice_getIdentity()
+ rid = rhs.ice_getIdentity()
+ return (lid > rid) - (lid < rid)
def proxyIdentityAndFacetEqual(lhs, rhs):
'''Determines whether the identities and facets of two
@@ -1344,12 +1350,34 @@ def proxyIdentityAndFacetCompare(lhs, rhs):
if (lhs and not isinstance(lhs, ObjectPrx)) or (rhs and not isinstance(rhs, ObjectPrx)):
raise ValueError('argument is not a proxy')
if not lhs and not rhs:
- return True
+ return 0
elif not lhs and rhs:
return -1
elif lhs and not rhs:
return 1
elif lhs.ice_getIdentity() != rhs.ice_getIdentity():
- return cmp(lhs.ice_getIdentity(), rhs.ice_getIdentity())
+ lid = lhs.ice_getIdentity()
+ rid = rhs.ice_getIdentity()
+ return (lid > rid) - (lid < rid)
else:
- return cmp(lhs.ice_getFacet(), rhs.ice_getFacet())
+ lf = lhs.ice_getFacet()
+ rf = rhs.ice_getFacet()
+ return (lf > rf) - (lf < rf)
+
+#
+# Used by generated code. Defining these in the Ice module means the generated code
+# can avoid the need to qualify the type() and hash() functions with their module
+# names. Since the functions are in the __builtin__ module (for Python 2.x) and the
+# builtins module (for Python 3.x), it's easier to define them here.
+#
+def getType(o):
+ return type(o)
+
+#
+# Used by generated code. Defining this in the Ice module means the generated code
+# can avoid the need to qualify the hash() function with its module name. Since
+# the function is in the __builtin__ module (for Python 2.x) and the builtins
+# module (for Python 3.x), it's easier to define it here.
+#
+def getHash(o):
+ return hash(o)
diff --git a/py/test/Ice/adapterDeactivation/AllTests.py b/py/test/Ice/adapterDeactivation/AllTests.py
index b422f6784d8..978db730867 100644
--- a/py/test/Ice/adapterDeactivation/AllTests.py
+++ b/py/test/Ice/adapterDeactivation/AllTests.py
@@ -14,20 +14,20 @@ def test(b):
raise RuntimeError('test assertion failed')
def allTests(communicator):
- print "testing stringToProxy... ",
+ sys.stdout.write("testing stringToProxy... ")
sys.stdout.flush()
base = communicator.stringToProxy("test:default -p 12010")
test(base)
- print "ok"
+ print("ok")
- print "testing checked cast... ",
+ sys.stdout.write("testing checked cast... ")
sys.stdout.flush()
obj = Test.TestIntfPrx.checkedCast(base)
test(obj)
test(obj == base)
- print "ok"
+ print("ok")
- print "creating/destroying/recreating object adapter... ",
+ sys.stdout.write("creating/destroying/recreating object adapter... ")
sys.stdout.flush()
adapter = communicator.createObjectAdapterWithEndpoints("TransientTestAdapter", "default")
try:
@@ -39,24 +39,24 @@ def allTests(communicator):
adapter = communicator.createObjectAdapterWithEndpoints("TransientTestAdapter", "default")
adapter.destroy()
- print "ok"
+ print("ok")
- print "creating/activating/deactivating object adapter in one operation... ",
+ sys.stdout.write("creating/activating/deactivating object adapter in one operation... ")
sys.stdout.flush()
obj.transient()
- print "ok"
+ print("ok")
- print "deactivating object adapter in the server... ",
+ sys.stdout.write("deactivating object adapter in the server... ")
sys.stdout.flush()
obj.deactivate()
- print "ok"
+ print("ok")
- print "testing whether server is gone... ",
+ sys.stdout.write("testing whether server is gone... ")
sys.stdout.flush()
try:
obj.ice_ping()
test(False)
except Ice.LocalException:
- print "ok"
+ print("ok")
return obj
diff --git a/py/test/Ice/adapterDeactivation/run.py b/py/test/Ice/adapterDeactivation/run.py
index 099ce110107..db68ff30b9a 100755
--- a/py/test/Ice/adapterDeactivation/run.py
+++ b/py/test/Ice/adapterDeactivation/run.py
@@ -16,10 +16,9 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
-sys.path.append(os.path.join(path[0]))
-from scripts import *
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0], "scripts"))
+import TestUtil
TestUtil.clientServerTest()
TestUtil.collocatedTest()
-
diff --git a/py/test/Ice/ami/AllTests.py b/py/test/Ice/ami/AllTests.py
index ae4dd376760..6c6bf83840c 100644
--- a/py/test/Ice/ami/AllTests.py
+++ b/py/test/Ice/ami/AllTests.py
@@ -7,7 +7,7 @@
#
# **********************************************************************
-import Ice, Test, threading, random
+import Ice, Test, sys, threading, random
def test(b):
if not b:
@@ -300,7 +300,8 @@ def allTests(communicator):
testController = Test.TestIntfControllerPrx.uncheckedCast(obj)
- print "testing begin/end invocation...",
+ sys.stdout.write("testing begin/end invocation... ")
+ sys.stdout.flush()
ctx = {}
result = p.begin_ice_isA("::Test::TestIntf")
@@ -346,9 +347,10 @@ def allTests(communicator):
except Test.TestIntfException:
pass
- print "ok"
+ print("ok")
- print "testing response callback...",
+ sys.stdout.write("testing response callback... ")
+ sys.stdout.flush()
ctx = {}
cb = ResponseCallback()
@@ -419,9 +421,10 @@ def allTests(communicator):
p.begin_opWithUE(lambda: cbWC.op(cookie), lambda ex: cbWC.opWithUE(ex, cookie), _ctx=ctx)
cbWC.check()
- print "ok"
+ print("ok")
- print "testing local exceptions...",
+ sys.stdout.write("testing local exceptions... ")
+ sys.stdout.flush()
indirect = Test.TestIntfPrx.uncheckedCast(p.ice_adapterId("dummy"))
@@ -454,9 +457,10 @@ def allTests(communicator):
except Ice.CommunicatorDestroyedException:
pass
- print "ok"
+ print("ok")
- print "testing local exceptions with response callback...",
+ sys.stdout.write("testing local exceptions with response callback... ")
+ sys.stdout.flush()
i = Test.TestIntfPrx.uncheckedCast(p.ice_adapterId("dummy"))
cb = ExceptionCallback()
@@ -488,9 +492,10 @@ def allTests(communicator):
i.begin_op(lambda: cbWC.response(cookie), lambda ex: cbWC.ex(ex, cookie))
cbWC.check()
- print "ok"
+ print("ok")
- print "testing exception callback...",
+ sys.stdout.write("testing exception callback... ")
+ sys.stdout.flush()
cb = ExceptionCallback()
cookie = 5
@@ -509,9 +514,10 @@ def allTests(communicator):
p.begin_opWithUE(lambda: cbWC.nullResponse(cookie), lambda ex: cbWC.opWithUE(ex, cookie))
cbWC.check()
- print "ok"
+ print("ok")
- print "testing sent callback...",
+ sys.stdout.write("testing sent callback... ")
+ sys.stdout.flush()
cb = SentCallback()
cookie = 5
@@ -546,26 +552,29 @@ def allTests(communicator):
cbWC.check()
cbs = []
- bytes = []
- bytes[0:1024] = range(0, 1024)
- bytes = [chr(random.randint(0, 255)) for x in bytes] # Make sure the request doesn't compress too well.
- seq = ''.join(bytes)
+ if sys.version_info[0] == 2:
+ b = [chr(random.randint(0, 255)) for x in range(0, 1024)] # Make sure the request doesn't compress too well.
+ seq = ''.join(b)
+ else:
+ b = [random.randint(0, 255) for x in range(0, 1024)] # Make sure the request doesn't compress too well.
+ seq = bytes(b)
testController.holdAdapter()
try:
cb = SentCallback()
while(p.begin_opWithPayload(seq, None, cb.ex, cb.sent).sentSynchronously()):
cbs.append(cb)
cb = SentCallback()
- except ex:
+ except Exception as ex:
testController.resumeAdapter()
raise ex
testController.resumeAdapter()
for r in cbs:
r.check()
- print "ok"
+ print("ok")
- print "testing illegal arguments...",
+ sys.stdout.write("testing illegal arguments... ")
+ sys.stdout.flush()
result = p.begin_op()
p.end_op(result)
@@ -582,9 +591,10 @@ def allTests(communicator):
except RuntimeError:
pass
- print "ok"
+ print("ok")
- print "testing unexpected exceptions from callback...",
+ sys.stdout.write("testing unexpected exceptions from callback... ")
+ sys.stdout.flush()
q = Test.TestIntfPrx.uncheckedCast(p.ice_adapterId("dummy"))
throwTypes = [ LocalException, UserException, OtherException ]
@@ -617,9 +627,10 @@ def allTests(communicator):
q.begin_op(None, lambda ex: cb.exWC(ex, cookie))
cb.check()
- print "ok"
+ print("ok")
- print "testing batch requests with proxy...",
+ sys.stdout.write("testing batch requests with proxy... ")
+ sys.stdout.flush()
cookie = 5
@@ -675,9 +686,10 @@ def allTests(communicator):
cb.check()
test(p.opBatchCount() == 0)
- print "ok"
+ print("ok")
- print "testing batch requests with connection...",
+ sys.stdout.write("testing batch requests with connection... ")
+ sys.stdout.flush()
cookie = 5
@@ -735,9 +747,10 @@ def allTests(communicator):
cb.check()
test(p.opBatchCount() == 0)
- print "ok"
+ print("ok")
- print "testing batch requests with communicator...",
+ sys.stdout.write("testing batch requests with communicator... ")
+ sys.stdout.flush()
#
# 1 connection.
@@ -825,9 +838,10 @@ def allTests(communicator):
test(r.isCompleted())
test(p.opBatchCount() == 0)
- print "ok"
+ print("ok")
- print "testing AsyncResult operations...",
+ sys.stdout.write("testing AsyncResult operations... ")
+ sys.stdout.flush()
indirect = Test.TestIntfPrx.uncheckedCast(p.ice_adapterId("dummy"))
r = indirect.begin_op()
@@ -843,10 +857,12 @@ def allTests(communicator):
r2 = None
try:
r1 = p.begin_op()
- bytes = []
- bytes[0:1024] = range(0, 1024)
- bytes = [chr(random.randint(0, 255)) for x in bytes] # Make sure the request doesn't compress too well.
- seq = ''.join(bytes)
+ if sys.version_info[0] == 2:
+ b = [chr(random.randint(0, 255)) for x in range(0, 1024)] # Make sure the request doesn't compress too well.
+ seq = ''.join(b)
+ else:
+ b = [random.randint(0, 255) for x in range(0, 1024)] # Make sure the request doesn't compress too well.
+ seq = bytes(b)
while(True):
r2 = p.begin_opWithPayload(seq)
if not r2.sentSynchronously():
@@ -859,7 +875,7 @@ def allTests(communicator):
(not r1.sentSynchronously() and not r1.isCompleted()));
test(not r2.sentSynchronously() and not r2.isCompleted());
- except ex:
+ except Exception as ex:
testController.resumeAdapter()
raise ex
testController.resumeAdapter()
@@ -933,6 +949,6 @@ def allTests(communicator):
test(r.getProxy() == None) # Expected
communicator.end_flushBatchRequests(r)
- print "ok"
+ print("ok")
p.shutdown()
diff --git a/py/test/Ice/ami/Client.py b/py/test/Ice/ami/Client.py
index d1325816e78..97383d6b389 100755
--- a/py/test/Ice/ami/Client.py
+++ b/py/test/Ice/ami/Client.py
@@ -14,7 +14,7 @@ import Ice
import Ice
slice_dir = Ice.getSliceDir()
if not slice_dir:
- print sys.argv[0] + ': Slice directory not found.'
+ print(sys.argv[0] + ': Slice directory not found.')
sys.exit(1)
Ice.loadSlice("'-I" + slice_dir + "' Test.ice")
diff --git a/py/test/Ice/ami/Server.py b/py/test/Ice/ami/Server.py
index deaa5356aa5..f231c277cb9 100755
--- a/py/test/Ice/ami/Server.py
+++ b/py/test/Ice/ami/Server.py
@@ -12,7 +12,7 @@ import os, sys, traceback
import Ice
slice_dir = Ice.getSliceDir()
if not slice_dir:
- print sys.argv[0] + ': Slice directory not found.'
+ print(sys.argv[0] + ': Slice directory not found.')
sys.exit(1)
Ice.loadSlice('"-I' + slice_dir + '" Test.ice')
diff --git a/py/test/Ice/ami/run.py b/py/test/Ice/ami/run.py
index 645839990d4..2265a40ca12 100755
--- a/py/test/Ice/ami/run.py
+++ b/py/test/Ice/ami/run.py
@@ -16,8 +16,8 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
-sys.path.append(os.path.join(path[0]))
-from scripts import *
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0], "scripts"))
+import TestUtil
TestUtil.clientServerTest()
diff --git a/py/test/Ice/application/Client.py b/py/test/Ice/application/Client.py
index be9d4dc9ea6..0641a7ddf0b 100755
--- a/py/test/Ice/application/Client.py
+++ b/py/test/Ice/application/Client.py
@@ -12,7 +12,7 @@ import sys, Ice, time
class Client(Ice.Application):
def interruptCallback(self, sig):
- print "handling signal " + str(sig)
+ print("handling signal " + str(sig))
# SIGINT interrupts time.sleep so a custom method is needed to
# sleep for a given interval.
@@ -26,32 +26,32 @@ class Client(Ice.Application):
def run(self, args):
self.ignoreInterrupt()
- print "Ignore CTRL+C and the like for 5 seconds (try it!)"
+ print("Ignore CTRL+C and the like for 5 seconds (try it!)")
self.sleep(5)
self.callbackOnInterrupt()
self.holdInterrupt()
- print "Hold CTRL+C and the like for 5 seconds (try it!)"
+ print("Hold CTRL+C and the like for 5 seconds (try it!)")
self.sleep(5)
self.releaseInterrupt()
- print "Release CTRL+C (any held signals should be released)"
+ print("Release CTRL+C (any held signals should be released)")
self.sleep(5)
self.holdInterrupt()
- print "Hold CTRL+C and the like for 5 seconds (try it!)"
+ print("Hold CTRL+C and the like for 5 seconds (try it!)")
self.sleep(5)
self.callbackOnInterrupt()
- print "Release CTRL+C (any held signals should be released)"
+ print("Release CTRL+C (any held signals should be released)")
self.sleep(5)
self.shutdownOnInterrupt()
- print "Test shutdown on destroy. Press CTRL+C to shutdown & terminate"
+ print("Test shutdown on destroy. Press CTRL+C to shutdown & terminate")
self.communicator().waitForShutdown()
- print "ok"
+ print("ok")
return False
app = Client()
diff --git a/py/test/Ice/binding/AllTests.py b/py/test/Ice/binding/AllTests.py
index 902926bca0b..b289818c88a 100644
--- a/py/test/Ice/binding/AllTests.py
+++ b/py/test/Ice/binding/AllTests.py
@@ -7,7 +7,7 @@
#
# **********************************************************************
-import Ice, Test, random, threading
+import Ice, Test, sys, random, threading
def test(b):
if not b:
@@ -61,7 +61,8 @@ def allTests(communicator):
ref = "communicator:default -p 12010"
com = Test.RemoteCommunicatorPrx.uncheckedCast(communicator.stringToProxy(ref))
- print "testing binding with single endpoint...",
+ sys.stdout.write("testing binding with single endpoint... ")
+ sys.stdout.flush()
adapter = com.createObjectAdapter("Adapter", "default")
@@ -84,9 +85,10 @@ def allTests(communicator):
except Ice.ConnectionRefusedException:
pass
- print "ok"
+ print("ok")
- print "testing binding with multiple endpoints...",
+ sys.stdout.write("testing binding with multiple endpoints... ")
+ sys.stdout.flush()
adapters = []
adapters.append(com.createObjectAdapter("Adapter11", "default"))
@@ -167,9 +169,10 @@ def allTests(communicator):
deactivate(com, adapters)
- print "ok"
+ print("ok")
- print "testing binding with multiple endpoints and AMI...",
+ sys.stdout.write("testing binding with multiple endpoints and AMI... ")
+ sys.stdout.flush()
adapters = []
adapters.append(com.createObjectAdapter("AdapterAMI11", "default"))
@@ -250,9 +253,10 @@ def allTests(communicator):
deactivate(com, adapters)
- print "ok"
+ print("ok")
- print "testing random endpoint selection...",
+ sys.stdout.write("testing random endpoint selection... ")
+ sys.stdout.flush()
adapters = []
adapters.append(com.createObjectAdapter("Adapter21", "default"))
@@ -283,9 +287,10 @@ def allTests(communicator):
deactivate(com, adapters)
- print "ok"
+ print("ok")
- print "testing ordered endpoint selection...",
+ sys.stdout.write("testing ordered endpoint selection... ")
+ sys.stdout.flush()
adapters = []
adapters.append(com.createObjectAdapter("Adapter31", "default"))
@@ -350,9 +355,10 @@ def allTests(communicator):
deactivate(com, adapters)
- print "ok"
+ print("ok")
- print "testing per request binding with single endpoint...",
+ sys.stdout.write("testing per request binding with single endpoint... ")
+ sys.stdout.flush()
adapter = com.createObjectAdapter("Adapter41", "default")
@@ -373,9 +379,10 @@ def allTests(communicator):
except Ice.ConnectionRefusedException:
pass
- print "ok"
+ print("ok")
- print "testing per request binding with multiple endpoints...",
+ sys.stdout.write("testing per request binding with multiple endpoints... ")
+ sys.stdout.flush()
adapters = []
adapters.append(com.createObjectAdapter("Adapter51", "default"))
@@ -406,9 +413,10 @@ def allTests(communicator):
deactivate(com, adapters)
- print "ok"
+ print("ok")
- print "testing per request binding with multiple endpoints and AMI...",
+ sys.stdout.write("testing per request binding with multiple endpoints and AMI... ")
+ sys.stdout.flush()
adapters = []
adapters.append(com.createObjectAdapter("AdapterAMI51", "default"))
@@ -439,9 +447,10 @@ def allTests(communicator):
deactivate(com, adapters)
- print "ok"
+ print("ok")
- print "testing per request binding and ordered endpoint selection...",
+ sys.stdout.write("testing per request binding and ordered endpoint selection... ")
+ sys.stdout.flush()
adapters = []
adapters.append(com.createObjectAdapter("Adapter61", "default"))
@@ -506,9 +515,10 @@ def allTests(communicator):
deactivate(com, adapters)
- print "ok"
+ print("ok")
- print "testing per request binding and ordered endpoint selection and AMI...",
+ sys.stdout.write("testing per request binding and ordered endpoint selection and AMI... ")
+ sys.stdout.flush()
adapters = []
adapters.append(com.createObjectAdapter("AdapterAMI61", "default"))
@@ -573,9 +583,10 @@ def allTests(communicator):
deactivate(com, adapters)
- print "ok"
+ print("ok")
- print "testing endpoint mode filtering...",
+ sys.stdout.write("testing endpoint mode filtering... ")
+ sys.stdout.flush()
adapters = []
adapters.append(com.createObjectAdapter("Adapter71", "default"))
@@ -591,10 +602,11 @@ def allTests(communicator):
except Ice.TwowayOnlyException:
pass
- print "ok"
+ print("ok")
if(len(communicator.getProperties().getProperty("Ice.Plugin.IceSSL")) > 0):
- print "testing unsecure vs. secure endpoints...",
+ sys.stdout.write("testing unsecure vs. secure endpoints... ")
+ sys.stdout.flush()
adapters = []
adapters.append(com.createObjectAdapter("Adapter81", "ssl"))
@@ -634,6 +646,6 @@ def allTests(communicator):
deactivate(com, adapters)
- print "ok"
+ print("ok")
com.shutdown()
diff --git a/py/test/Ice/binding/run.py b/py/test/Ice/binding/run.py
index 32ea526c3b4..2265a40ca12 100755
--- a/py/test/Ice/binding/run.py
+++ b/py/test/Ice/binding/run.py
@@ -16,9 +16,8 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
-sys.path.append(os.path.join(path[0]))
-from scripts import *
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0], "scripts"))
+import TestUtil
TestUtil.clientServerTest()
-
diff --git a/py/test/Ice/blobject/Client.py b/py/test/Ice/blobject/Client.py
index 24829f54511..14dd311f16b 100755
--- a/py/test/Ice/blobject/Client.py
+++ b/py/test/Ice/blobject/Client.py
@@ -40,7 +40,7 @@ def run(args, communicator, sync):
try:
Test.HelloPrx.checkedCast(communicator.stringToProxy("missing:default -p 12000 -t 10000"))
test(False)
- except Ice.UnknownLocalException, e:
+ except Ice.UnknownLocalException as e:
test(e.unknown.find('ConnectionRefusedException'))
if sync:
hello.shutdown()
@@ -54,10 +54,10 @@ try:
initData.properties.setProperty('Ice.Warn.Dispatch', '0')
communicator = Ice.initialize(argv, initData)
router = RouterI.RouterI(communicator, False)
- print "testing async blobject...",
+ sys.stdout.write("testing async blobject... ")
sys.stdout.flush()
status = run(sys.argv, communicator, False)
- print "ok"
+ print("ok")
router.destroy()
except:
traceback.print_exc()
@@ -77,10 +77,10 @@ if status:
initData.properties.setProperty('Ice.Warn.Dispatch', '0')
communicator = Ice.initialize(sys.argv, initData)
router = RouterI.RouterI(communicator, True)
- print "testing sync blobject...",
+ sys.stdout.write("testing sync blobject... ")
sys.stdout.flush()
status = run(sys.argv, communicator, True)
- print "ok"
+ print("ok")
router.destroy()
except:
traceback.print_exc()
diff --git a/py/test/Ice/blobject/RouterI.py b/py/test/Ice/blobject/RouterI.py
index 7942a286fb8..fdf6c7eba39 100644
--- a/py/test/Ice/blobject/RouterI.py
+++ b/py/test/Ice/blobject/RouterI.py
@@ -62,12 +62,12 @@ class BlobjectCall(object):
if len(self._curr.facet) > 0:
proxy = self._proxy.ice_facet(self._curr.facet)
- if self._curr.ctx.has_key("_fwd") and self._curr.ctx["_fwd"] == "o":
+ if "_fwd" in self._curr.ctx and self._curr.ctx["_fwd"] == "o":
proxy = proxy.ice_oneway()
try:
ok, out = proxy.ice_invoke(self._curr.operation, self._curr.mode, self._inParams, self._curr.ctx)
self._amdCallback.ice_response(ok, out)
- except Ice.Exception, e:
+ except Ice.Exception as e:
self._amdCallback.ice_exception(e)
else:
cb = AsyncCallback(self._amdCallback)
@@ -113,12 +113,12 @@ class BlobjectI(Ice.Blobject):
proxy = proxy.ice_facet(curr.facet)
try:
- if curr.ctx.has_key("_fwd") and curr.ctx["_fwd"] == "o":
+ if "_fwd" in curr.ctx and curr.ctx["_fwd"] == "o":
proxy = proxy.ice_oneway()
return proxy.ice_invoke(curr.operation, curr.mode, inParams, curr.ctx)
else:
return proxy.ice_invoke(curr.operation, curr.mode, inParams, curr.ctx)
- except Ice.Exception, e:
+ except Ice.Exception as e:
raise
def add(self, proxy):
diff --git a/py/test/Ice/blobject/run.py b/py/test/Ice/blobject/run.py
index c80260ad967..2265a40ca12 100755
--- a/py/test/Ice/blobject/run.py
+++ b/py/test/Ice/blobject/run.py
@@ -10,20 +10,14 @@
import os, sys
-# Skip the test if we're using python 2.3 and we're not on Mac.
-if sys.version_info[1] == 3 and sys.platform != 'darwin':
- print "Test skipped due to python 2.3"
- sys.exit(0)
-
path = [ ".", "..", "../..", "../../..", "../../../.." ]
head = os.path.dirname(sys.argv[0])
if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
-sys.path.append(os.path.join(path[0]))
-from scripts import *
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0], "scripts"))
+import TestUtil
TestUtil.clientServerTest()
-
diff --git a/py/test/Ice/checksum/AllTests.py b/py/test/Ice/checksum/AllTests.py
index 506191bb131..8e349a604b1 100644
--- a/py/test/Ice/checksum/AllTests.py
+++ b/py/test/Ice/checksum/AllTests.py
@@ -24,10 +24,11 @@ def allTests(communicator):
#
# Verify that no checksums are present for local types.
#
- print "testing checksums... ",
+ sys.stdout.write("testing checksums... ")
+ sys.stdout.flush()
test(len(Ice.sliceChecksums) > 0)
for i in Ice.sliceChecksums:
- test(string.find(i, "Local") == -1)
+ test(i.find("Local") == -1)
#
# Get server's Slice checksums.
@@ -46,13 +47,13 @@ def allTests(communicator):
if m:
n = int(i[m.start():])
- test(Ice.sliceChecksums.has_key(i))
+ test(i in Ice.sliceChecksums)
if n <= 1:
test(Ice.sliceChecksums[i] == d[i])
else:
test(Ice.sliceChecksums[i] != d[i])
- print "ok"
+ print("ok")
return checksum
diff --git a/py/test/Ice/checksum/Client.py b/py/test/Ice/checksum/Client.py
index 60c6f0a35f5..25d6f7dcee8 100755
--- a/py/test/Ice/checksum/Client.py
+++ b/py/test/Ice/checksum/Client.py
@@ -13,7 +13,7 @@ import os, sys, traceback
import Ice
slice_dir = Ice.getSliceDir()
if not slice_dir:
- print sys.argv[0] + ': Slice directory not found.'
+ print(sys.argv[0] + ': Slice directory not found.')
sys.exit(1)
Ice.loadSlice("'-I" + slice_dir + "' --checksum Test.ice CTypes.ice")
diff --git a/py/test/Ice/checksum/Server.py b/py/test/Ice/checksum/Server.py
index 4c2659bcb7a..b61b4c55697 100755
--- a/py/test/Ice/checksum/Server.py
+++ b/py/test/Ice/checksum/Server.py
@@ -13,7 +13,7 @@ import os, sys, traceback
import Ice
slice_dir = Ice.getSliceDir()
if not slice_dir:
- print sys.argv[0] + ': Slice directory not found.'
+ print(sys.argv[0] + ': Slice directory not found.')
sys.exit(1)
Ice.loadSlice("'-I" + slice_dir + "' --checksum Test.ice STypes.ice")
diff --git a/py/test/Ice/checksum/run.py b/py/test/Ice/checksum/run.py
index 32ea526c3b4..2265a40ca12 100755
--- a/py/test/Ice/checksum/run.py
+++ b/py/test/Ice/checksum/run.py
@@ -16,9 +16,8 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
-sys.path.append(os.path.join(path[0]))
-from scripts import *
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0], "scripts"))
+import TestUtil
TestUtil.clientServerTest()
-
diff --git a/py/test/Ice/custom/AllTests.py b/py/test/Ice/custom/AllTests.py
index fe407a26122..03046ab56f6 100644
--- a/py/test/Ice/custom/AllTests.py
+++ b/py/test/Ice/custom/AllTests.py
@@ -22,14 +22,22 @@ def allTests(communicator):
test(custom)
byteList = [1, 2, 3, 4, 5]
- byteString = ''.join(map(chr, byteList))
+ if sys.version_info[0] == 2:
+ byteString = ''.join(map(chr, byteList))
+ else:
+ byteString = bytes(byteList)
stringList = ['s1', 's2', 's3']
- print "testing custom sequences...",
+ sys.stdout.write("testing custom sequences... ")
+ sys.stdout.flush()
(r, b2) = custom.opByteString1(byteString)
- test(isinstance(r, str))
- test(isinstance(b2, str))
+ if sys.version_info[0] == 2:
+ test(isinstance(r, str))
+ test(isinstance(b2, str))
+ else:
+ test(isinstance(r, bytes))
+ test(isinstance(b2, bytes))
test(r == byteString)
test(b2 == byteString)
@@ -48,7 +56,10 @@ def allTests(communicator):
test(b2[i] == byteList[i])
(r, b2) = custom.opByteList2(byteList)
- test(isinstance(r, str))
+ if sys.version_info[0] == 2:
+ test(isinstance(r, str))
+ else:
+ test(isinstance(r, bytes))
test(isinstance(b2, tuple))
test(r == byteString)
for i in range(0, len(byteList)):
@@ -102,6 +113,6 @@ def allTests(communicator):
c.s4 = stringList;
custom.sendC(c)
- print "ok"
+ print("ok")
return custom
diff --git a/py/test/Ice/custom/Server.py b/py/test/Ice/custom/Server.py
index 22664625afa..65ef09e80d0 100755
--- a/py/test/Ice/custom/Server.py
+++ b/py/test/Ice/custom/Server.py
@@ -20,7 +20,10 @@ def test(b):
class CustomI(Test.Custom):
def opByteString1(self, b1, current=None):
- test(isinstance(b1, str))
+ if sys.version_info[0] == 2:
+ test(isinstance(b1, str))
+ else:
+ test(isinstance(b1, bytes))
return (b1, b1)
def opByteString2(self, b1, current=None):
@@ -52,9 +55,15 @@ class CustomI(Test.Custom):
return (s1, s1)
def sendS(self, val, current=None):
- test(isinstance(val.b1, str))
+ if sys.version_info[0] == 2:
+ test(isinstance(val.b1, str))
+ else:
+ test(isinstance(val.b1, bytes))
test(isinstance(val.b2, list))
- test(isinstance(val.b3, str))
+ if sys.version_info[0] == 2:
+ test(isinstance(val.b3, str))
+ else:
+ test(isinstance(val.b3, bytes))
test(isinstance(val.b4, list))
test(isinstance(val.s1, list))
test(isinstance(val.s2, tuple))
@@ -62,9 +71,15 @@ class CustomI(Test.Custom):
test(isinstance(val.s4, list))
def sendC(self, val, current=None):
- test(isinstance(val.b1, str))
+ if sys.version_info[0] == 2:
+ test(isinstance(val.b1, str))
+ else:
+ test(isinstance(val.b1, bytes))
test(isinstance(val.b2, list))
- test(isinstance(val.b3, str))
+ if sys.version_info[0] == 2:
+ test(isinstance(val.b3, str))
+ else:
+ test(isinstance(val.b3, bytes))
test(isinstance(val.b4, list))
test(isinstance(val.s1, list))
test(isinstance(val.s2, tuple))
diff --git a/py/test/Ice/custom/run.py b/py/test/Ice/custom/run.py
index 32ea526c3b4..2265a40ca12 100755
--- a/py/test/Ice/custom/run.py
+++ b/py/test/Ice/custom/run.py
@@ -16,9 +16,8 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
-sys.path.append(os.path.join(path[0]))
-from scripts import *
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0], "scripts"))
+import TestUtil
TestUtil.clientServerTest()
-
diff --git a/py/test/Ice/defaultServant/AllTests.py b/py/test/Ice/defaultServant/AllTests.py
index cfa82a9048a..8dfde7db6c4 100644
--- a/py/test/Ice/defaultServant/AllTests.py
+++ b/py/test/Ice/defaultServant/AllTests.py
@@ -7,7 +7,7 @@
#
# **********************************************************************
-import Ice, Test, MyObjectI
+import Ice, Test, MyObjectI, sys
def test(b):
if not b:
@@ -24,7 +24,8 @@ def allTests(communicator):
oa.addDefaultServant(servant, "foo")
# Start test
- print "testing single category... ",
+ sys.stdout.write("testing single category... ")
+ sys.stdout.flush()
r = oa.findDefaultServant("foo")
test(r == servant)
@@ -103,9 +104,10 @@ def allTests(communicator):
# Expected
pass
- print "ok"
+ print("ok")
- print "testing default category... ",
+ sys.stdout.write("testing default category... ")
+ sys.stdout.flush()
oa.addDefaultServant(servant, "")
@@ -121,4 +123,4 @@ def allTests(communicator):
prx.ice_ping()
test(prx.getName() == names[idx])
- print "ok"
+ print("ok")
diff --git a/py/test/Ice/defaultServant/run.py b/py/test/Ice/defaultServant/run.py
index 08d8d6cd828..f75ac017c4d 100755
--- a/py/test/Ice/defaultServant/run.py
+++ b/py/test/Ice/defaultServant/run.py
@@ -16,14 +16,14 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
-sys.path.append(os.path.join(path[0]))
-from scripts import *
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0], "scripts"))
+import TestUtil
-print "starting client...",
+sys.stdout.write("starting client... ")
+sys.stdout.flush()
clientProc = TestUtil.startClient("Client.py", startReader = False)
-print "ok"
+print("ok")
clientProc.startReader()
clientProc.waitTestSuccess()
-
diff --git a/py/test/Ice/defaultValue/AllTests.py b/py/test/Ice/defaultValue/AllTests.py
index eb9c6eefca7..64967566cdb 100644
--- a/py/test/Ice/defaultValue/AllTests.py
+++ b/py/test/Ice/defaultValue/AllTests.py
@@ -7,7 +7,7 @@
#
# **********************************************************************
-import Ice, Test
+import Ice, Test, sys
def test(b):
if not b:
@@ -15,7 +15,8 @@ def test(b):
def allTests():
- print "testing default values...",
+ sys.stdout.write("testing default values... ")
+ sys.stdout.flush()
v = Test.Struct1()
test(not v.boolFalse)
@@ -147,4 +148,4 @@ def allTests():
test(v.zeroD == 0)
test(v.zeroDotD == 0)
- print "ok"
+ print("ok")
diff --git a/py/test/Ice/defaultValue/run.py b/py/test/Ice/defaultValue/run.py
index 16a6b09aaa5..f75ac017c4d 100755
--- a/py/test/Ice/defaultValue/run.py
+++ b/py/test/Ice/defaultValue/run.py
@@ -16,13 +16,14 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
-sys.path.append(os.path.join(path[0]))
-from scripts import *
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0], "scripts"))
+import TestUtil
-print "starting client...",
+sys.stdout.write("starting client... ")
+sys.stdout.flush()
clientProc = TestUtil.startClient("Client.py", startReader = False)
-print "ok"
+print("ok")
clientProc.startReader()
clientProc.waitTestSuccess()
diff --git a/py/test/Ice/exceptions/AllTests.py b/py/test/Ice/exceptions/AllTests.py
index c89c4b27851..7b373f1c105 100644
--- a/py/test/Ice/exceptions/AllTests.py
+++ b/py/test/Ice/exceptions/AllTests.py
@@ -60,7 +60,7 @@ class AMI_Thrower_throwAasAI(CallbackBase):
def ice_exception(self, ex):
try:
raise ex
- except Test.A, ex:
+ except Test.A as ex:
test(ex.aMem == 1)
except:
test(False)
@@ -77,7 +77,7 @@ class AMI_Thrower_throwAasAObjectNotExistI(CallbackBase):
def ice_exception(self, ex):
try:
raise ex
- except Ice.ObjectNotExistException, ex:
+ except Ice.ObjectNotExistException as ex:
id = self._communicator.stringToIdentity("does not exist")
test(ex.id == id)
except:
@@ -91,7 +91,7 @@ class AMI_Thrower_throwAasAFacetNotExistI(CallbackBase):
def ice_exception(self, ex):
try:
raise ex
- except Ice.FacetNotExistException, ex:
+ except Ice.FacetNotExistException as ex:
test(ex.facet == "no such facet")
except:
test(False)
@@ -104,9 +104,9 @@ class AMI_Thrower_throwAorDasAorDI(CallbackBase):
def ice_exception(self, ex):
try:
raise ex
- except Test.A, ex:
+ except Test.A as ex:
test(ex.aMem == 1)
- except Test.D, ex:
+ except Test.D as ex:
test(ex.dMem == -1)
except:
test(False)
@@ -119,7 +119,7 @@ class AMI_Thrower_throwBasAI(CallbackBase):
def ice_exception(self, ex):
try:
raise ex
- except Test.B, ex:
+ except Test.B as ex:
test(ex.aMem == 1)
test(ex.bMem == 2)
except:
@@ -133,7 +133,7 @@ class AMI_Thrower_throwCasAI(CallbackBase):
def ice_exception(self, ex):
try:
raise ex
- except Test.C, ex:
+ except Test.C as ex:
test(ex.aMem == 1)
test(ex.bMem == 2)
test(ex.cMem == 3)
@@ -148,7 +148,7 @@ class AMI_Thrower_throwBasBI(CallbackBase):
def ice_exception(self, ex):
try:
raise ex
- except Test.B, ex:
+ except Test.B as ex:
test(ex.aMem == 1)
test(ex.bMem == 2)
except:
@@ -162,7 +162,7 @@ class AMI_Thrower_throwCasBI(CallbackBase):
def ice_exception(self, ex):
try:
raise ex
- except Test.C, ex:
+ except Test.C as ex:
test(ex.aMem == 1)
test(ex.bMem == 2)
test(ex.cMem == 3)
@@ -177,7 +177,7 @@ class AMI_Thrower_throwCasCI(CallbackBase):
def ice_exception(self, ex):
try:
raise ex
- except Test.C, ex:
+ except Test.C as ex:
test(ex.aMem == 1)
test(ex.bMem == 2)
test(ex.cMem == 3)
@@ -192,7 +192,7 @@ class AMI_Thrower_throwModAI(CallbackBase):
def ice_exception(self, ex):
try:
raise ex
- except Test.Mod.A, ex:
+ except Test.Mod.A as ex:
test(ex.aMem == 1)
test(ex.a2Mem == 2)
except Ice.OperationNotExistException:
@@ -276,7 +276,7 @@ class AMI_WrongOperation_noSuchOperationI(CallbackBase):
def ice_exception(self, ex):
try:
raise ex
- except Ice.OperationNotExistException, ex:
+ except Ice.OperationNotExistException as ex:
test(ex.operation == "noSuchOperation")
except:
test(False)
@@ -298,9 +298,9 @@ class Callback(CallbackBase):
def exception_AorDasAorD(self, ex):
try:
raise ex
- except Test.A, ex:
+ except Test.A as ex:
test(ex.aMem == 1)
- except Test.D, ex:
+ except Test.D as ex:
test(ex.dMem == -1)
except:
test(False)
@@ -309,7 +309,7 @@ class Callback(CallbackBase):
def exception_BasB(self, ex):
try:
raise ex
- except Test.B, ex:
+ except Test.B as ex:
test(ex.aMem == 1)
test(ex.bMem == 2)
except:
@@ -319,7 +319,7 @@ class Callback(CallbackBase):
def exception_CasC(self, ex):
try:
raise ex
- except Test.C, ex:
+ except Test.C as ex:
test(ex.aMem == 1)
test(ex.bMem == 2)
test(ex.cMem == 3)
@@ -330,7 +330,7 @@ class Callback(CallbackBase):
def exception_ModA(self, ex):
try:
raise ex
- except Test.Mod.A, ex:
+ except Test.Mod.A as ex:
test(ex.aMem == 1)
test(ex.a2Mem == 2)
except Ice.OperationNotExistException:
@@ -345,7 +345,7 @@ class Callback(CallbackBase):
def exception_BasA(self, ex):
try:
raise ex
- except Test.B, ex:
+ except Test.B as ex:
test(ex.aMem == 1)
test(ex.bMem == 2)
except:
@@ -355,7 +355,7 @@ class Callback(CallbackBase):
def exception_CasA(self, ex):
try:
raise ex
- except Test.C, ex:
+ except Test.C as ex:
test(ex.aMem == 1)
test(ex.bMem == 2)
test(ex.cMem == 3)
@@ -366,7 +366,7 @@ class Callback(CallbackBase):
def exception_CasB(self, ex):
try:
raise ex
- except Test.C, ex:
+ except Test.C as ex:
test(ex.aMem == 1)
test(ex.bMem == 2)
test(ex.cMem == 3)
@@ -404,7 +404,7 @@ class Callback(CallbackBase):
def exception_AasAObjectNotExist(self, ex):
try:
raise ex
- except Ice.ObjectNotExistException, ex:
+ except Ice.ObjectNotExistException as ex:
id = self._communicator.stringToIdentity("does not exist")
test(ex.id == id)
except:
@@ -414,7 +414,7 @@ class Callback(CallbackBase):
def exception_AasAFacetNotExist(self, ex):
try:
raise ex
- except Ice.FacetNotExistException, ex:
+ except Ice.FacetNotExistException as ex:
test(ex.facet == "no such facet")
except:
test(False)
@@ -423,7 +423,7 @@ class Callback(CallbackBase):
def exception_noSuchOperation(self, ex):
try:
raise ex
- except Ice.OperationNotExistException, ex:
+ except Ice.OperationNotExistException as ex:
test(ex.operation == "noSuchOperation")
except:
test(False)
@@ -432,7 +432,7 @@ class Callback(CallbackBase):
def exception_LocalException(self, ex):
try:
raise ex
- except Ice.UnknownLocalException, ex:
+ except Ice.UnknownLocalException as ex:
pass
except:
test(False)
@@ -441,14 +441,15 @@ class Callback(CallbackBase):
def exception_NonIceException(self, ex):
try:
raise ex
- except Ice.UnknownException, ex:
+ except Ice.UnknownException as ex:
pass
except:
test(False)
self.called()
def allTests(communicator):
- print "testing servant registration exceptions...",
+ sys.stdout.write("testing servant registration exceptions... ")
+ sys.stdout.flush()
communicator.getProperties().setProperty("TestAdapter1.Endpoints", "default")
adapter = communicator.createObjectAdapter("TestAdapter1")
obj = EmptyI()
@@ -467,9 +468,10 @@ def allTests(communicator):
pass
adapter.deactivate()
- print "ok"
+ print("ok")
- print "testing servant locator registrations exceptions...",
+ sys.stdout.write("testing servant locator registrations exceptions... ")
+ sys.stdout.flush()
communicator.getProperties().setProperty("TestAdapter2.Endpoints", "default")
adapter = communicator.createObjectAdapter("TestAdapter2")
loc = ServantLocatorI()
@@ -481,9 +483,10 @@ def allTests(communicator):
pass
adapter.deactivate()
- print "ok"
+ print("ok")
- print "testing object factory registration exception...",
+ sys.stdout.write("testing object factory registration exception... ")
+ sys.stdout.flush()
of = ObjectFactoryI()
communicator.addObjectFactory(of, "x")
try:
@@ -491,74 +494,77 @@ def allTests(communicator):
test(false)
except Ice.AlreadyRegisteredException:
pass
- print "ok"
+ print("ok")
- print "testing stringToProxy...",
+ sys.stdout.write("testing stringToProxy... ")
+ sys.stdout.flush()
ref = "thrower:default -p 12010"
base = communicator.stringToProxy(ref)
test(base)
- print "ok"
+ print("ok")
- print "testing checked cast...",
+ sys.stdout.write("testing checked cast... ")
+ sys.stdout.flush()
thrower = Test.ThrowerPrx.checkedCast(base)
test(thrower)
test(thrower == base)
- print "ok"
+ print("ok")
- print "catching exact types...",
+ sys.stdout.write("catching exact types... ")
+ sys.stdout.flush()
try:
thrower.throwAasA(1)
test(False)
- except Test.A, ex:
+ except Test.A as ex:
test(ex.aMem == 1)
except:
- print sys.exc_info()
+ print(sys.exc_info())
test(False)
try:
thrower.throwAorDasAorD(1)
test(False)
- except Test.A, ex:
+ except Test.A as ex:
test(ex.aMem == 1)
except:
- print sys.exc_info()
+ print(sys.exc_info())
test(False)
try:
thrower.throwAorDasAorD(-1)
test(False)
- except Test.D, ex:
+ except Test.D as ex:
test(ex.dMem == -1)
except:
- print sys.exc_info()
+ print(sys.exc_info())
test(False)
try:
thrower.throwBasB(1, 2)
test(False)
- except Test.B, ex:
+ except Test.B as ex:
test(ex.aMem == 1)
test(ex.bMem == 2)
except:
- print sys.exc_info()
+ print(sys.exc_info())
test(False)
try:
thrower.throwCasC(1, 2, 3)
test(False)
- except Test.C, ex:
+ except Test.C as ex:
test(ex.aMem == 1)
test(ex.bMem == 2)
test(ex.cMem == 3)
except:
- print sys.exc_info()
+ print(sys.exc_info())
test(False)
try:
thrower.throwModA(1, 2)
test(False)
- except Test.Mod.A, ex:
+ except Test.Mod.A as ex:
test(ex.aMem == 1)
test(ex.a2Mem == 2)
except Ice.OperationNotExistException:
@@ -567,36 +573,37 @@ def allTests(communicator):
#
pass
except:
- print sys.exc_info()
+ print(sys.exc_info())
test(False)
- print "ok"
+ print("ok")
- print "catching base types...",
+ sys.stdout.write("catching base types... ")
+ sys.stdout.flush()
try:
thrower.throwBasB(1, 2)
test(False)
- except Test.A, ex:
+ except Test.A as ex:
test(ex.aMem == 1)
except:
- print sys.exc_info()
+ print(sys.exc_info())
test(False)
try:
thrower.throwCasC(1, 2, 3)
test(False)
- except Test.B, ex:
+ except Test.B as ex:
test(ex.aMem == 1)
test(ex.bMem == 2)
except:
- print sys.exc_info()
+ print(sys.exc_info())
test(False)
try:
thrower.throwModA(1, 2)
test(False)
- except Test.A, ex:
+ except Test.A as ex:
test(ex.aMem == 1)
except Ice.OperationNotExistException:
#
@@ -604,49 +611,51 @@ def allTests(communicator):
#
pass
except:
- print sys.exc_info()
+ print(sys.exc_info())
test(False)
- print "ok"
+ print("ok")
- print "catching derived types...",
+ sys.stdout.write("catching derived types... ")
+ sys.stdout.flush()
try:
thrower.throwBasA(1, 2)
test(False)
- except Test.B, ex:
+ except Test.B as ex:
test(ex.aMem == 1)
test(ex.bMem == 2)
except:
- print sys.exc_info()
+ print(sys.exc_info())
test(False)
try:
thrower.throwCasA(1, 2, 3)
test(False)
- except Test.C, ex:
+ except Test.C as ex:
test(ex.aMem == 1)
test(ex.bMem == 2)
test(ex.cMem == 3)
except:
- print sys.exc_info()
+ print(sys.exc_info())
test(False)
try:
thrower.throwCasB(1, 2, 3)
test(False)
- except Test.C, ex:
+ except Test.C as ex:
test(ex.aMem == 1)
test(ex.bMem == 2)
test(ex.cMem == 3)
except:
- print sys.exc_info()
+ print(sys.exc_info())
test(False)
- print "ok"
+ print("ok")
if thrower.supportsUndeclaredExceptions():
- print "catching unknown user exception...",
+ sys.stdout.write("catching unknown user exception... ")
+ sys.stdout.flush()
try:
thrower.throwUndeclaredA(1)
@@ -654,7 +663,7 @@ def allTests(communicator):
except Ice.UnknownUserException:
pass
except:
- print sys.exc_info()
+ print(sys.exc_info())
test(False)
try:
@@ -663,7 +672,7 @@ def allTests(communicator):
except Ice.UnknownUserException:
pass
except:
- print sys.exc_info()
+ print(sys.exc_info())
test(False)
try:
@@ -672,12 +681,13 @@ def allTests(communicator):
except Ice.UnknownUserException:
pass
except:
- print sys.exc_info()
+ print(sys.exc_info())
test(False)
- print "ok"
+ print("ok")
- print "catching object not exist exception...",
+ sys.stdout.write("catching object not exist exception... ")
+ sys.stdout.flush()
id = communicator.stringToIdentity("does not exist")
try:
@@ -685,44 +695,47 @@ def allTests(communicator):
thrower2.throwAasA(1)
# thrower2.ice_ping()
test(False)
- except Ice.ObjectNotExistException, ex:
+ except Ice.ObjectNotExistException as ex:
test(ex.id == id)
except:
- print sys.exc_info()
+ print(sys.exc_info())
test(False)
- print "ok"
+ print("ok")
- print "catching facet not exist exception...",
+ sys.stdout.write("catching facet not exist exception... ")
+ sys.stdout.flush()
try:
thrower2 = Test.ThrowerPrx.uncheckedCast(thrower, "no such facet")
try:
thrower2.ice_ping()
test(False)
- except Ice.FacetNotExistException, ex:
+ except Ice.FacetNotExistException as ex:
test(ex.facet == "no such facet")
except:
- print sys.exc_info()
+ print(sys.exc_info())
test(False)
- print "ok"
+ print("ok")
- print "catching operation not exist exception...",
+ sys.stdout.write("catching operation not exist exception... ")
+ sys.stdout.flush()
try:
thrower2 = Test.WrongOperationPrx.uncheckedCast(thrower)
thrower2.noSuchOperation()
test(False)
- except Ice.OperationNotExistException, ex:
+ except Ice.OperationNotExistException as ex:
test(ex.operation == "noSuchOperation")
except:
- print sys.exc_info()
+ print(sys.exc_info())
test(False)
- print "ok"
+ print("ok")
- print "catching unknown local exception...",
+ sys.stdout.write("catching unknown local exception... ")
+ sys.stdout.flush()
try:
thrower.throwLocalException()
@@ -730,12 +743,13 @@ def allTests(communicator):
except Ice.UnknownLocalException:
pass
except:
- print sys.exc_info()
+ print(sys.exc_info())
test(False)
- print "ok"
+ print("ok")
- print "catching unknown non-Ice exception...",
+ sys.stdout.write("catching unknown non-Ice exception... ")
+ sys.stdout.flush()
try:
thrower.throwNonIceException()
@@ -743,17 +757,18 @@ def allTests(communicator):
except Ice.UnknownException:
pass
except:
- print sys.exc_info()
+ print(sys.exc_info())
test(False)
- print "ok"
+ print("ok")
- print "testing asynchronous exceptions...",
+ sys.stdout.write("testing asynchronous exceptions... ")
+ sys.stdout.flush()
try:
thrower.throwAfterResponse()
except:
- print sys.exc_info()
+ print(sys.exc_info())
test(False)
try:
@@ -761,12 +776,13 @@ def allTests(communicator):
except Test.A:
pass
except:
- print sys.exc_info()
+ print(sys.exc_info())
test(False)
- print "ok"
+ print("ok")
- print "catching exact types with AMI...",
+ sys.stdout.write("catching exact types with AMI... ")
+ sys.stdout.flush()
cb = AMI_Thrower_throwAasAI()
thrower.throwAasA_async(cb, 1)
@@ -798,9 +814,10 @@ def allTests(communicator):
thrower.throwModA_async(cb, 1, 2)
cb.check()
- print "ok"
+ print("ok")
- print "catching derived types...",
+ sys.stdout.write("catching derived types... ")
+ sys.stdout.flush()
cb = AMI_Thrower_throwBasAI()
thrower.throwBasA_async(cb, 1, 2)
@@ -814,10 +831,11 @@ def allTests(communicator):
thrower.throwCasB_async(cb, 1, 2, 3)
cb.check()
- print "ok"
+ print("ok")
if thrower.supportsUndeclaredExceptions():
- print "catching unknown user exception with AMI...",
+ sys.stdout.write("catching unknown user exception with AMI... ")
+ sys.stdout.flush()
cb = AMI_Thrower_throwUndeclaredAI()
thrower.throwUndeclaredA_async(cb, 1)
@@ -831,9 +849,10 @@ def allTests(communicator):
thrower.throwUndeclaredC_async(cb, 1, 2, 3)
cb.check()
- print "ok"
+ print("ok")
- print "catching object not exist exception with AMI...",
+ sys.stdout.write("catching object not exist exception with AMI... ")
+ sys.stdout.flush()
id = communicator.stringToIdentity("does not exist")
thrower2 = Test.ThrowerPrx.uncheckedCast(thrower.ice_identity(id))
@@ -841,43 +860,48 @@ def allTests(communicator):
thrower2.throwAasA_async(cb, 1)
cb.check()
- print "ok"
+ print("ok")
- print "catching facet not exist exception with AMI...",
+ sys.stdout.write("catching facet not exist exception with AMI... ")
+ sys.stdout.flush()
thrower2 = Test.ThrowerPrx.uncheckedCast(thrower, "no such facet")
cb = AMI_Thrower_throwAasAFacetNotExistI()
thrower2.throwAasA_async(cb, 1)
cb.check()
- print "ok"
+ print("ok")
- print "catching operation not exist exception with AMI...",
+ sys.stdout.write("catching operation not exist exception with AMI... ")
+ sys.stdout.flush()
cb = AMI_WrongOperation_noSuchOperationI()
thrower4 = Test.WrongOperationPrx.uncheckedCast(thrower)
thrower4.noSuchOperation_async(cb)
cb.check()
- print "ok"
+ print("ok")
- print "catching unknown local exception with AMI...",
+ sys.stdout.write("catching unknown local exception with AMI... ")
+ sys.stdout.flush()
cb = AMI_Thrower_throwLocalExceptionI()
thrower.throwLocalException_async(cb)
cb.check()
- print "ok"
+ print("ok")
- print "catching unknown non-Ice exception with AMI...",
+ sys.stdout.write("catching unknown non-Ice exception with AMI... ")
+ sys.stdout.flush()
cb = AMI_Thrower_throwNonIceExceptionI()
thrower.throwNonIceException_async(cb)
cb.check()
- print "ok"
+ print("ok")
- print "catching exact types with new AMI mapping...",
+ sys.stdout.write("catching exact types with new AMI mapping... ")
+ sys.stdout.flush()
cb = Callback()
thrower.begin_throwAasA(1, cb.response, cb.exception_AasA)
@@ -903,9 +927,10 @@ def allTests(communicator):
thrower.begin_throwModA(1, 2, cb.response, cb.exception_ModA)
cb.check()
- print "ok"
+ print("ok")
- print "catching derived types with new AMI mapping...",
+ sys.stdout.write("catching derived types with new AMI mapping... ")
+ sys.stdout.flush()
cb = Callback()
thrower.begin_throwBasA(1, 2, cb.response, cb.exception_BasA)
@@ -919,10 +944,11 @@ def allTests(communicator):
thrower.begin_throwCasB(1, 2, 3, cb.response, cb.exception_CasB)
cb.check()
- print "ok"
+ print("ok")
if thrower.supportsUndeclaredExceptions():
- print "catching unknown user exception with new AMI mapping...",
+ sys.stdout.write("catching unknown user exception with new AMI mapping... ")
+ sys.stdout.flush()
cb = Callback()
thrower.begin_throwUndeclaredA(1, cb.response, cb.exception_UndeclaredA)
@@ -936,9 +962,10 @@ def allTests(communicator):
thrower.begin_throwUndeclaredC(1, 2, 3, cb.response, cb.exception_UndeclaredC)
cb.check()
- print "ok"
+ print("ok")
- print "catching object not exist exception with new AMI mapping...",
+ sys.stdout.write("catching object not exist exception with new AMI mapping... ")
+ sys.stdout.flush()
id = communicator.stringToIdentity("does not exist")
thrower2 = Test.ThrowerPrx.uncheckedCast(thrower.ice_identity(id))
@@ -946,40 +973,44 @@ def allTests(communicator):
thrower2.begin_throwAasA(1, cb.response, cb.exception_AasAObjectNotExist)
cb.check()
- print "ok"
+ print("ok")
- print "catching facet not exist exception with new AMI mapping...",
+ sys.stdout.write("catching facet not exist exception with new AMI mapping... ")
+ sys.stdout.flush()
thrower2 = Test.ThrowerPrx.uncheckedCast(thrower, "no such facet")
cb = Callback()
thrower2.begin_throwAasA(1, cb.response, cb.exception_AasAFacetNotExist)
cb.check()
- print "ok"
+ print("ok")
- print "catching operation not exist exception with new AMI mapping...",
+ sys.stdout.write("catching operation not exist exception with new AMI mapping... ")
+ sys.stdout.flush()
cb = Callback()
thrower4 = Test.WrongOperationPrx.uncheckedCast(thrower)
thrower4.begin_noSuchOperation(cb.response, cb.exception_noSuchOperation)
cb.check()
- print "ok"
+ print("ok")
- print "catching unknown local exception with new AMI mapping...",
+ sys.stdout.write("catching unknown local exception with new AMI mapping... ")
+ sys.stdout.flush()
cb = Callback()
thrower.begin_throwLocalException(cb.response, cb.exception_LocalException)
cb.check()
- print "ok"
+ print("ok")
- print "catching unknown non-Ice exception with new AMI mapping...",
+ sys.stdout.write("catching unknown non-Ice exception with new AMI mapping... ")
+ sys.stdout.flush()
cb = Callback()
thrower.begin_throwNonIceException(cb.response, cb.exception_NonIceException)
cb.check()
- print "ok"
+ print("ok")
return thrower
diff --git a/py/test/Ice/exceptions/run.py b/py/test/Ice/exceptions/run.py
index 83bb6d46a7e..8cc11dcb39f 100755
--- a/py/test/Ice/exceptions/run.py
+++ b/py/test/Ice/exceptions/run.py
@@ -16,14 +16,13 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
-sys.path.append(os.path.join(path[0]))
-from scripts import *
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0], "scripts"))
+import TestUtil
-print "tests with regular server."
+print("tests with regular server.")
TestUtil.clientServerTest()
-print "tests with AMD server."
+print("tests with AMD server.")
TestUtil.clientServerTest(server="ServerAMD.py")
-print "tests with collocated server."
+print("tests with collocated server.")
TestUtil.collocatedTest()
-
diff --git a/py/test/Ice/facets/AllTests.py b/py/test/Ice/facets/AllTests.py
index 88a6a73ee92..263d7883186 100644
--- a/py/test/Ice/facets/AllTests.py
+++ b/py/test/Ice/facets/AllTests.py
@@ -7,7 +7,7 @@
#
# **********************************************************************
-import Ice, Test
+import Ice, Test, sys
def test(b):
if not b:
@@ -18,7 +18,8 @@ class EmptyI(Test.Empty):
def allTests(communicator):
- print "testing Ice.Admin.Facets property... ",
+ sys.stdout.write("testing Ice.Admin.Facets property... ")
+ sys.stdout.flush()
test(len(communicator.getProperties().getPropertyAsList("Ice.Admin.Facets")) == 0)
communicator.getProperties().setProperty("Ice.Admin.Facets", "foobar");
facetFilter = communicator.getProperties().getPropertyAsList("Ice.Admin.Facets");
@@ -37,9 +38,10 @@ def allTests(communicator):
# facetFilter = communicator.getProperties().getPropertyAsList("Ice.Admin.Facets");
# test(len(facetFilter) == 0);
communicator.getProperties().setProperty("Ice.Admin.Facets", "");
- print "ok"
+ print("ok")
- print "testing facet registration exceptions... ",
+ sys.stdout.write("testing facet registration exceptions... ")
+ sys.stdout.flush()
communicator.getProperties().setProperty("FacetExceptionTestAdapter.Endpoints", "default")
adapter = communicator.createObjectAdapter("FacetExceptionTestAdapter")
obj = EmptyI()
@@ -56,9 +58,10 @@ def allTests(communicator):
test(false)
except Ice.NotRegisteredException:
pass
- print "ok"
+ print("ok")
- print "testing removeAllFacets... ",
+ sys.stdout.write("testing removeAllFacets... ")
+ sys.stdout.flush()
obj1 = EmptyI()
obj2 = EmptyI()
adapter.addFacet(obj1, communicator.stringToIdentity("id1"), "f1")
@@ -81,17 +84,19 @@ def allTests(communicator):
test(fm["f1"] == obj1)
test(fm["f2"] == obj2)
test(fm[""] == obj3)
- print "ok"
+ print("ok")
adapter.deactivate()
- print "testing stringToProxy... ",
+ sys.stdout.write("testing stringToProxy... ")
+ sys.stdout.flush()
ref = "d:default -p 12010"
db = communicator.stringToProxy(ref)
test(db)
- print "ok"
+ print("ok")
- print "testing unchecked cast... ",
+ sys.stdout.write("testing unchecked cast... ")
+ sys.stdout.flush()
obj = Ice.ObjectPrx.uncheckedCast(db)
test(obj.ice_getFacet() == "")
obj = Ice.ObjectPrx.uncheckedCast(db, "facetABCD")
@@ -108,9 +113,10 @@ def allTests(communicator):
test(df2.ice_getFacet() == "facetABCD")
df3 = Test.DPrx.uncheckedCast(df, "")
test(df3.ice_getFacet() == "")
- print "ok"
+ print("ok")
- print "testing checked cast... ",
+ sys.stdout.write("testing checked cast... ")
+ sys.stdout.flush()
obj = Ice.ObjectPrx.checkedCast(db)
test(obj.ice_getFacet() == "")
obj = Ice.ObjectPrx.checkedCast(db, "facetABCD")
@@ -127,9 +133,10 @@ def allTests(communicator):
test(df2.ice_getFacet() == "facetABCD")
df3 = Test.DPrx.checkedCast(df, "")
test(df3.ice_getFacet() == "")
- print "ok"
+ print("ok")
- print "testing non-facets A, B, C, and D... ",
+ sys.stdout.write("testing non-facets A, B, C, and D... ")
+ sys.stdout.flush()
d = Test.DPrx.checkedCast(db)
test(d)
test(d == db)
@@ -137,35 +144,39 @@ def allTests(communicator):
test(d.callB() == "B")
test(d.callC() == "C")
test(d.callD() == "D")
- print "ok"
+ print("ok")
- print "testing facets A, B, C, and D... ",
+ sys.stdout.write("testing facets A, B, C, and D... ")
+ sys.stdout.flush()
df = Test.DPrx.checkedCast(d, "facetABCD")
test(df)
test(df.callA() == "A")
test(df.callB() == "B")
test(df.callC() == "C")
test(df.callD() == "D")
- print "ok"
+ print("ok")
- print "testing facets E and F... ",
+ sys.stdout.write("testing facets E and F... ")
+ sys.stdout.flush()
ff = Test.FPrx.checkedCast(d, "facetEF")
test(ff)
test(ff.callE() == "E")
test(ff.callF() == "F")
- print "ok"
+ print("ok")
- print "testing facet G... ",
+ sys.stdout.write("testing facet G... ")
+ sys.stdout.flush()
gf = Test.GPrx.checkedCast(ff, "facetGH")
test(gf)
test(gf.callG() == "G")
- print "ok"
+ print("ok")
- print "testing whether casting preserves the facet... ",
+ sys.stdout.write("testing whether casting preserves the facet... ")
+ sys.stdout.flush()
hf = Test.HPrx.checkedCast(gf)
test(hf)
test(hf.callG() == "G")
test(hf.callH() == "H")
- print "ok"
+ print("ok")
return gf
diff --git a/py/test/Ice/facets/run.py b/py/test/Ice/facets/run.py
index 099ce110107..db68ff30b9a 100755
--- a/py/test/Ice/facets/run.py
+++ b/py/test/Ice/facets/run.py
@@ -16,10 +16,9 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
-sys.path.append(os.path.join(path[0]))
-from scripts import *
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0], "scripts"))
+import TestUtil
TestUtil.clientServerTest()
TestUtil.collocatedTest()
-
diff --git a/py/test/Ice/faultTolerance/AllTests.py b/py/test/Ice/faultTolerance/AllTests.py
index 040e99a7540..e82f326051e 100644
--- a/py/test/Ice/faultTolerance/AllTests.py
+++ b/py/test/Ice/faultTolerance/AllTests.py
@@ -7,7 +7,7 @@
#
# **********************************************************************
-import Ice, threading
+import Ice, sys, threading
Ice.loadSlice('Test.ice')
import Test
@@ -57,8 +57,8 @@ class Callback(CallbackBase):
pass
except Ice.ConnectFailedException:
pass
- except Ice.Exception, ex:
- print ex
+ except Ice.Exception as ex:
+ print(ex)
test(False)
self.called()
@@ -66,19 +66,21 @@ class Callback(CallbackBase):
return self._pid
def allTests(communicator, ports):
- print "testing stringToProxy... ",
+ sys.stdout.write("testing stringToProxy... ")
+ sys.stdout.flush()
ref = "test"
for p in ports:
ref = ref + ":default -p " + str(p)
base = communicator.stringToProxy(ref)
test(base)
- print "ok"
+ print("ok")
- print "testing checked cast... ",
+ sys.stdout.write("testing checked cast... ")
+ sys.stdout.flush()
obj = Test.TestIntfPrx.checkedCast(base)
test(obj)
test(obj == base)
- print "ok"
+ print("ok")
oldPid = 0
ami = False
@@ -90,64 +92,72 @@ def allTests(communicator, ports):
ami = not ami
if not ami:
- print "testing server #%d... " % i,
+ sys.stdout.write("testing server #%d... " % i)
+ sys.stdout.flush()
pid = obj.pid()
test(pid != oldPid)
- print "ok"
+ print("ok")
oldPid = pid
else:
- print "testing server #%d with AMI... " % i,
+ sys.stdout.write("testing server #%d with AMI... " % i)
+ sys.stdout.flush()
cb = Callback()
obj.begin_pid(cb.opPidI, cb.exception)
cb.check()
pid = cb.pid()
test(pid != oldPid)
- print "ok"
+ print("ok")
oldPid = pid
if j == 0:
if not ami:
- print "shutting down server #%d... " % i,
+ sys.stdout.write("shutting down server #%d... " % i)
+ sys.stdout.flush()
obj.shutdown()
- print "ok"
+ print("ok")
else:
- print "shutting down server #%d with AMI... " % i,
+ sys.stdout.write("shutting down server #%d with AMI... " % i)
+ sys.stdout.flush()
cb = Callback()
obj.begin_shutdown(cb.opShutdownI, cb.exception)
cb.check()
- print "ok"
+ print("ok")
elif j == 1 or i + 1 > len(ports):
if not ami:
- print "aborting server #%d... " % i,
+ sys.stdout.write("aborting server #%d... " % i)
+ sys.stdout.flush()
try:
obj.abort()
test(False)
except Ice.ConnectionLostException:
- print "ok"
+ print("ok")
except Ice.ConnectFailedException:
- print "ok"
+ print("ok")
else:
- print "aborting server #%d with AMI... " % i,
+ sys.stdout.write("aborting server #%d with AMI... " % i)
+ sys.stdout.flush()
cb = Callback()
obj.begin_abort(cb.response, cb.exceptAbortI)
cb.check()
- print "ok"
+ print("ok")
elif j == 2 or j == 3:
if not ami:
- print "aborting server #%d and #%d with idempotent call... " % (i, i + 1),
+ sys.stdout.write("aborting server #%d and #%d with idempotent call... " % (i, i + 1))
+ sys.stdout.flush()
try:
obj.idempotentAbort()
test(False)
except Ice.ConnectionLostException:
- print "ok"
+ print("ok")
except Ice.ConnectFailedException:
- print "ok"
+ print("ok")
else:
- print "aborting server #%d and #%d with idempotent AMI call... " % (i, i + 1),
+ sys.stdout.write("aborting server #%d and #%d with idempotent AMI call... " % (i, i + 1))
+ sys.stdout.flush()
cb = Callback()
obj.begin_idempotentAbort(cb.response, cb.exceptAbortI)
cb.check()
- print "ok"
+ print("ok")
i = i + 1
else:
@@ -156,9 +166,10 @@ def allTests(communicator, ports):
i = i + 1
j = j + 1
- print "testing whether all servers are gone... ",
+ sys.stdout.write("testing whether all servers are gone... ")
+ sys.stdout.flush()
try:
obj.ice_ping()
test(False)
except Ice.LocalException:
- print "ok"
+ print("ok")
diff --git a/py/test/Ice/faultTolerance/Server.py b/py/test/Ice/faultTolerance/Server.py
index dbc69708beb..b1b6b277d3f 100755
--- a/py/test/Ice/faultTolerance/Server.py
+++ b/py/test/Ice/faultTolerance/Server.py
@@ -22,7 +22,7 @@ class TestI(Test.TestIntf):
current.adapter.getCommunicator().shutdown()
def abort(self, current=None):
- print "aborting..."
+ sys.stdout.write("aborting...")
os._exit(0)
def idempotentAbort(self, current=None):
@@ -35,18 +35,18 @@ def run(args, communicator):
port = 0
for arg in args[1:]:
if arg[0] == '-':
- print >> sys.stderr, args[0] + ": unknown option `" + arg + "'"
+ sys.stderr.write(args[0] + ": unknown option `" + arg + "'\n")
usage(args[0])
return False
if port > 0:
- print >> sys.stderr, args[0] + ": only one port can be specified"
+ sys.stderr.write(args[0] + ": only one port can be specified\n")
usage(args[0])
return False
port = int(arg)
if port <= 0:
- print >> sys.stderr, args[0] + ": no port specified"
+ sys.stderr.write(args[0] + ": no port specified\n")
usage(args[0])
return False
diff --git a/py/test/Ice/faultTolerance/run.py b/py/test/Ice/faultTolerance/run.py
index 44cf4fde9f3..b59bb43dae9 100755
--- a/py/test/Ice/faultTolerance/run.py
+++ b/py/test/Ice/faultTolerance/run.py
@@ -16,9 +16,9 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
-sys.path.append(os.path.join(path[0]))
-from scripts import *
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0], "scripts"))
+import TestUtil
server = os.path.join(os.getcwd(), "Server.py")
client = os.path.join(os.getcwd(), "Client.py")
@@ -28,20 +28,20 @@ base = 12340
serverProc = []
for i in range(0, num):
- print "starting server #%d..." % (i + 1),
+ sys.stdout.write("starting server #%d... " % (i + 1))
sys.stdout.flush()
serverProc.append(TestUtil.startServer(server, "%d" % (base + i)))
- print "ok"
+ print("ok")
ports = ""
for i in range(0, num):
ports = "%s %d" % (ports, base + i)
-print "starting client...",
+sys.stdout.write("starting client... ")
+sys.stdout.flush()
clientProc = TestUtil.startClient(client, ports, startReader = False)
-print "ok"
+print("ok")
clientProc.startReader()
clientProc.waitTestSuccess()
for p in serverProc:
p.waitTestSuccess()
-
diff --git a/py/test/Ice/info/AllTests.py b/py/test/Ice/info/AllTests.py
index 9820a1e83a4..b9d81645899 100644
--- a/py/test/Ice/info/AllTests.py
+++ b/py/test/Ice/info/AllTests.py
@@ -7,14 +7,15 @@
#
# **********************************************************************
-import Ice, Test, threading
+import Ice, Test, sys, threading
def test(b):
if not b:
raise RuntimeError('test assertion failed')
def allTests(communicator, collocated):
- print "testing proxy endpoint information...",
+ sys.stdout.write("testing proxy endpoint information... ")
+ sys.stdout.flush()
p1 = communicator.stringToProxy("test -t:default -h tcphost -p 10000 -t 1200 -z:" + \
"udp -h udphost -p 10001 --interface eth0 --ttl 5:" + \
@@ -49,11 +50,12 @@ def allTests(communicator, collocated):
opaqueEndpoint = endps[2].getInfo()
test(isinstance(opaqueEndpoint, Ice.OpaqueEndpointInfo))
- print "ok"
+ print("ok")
defaultHost = communicator.getProperties().getProperty("Ice.Default.Host")
- print "test object adapter endpoint information...",
+ sys.stdout.write("test object adapter endpoint information... ")
+ sys.stdout.flush()
communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -t 15000:udp")
adapter = communicator.createObjectAdapter("TestAdapter")
@@ -94,12 +96,13 @@ def allTests(communicator, collocated):
adapter.destroy()
- print "ok"
+ print("ok")
base = communicator.stringToProxy("test:default -p 12010:udp -p 12010")
testIntf = Test.TestIntfPrx.checkedCast(base)
- print "test connection endpoint information...",
+ sys.stdout.write("test connection endpoint information... ")
+ sys.stdout.flush()
ipinfo = base.ice_getConnection().getEndpoint().getInfo()
test(ipinfo.port == 12010)
@@ -116,9 +119,10 @@ def allTests(communicator, collocated):
test(udp.port == 12010)
test(udp.host == defaultHost)
- print "ok"
+ print("ok")
- print "testing connection information...",
+ sys.stdout.write("testing connection information... ")
+ sys.stdout.flush()
info = base.ice_getConnection().getInfo()
test(not info.incoming)
@@ -135,7 +139,7 @@ def allTests(communicator, collocated):
test(ctx["remotePort"] == str(info.localPort))
test(ctx["localPort"] == str(info.remotePort))
- print "ok"
+ print("ok")
testIntf.shutdown()
diff --git a/py/test/Ice/info/Client.py b/py/test/Ice/info/Client.py
index 5cd19058441..42d97e921b9 100755
--- a/py/test/Ice/info/Client.py
+++ b/py/test/Ice/info/Client.py
@@ -13,7 +13,7 @@ import os, sys, traceback
import Ice
slice_dir = Ice.getSliceDir()
if not slice_dir:
- print sys.argv[0] + ': Slice directory not found.'
+ print(sys.argv[0] + ': Slice directory not found.')
sys.exit(1)
Ice.loadSlice("'-I" + slice_dir + "' Test.ice")
diff --git a/py/test/Ice/info/Server.py b/py/test/Ice/info/Server.py
index 25d50c3f5b4..e48d8c894de 100755
--- a/py/test/Ice/info/Server.py
+++ b/py/test/Ice/info/Server.py
@@ -13,7 +13,7 @@ import os, sys, traceback
import Ice
slice_dir = Ice.getSliceDir()
if not slice_dir:
- print sys.argv[0] + ': Slice directory not found.'
+ print(sys.argv[0] + ': Slice directory not found.')
sys.exit(1)
Ice.loadSlice("'-I" + slice_dir + "' Test.ice")
diff --git a/py/test/Ice/info/run.py b/py/test/Ice/info/run.py
index 32ea526c3b4..2265a40ca12 100755
--- a/py/test/Ice/info/run.py
+++ b/py/test/Ice/info/run.py
@@ -16,9 +16,8 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
-sys.path.append(os.path.join(path[0]))
-from scripts import *
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0], "scripts"))
+import TestUtil
TestUtil.clientServerTest()
-
diff --git a/py/test/Ice/inheritance/AllTests.py b/py/test/Ice/inheritance/AllTests.py
index 3a2f243b1f3..acd585bb835 100644
--- a/py/test/Ice/inheritance/AllTests.py
+++ b/py/test/Ice/inheritance/AllTests.py
@@ -7,26 +7,29 @@
#
# **********************************************************************
-import Ice, Test
+import Ice, Test, sys
def test(b):
if not b:
raise RuntimeError('test assertion failed')
def allTests(communicator):
- print "testing stringToProxy... ",
+ sys.stdout.write("testing stringToProxy... ")
+ sys.stdout.flush()
ref = "initial:default -p 12010"
base = communicator.stringToProxy(ref)
test(base)
- print "ok"
+ print("ok")
- print "testing checked cast... ",
+ sys.stdout.write("testing checked cast... ")
+ sys.stdout.flush()
initial = Test.InitialPrx.checkedCast(base)
test(initial)
test(initial == base)
- print "ok"
+ print("ok")
- print "getting proxies for class hierarchy... ",
+ sys.stdout.write("getting proxies for class hierarchy... ")
+ sys.stdout.flush()
ca = initial.caop()
cb = initial.cbop()
cc = initial.ccop()
@@ -37,9 +40,10 @@ def allTests(communicator):
test(cb != cc)
test(cb != cd)
test(cc != cd)
- print "ok"
+ print("ok")
- print "getting proxies for interface hierarchy... ",
+ sys.stdout.write("getting proxies for interface hierarchy... ")
+ sys.stdout.flush()
ia = initial.iaop()
ib1 = initial.ib1op()
ib2 = initial.ib2op()
@@ -49,9 +53,10 @@ def allTests(communicator):
test(ia != ic)
test(ib1 != ic)
test(ib2 != ic)
- print "ok"
+ print("ok")
- print "invoking proxy operations on class hierarchy... ",
+ sys.stdout.write("invoking proxy operations on class hierarchy... ")
+ sys.stdout.flush()
cao = ca.caop(ca)
test(cao == ca)
cao = ca.caop(cb)
@@ -94,9 +99,10 @@ def allTests(communicator):
test(cbo == cc)
cco = cc.ccop(cc)
test(cco == cc)
- print "ok"
+ print("ok")
- print "ditto, but for interface hierarchy... ",
+ sys.stdout.write("ditto, but for interface hierarchy... ")
+ sys.stdout.flush()
iao = ia.iaop(ia)
test(iao == ia)
iao = ia.iaop(ib1)
@@ -173,9 +179,10 @@ def allTests(communicator):
ico = ic.icop(ic)
test(ico == ic)
- print "ok"
+ print("ok")
- print "ditto, but for class implementing interfaces... ",
+ sys.stdout.write("ditto, but for class implementing interfaces... ")
+ sys.stdout.flush()
cao = cd.caop(cd)
test(cao == cd)
cbo = cd.cbop(cd)
@@ -204,6 +211,6 @@ def allTests(communicator):
ib2o = cd.cdop(cd)
test(ib2o == cd)
- print "ok"
+ print("ok")
return initial
diff --git a/py/test/Ice/inheritance/run.py b/py/test/Ice/inheritance/run.py
index 099ce110107..db68ff30b9a 100755
--- a/py/test/Ice/inheritance/run.py
+++ b/py/test/Ice/inheritance/run.py
@@ -16,10 +16,9 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
-sys.path.append(os.path.join(path[0]))
-from scripts import *
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0], "scripts"))
+import TestUtil
TestUtil.clientServerTest()
TestUtil.collocatedTest()
-
diff --git a/py/test/Ice/location/AllTests.py b/py/test/Ice/location/AllTests.py
index da702bb1cfd..c0a37c2b2fd 100644
--- a/py/test/Ice/location/AllTests.py
+++ b/py/test/Ice/location/AllTests.py
@@ -7,7 +7,7 @@
#
# **********************************************************************
-import Ice, Test
+import Ice, Test, sys
def test(b):
if not b:
@@ -18,15 +18,17 @@ def allTests(communicator, ref):
locator = communicator.getDefaultLocator()
test(manager)
- print "testing stringToProxy...",
+ sys.stdout.write("testing stringToProxy... ")
+ sys.stdout.flush()
base = communicator.stringToProxy("test @ TestAdapter")
base2 = communicator.stringToProxy("test @ TestAdapter")
base3 = communicator.stringToProxy("test")
base4 = communicator.stringToProxy("ServerManager")
base5 = communicator.stringToProxy("test2")
- print "ok"
+ print("ok")
- print "testing ice_locator and ice_getLocator... ",
+ sys.stdout.write("testing ice_locator and ice_getLocator... ")
+ sys.stdout.flush()
test(Ice.proxyIdentityEqual(base.ice_getLocator(), communicator.getDefaultLocator()));
anotherLocator = Ice.LocatorPrx.uncheckedCast(communicator.stringToProxy("anotherLocator"));
base = base.ice_locator(anotherLocator);
@@ -55,13 +57,15 @@ def allTests(communicator, ref):
communicator.setDefaultRouter(None);
base = communicator.stringToProxy("test @ TestAdapter");
test(not base.ice_getRouter());
- print "ok"
+ print("ok")
- print "starting server...",
+ sys.stdout.write("starting server... ")
+ sys.stdout.flush()
manager.startServer()
- print "ok"
+ print("ok")
- print "testing checked cast...",
+ sys.stdout.write("testing checked cast... ")
+ sys.stdout.flush()
obj = Test.TestIntfPrx.checkedCast(base)
obj = Test.TestIntfPrx.checkedCast(communicator.stringToProxy("test@TestAdapter"))
obj = Test.TestIntfPrx.checkedCast(communicator.stringToProxy("test @TestAdapter"))
@@ -75,9 +79,10 @@ def allTests(communicator, ref):
test(obj4)
obj5 = Test.TestIntfPrx.checkedCast(base5)
test(obj5)
- print "ok"
+ print("ok")
- print "testing id@AdapterId indirect proxy...",
+ sys.stdout.write("testing id@AdapterId indirect proxy... ")
+ sys.stdout.flush()
obj.shutdown()
manager.startServer()
try:
@@ -85,9 +90,10 @@ def allTests(communicator, ref):
obj2.ice_ping()
except Ice.LocalException:
test(False)
- print "ok"
+ print("ok")
- print "testing identity indirect proxy...",
+ sys.stdout.write("testing identity indirect proxy... ")
+ sys.stdout.flush()
obj.shutdown()
manager.startServer()
try:
@@ -142,40 +148,45 @@ def allTests(communicator, ref):
obj5.ice_ping()
except Ice.LocalException:
test(False)
- print "ok"
+ print("ok")
- print "testing reference with unknown identity...",
+ sys.stdout.write("testing reference with unknown identity... ")
+ sys.stdout.flush()
try:
base = communicator.stringToProxy("unknown/unknown")
base.ice_ping()
test(False)
- except Ice.NotRegisteredException, ex:
+ except Ice.NotRegisteredException as ex:
test(ex.kindOfObject == "object")
test(ex.id == "unknown/unknown")
- print "ok"
+ print("ok")
- print "testing reference with unknown adapter...",
+ sys.stdout.write("testing reference with unknown adapter... ")
+ sys.stdout.flush()
try:
base = communicator.stringToProxy("test @ TestAdapterUnknown")
base.ice_ping()
test(False)
- except Ice.NotRegisteredException, ex:
+ except Ice.NotRegisteredException as ex:
test(ex.kindOfObject == "object adapter")
test(ex.id == "TestAdapterUnknown")
- print "ok"
+ print("ok")
- print "testing object reference from server...",
+ sys.stdout.write("testing object reference from server... ")
+ sys.stdout.flush()
hello = obj.getHello()
hello.sayHello()
- print "ok"
+ print("ok")
- print "testing object reference from server after shutdown...",
+ sys.stdout.write("testing object reference from server after shutdown... ")
+ sys.stdout.flush()
obj.shutdown()
manager.startServer()
hello.sayHello()
- print "ok"
+ print("ok")
- print "testing object migration...",
+ sys.stdout.write("testing object migration... ")
+ sys.stdout.flush()
hello = Test.HelloPrx.checkedCast(communicator.stringToProxy("hello"))
obj.migrateHello()
hello.sayHello()
@@ -183,13 +194,15 @@ def allTests(communicator, ref):
hello.sayHello()
obj.migrateHello()
hello.sayHello()
- print "ok"
+ print("ok")
- print "shutdown server...",
+ sys.stdout.write("shutdown server... ")
+ sys.stdout.flush()
obj.shutdown()
- print "ok"
+ print("ok")
- print "testing whether server is gone...",
+ sys.stdout.write("testing whether server is gone... ")
+ sys.stdout.flush()
try:
obj2.ice_ping()
test(False)
@@ -205,13 +218,14 @@ def allTests(communicator, ref):
test(False)
except Ice.LocalException:
pass
- print "ok"
+ print("ok")
#
# Collocated invocations are not supported in Python.
#
- #print "testing indirect references to collocated objects...",
+ #sys.stdout.write("testing indirect references to collocated objects... ")
- print "shutdown server manager...",
+ sys.stdout.write("shutdown server manager... ")
+ sys.stdout.flush()
manager.shutdown()
- print "ok"
+ print("ok")
diff --git a/py/test/Ice/location/Client.py b/py/test/Ice/location/Client.py
index bde025692ff..f69df0e42d9 100755
--- a/py/test/Ice/location/Client.py
+++ b/py/test/Ice/location/Client.py
@@ -13,7 +13,7 @@ import os, sys, traceback
import Ice
slice_dir = Ice.getSliceDir()
if not slice_dir:
- print sys.argv[0] + ': Slice directory not found.'
+ print(sys.argv[0] + ': Slice directory not found.')
sys.exit(1)
Ice.loadSlice("'-I" + slice_dir + "' Test.ice")
diff --git a/py/test/Ice/location/Server.py b/py/test/Ice/location/Server.py
index af53260c213..c10cdd3a64b 100755
--- a/py/test/Ice/location/Server.py
+++ b/py/test/Ice/location/Server.py
@@ -13,7 +13,7 @@ import os, sys, traceback
import Ice
slice_dir = Ice.getSliceDir()
if not slice_dir:
- print sys.argv[0] + ': Slice directory not found.'
+ print(sys.argv[0] + ': Slice directory not found.')
sys.exit(1)
Ice.loadSlice("'-I" + slice_dir + "' Test.ice")
@@ -47,12 +47,12 @@ class ServerLocatorRegistry(Test.TestLocatorRegistry):
self._objects[obj.ice_getIdentity()] = obj
def getAdapter(self, adapter):
- if not self._adapters.has_key(adapter):
+ if adapter not in self._adapters:
raise Ice.AdapterNotFoundException()
return self._adapters[adapter]
def getObject(self, id):
- if not self._objects.has_key(id):
+ if id not in self._objects:
raise Ice.ObjectNotFoundException()
return self._objects[id]
diff --git a/py/test/Ice/location/run.py b/py/test/Ice/location/run.py
index 32ea526c3b4..2265a40ca12 100755
--- a/py/test/Ice/location/run.py
+++ b/py/test/Ice/location/run.py
@@ -16,9 +16,8 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
-sys.path.append(os.path.join(path[0]))
-from scripts import *
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0], "scripts"))
+import TestUtil
TestUtil.clientServerTest()
-
diff --git a/py/test/Ice/objects/AllTests.py b/py/test/Ice/objects/AllTests.py
index ae6fa28ea6a..73025afd2a2 100644
--- a/py/test/Ice/objects/AllTests.py
+++ b/py/test/Ice/objects/AllTests.py
@@ -7,7 +7,7 @@
#
# **********************************************************************
-import Ice, Test, TestI
+import Ice, Test, TestI, sys
#
# Ice for Python behaves differently than Ice for C++, because
@@ -54,39 +54,46 @@ def allTests(communicator, collocated):
communicator.addObjectFactory(factory, '::Test::J')
communicator.addObjectFactory(factory, '::Test::H')
- print "testing stringToProxy...",
+ sys.stdout.write("testing stringToProxy... ")
+ sys.stdout.flush()
ref = "initial:default -p 12010"
base = communicator.stringToProxy(ref)
test(base)
- print "ok"
+ print("ok")
- print "testing checked cast...",
+ sys.stdout.write("testing checked cast... ")
+ sys.stdout.flush()
initial = Test.InitialPrx.checkedCast(base)
test(initial)
test(initial == base)
- print "ok"
+ print("ok")
- print "getting B1...",
+ sys.stdout.write("getting B1... ")
+ sys.stdout.flush()
b1 = initial.getB1()
test(b1)
- print "ok"
+ print("ok")
- print "getting B2...",
+ sys.stdout.write("getting B2... ")
+ sys.stdout.flush()
b2 = initial.getB2()
test(b2)
- print "ok"
+ print("ok")
- print "getting C...",
+ sys.stdout.write("getting C... ")
+ sys.stdout.flush()
c = initial.getC()
test(c)
- print "ok"
+ print("ok")
- print "getting D...",
+ sys.stdout.write("getting D... ")
+ sys.stdout.flush()
d = initial.getD()
test(d)
- print "ok"
+ print("ok")
- print "testing protected members...",
+ sys.stdout.write("testing protected members... ")
+ sys.stdout.flush()
e = initial.getE()
test(e.checkValues())
test(e._i == 1)
@@ -95,24 +102,27 @@ def allTests(communicator, collocated):
test(f.checkValues())
test(f.e2.checkValues())
test(f._e1.checkValues())
- print "ok"
+ print("ok")
- print "getting I, J, H...",
+ sys.stdout.write("getting I, J, H... ")
+ sys.stdout.flush()
i = initial.getI()
test(i)
j = initial.getJ()
test(isinstance(j, Test.J))
h = initial.getH()
test(isinstance(h, Test.H))
- print "ok"
+ print("ok")
- print "setting I...",
+ sys.stdout.write("setting I... ")
+ sys.stdout.flush()
initial.setI(TestI.II())
initial.setI(TestI.JI())
initial.setI(TestI.HI())
- print "ok"
+ print("ok")
- print "checking consistency...",
+ sys.stdout.write("checking consistency... ")
+ sys.stdout.flush()
test(b1 != b2)
test(b1 != c)
test(b1 != d)
@@ -135,17 +145,19 @@ def allTests(communicator, collocated):
# More tests possible for b2 and d, but I think this is already sufficient.
test(b2.theA == b2)
test(d.theC == None)
- print "ok"
+ print("ok")
- print "getting B1, B2, C, and D all at once...",
+ sys.stdout.write("getting B1, B2, C, and D all at once... ")
+ sys.stdout.flush()
b1, b2, c, d = initial.getAll()
test(b1)
test(b2)
test(c)
test(d)
- print "ok"
+ print("ok")
- print "checking consistency...",
+ sys.stdout.write("checking consistency... ")
+ sys.stdout.flush()
test(b1 != b2)
test(b1 != c)
test(b1 != d)
@@ -170,10 +182,11 @@ def allTests(communicator, collocated):
test(d.theB.postUnmarshalInvoked())
test(d.theB.theC.preMarshalInvoked)
test(d.theB.theC.postUnmarshalInvoked())
- print "ok"
+ print("ok")
if not collocated:
- print "testing UnexpectedObjectException...",
+ sys.stdout.write("testing UnexpectedObjectException... ")
+ sys.stdout.flush()
ref = "uoet:default -p 12010"
base = communicator.stringToProxy(ref)
test(base)
@@ -182,15 +195,15 @@ def allTests(communicator, collocated):
try:
uoet.op()
test(False)
- except Ice.UnexpectedObjectException, ex:
+ except Ice.UnexpectedObjectException as ex:
test(ex.type == "::Test::AlsoEmpty")
test(ex.expectedType == "::Test::Empty")
- except Ice.Exception, ex:
- print ex
+ except Ice.Exception as ex:
+ print(ex)
test(False)
except:
- print sys.exc_info()
+ print(sys.exc_info())
test(False)
- print "ok"
+ print("ok")
return initial
diff --git a/py/test/Ice/objects/run.py b/py/test/Ice/objects/run.py
index 099ce110107..db68ff30b9a 100755
--- a/py/test/Ice/objects/run.py
+++ b/py/test/Ice/objects/run.py
@@ -16,10 +16,9 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
-sys.path.append(os.path.join(path[0]))
-from scripts import *
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0], "scripts"))
+import TestUtil
TestUtil.clientServerTest()
TestUtil.collocatedTest()
-
diff --git a/py/test/Ice/operations/AllTests.py b/py/test/Ice/operations/AllTests.py
index ee7ee230e9b..13debf12e8b 100644
--- a/py/test/Ice/operations/AllTests.py
+++ b/py/test/Ice/operations/AllTests.py
@@ -7,7 +7,7 @@
#
# **********************************************************************
-import Ice, Test, Twoways, TwowaysAMI, TwowaysNewAMI, Oneways, OnewaysAMI, OnewaysNewAMI, BatchOneways
+import Ice, Test, Twoways, TwowaysAMI, TwowaysNewAMI, Oneways, OnewaysAMI, OnewaysNewAMI, BatchOneways, sys
def test(b):
if not b:
@@ -19,36 +19,43 @@ def allTests(communicator, collocated):
cl = Test.MyClassPrx.checkedCast(base)
derived = Test.MyDerivedClassPrx.checkedCast(cl)
- print "testing twoway operations...",
+ sys.stdout.write("testing twoway operations... ")
+ sys.stdout.flush()
Twoways.twoways(communicator, cl)
Twoways.twoways(communicator, derived)
derived.opDerived()
- print "ok"
+ print("ok")
- print "testing oneway operations...",
+ sys.stdout.write("testing oneway operations... ")
+ sys.stdout.flush()
Oneways.oneways(communicator, cl)
- print "ok"
+ print("ok")
if not collocated:
- print "testing twoway operations with AMI...",
+ sys.stdout.write("testing twoway operations with AMI... ")
+ sys.stdout.flush()
TwowaysAMI.twowaysAMI(communicator, cl)
- print "ok"
+ print("ok")
- print "testing twoway operations with new AMI mapping...",
+ sys.stdout.write("testing twoway operations with new AMI mapping... ")
+ sys.stdout.flush()
TwowaysNewAMI.twowaysNewAMI(communicator, cl)
- print "ok"
+ print("ok")
- print "testing oneway operations with AMI...",
+ sys.stdout.write("testing oneway operations with AMI... ")
+ sys.stdout.flush()
OnewaysAMI.onewaysAMI(communicator, cl)
- print "ok"
+ print("ok")
- print "testing oneway operations with new AMI mapping...",
+ sys.stdout.write("testing oneway operations with new AMI mapping... ")
+ sys.stdout.flush()
OnewaysNewAMI.onewaysNewAMI(communicator, cl)
- print "ok"
+ print("ok")
- print "testing batch oneway operations... ",
+ sys.stdout.write("testing batch oneway operations... ")
+ sys.stdout.flush()
BatchOneways.batchOneways(cl)
BatchOneways.batchOneways(derived)
- print "ok"
+ print("ok")
return cl
diff --git a/py/test/Ice/operations/BatchOneways.py b/py/test/Ice/operations/BatchOneways.py
index a263d190d07..97d8eec9c04 100644
--- a/py/test/Ice/operations/BatchOneways.py
+++ b/py/test/Ice/operations/BatchOneways.py
@@ -7,7 +7,7 @@
#
# **********************************************************************
-import Ice, Test, array
+import Ice, Test, array, sys
def test(b):
if not b:
@@ -15,20 +15,25 @@ def test(b):
def batchOneways(p):
- bs1 = []
- bs1[0:10 * 1024] = range(0, 10 * 1024) # add 100,000 entries.
- bs1 = ['\x00' for x in bs1] # set them all to \x00
- bs1 = ''.join(bs1) # make into a byte array
-
- bs2 = []
- bs2[0:99 * 1024] = range(0, 99 * 1024) # add 100,000 entries.
- bs2 = ['\x00' for x in bs2] # set them all to \x00
- bs2 = ''.join(bs2) # make into a byte array
-
- bs3 = []
- bs3[0:100 * 1024] = range(0, 100 * 1024) # add 100,000 entries.
- bs3 = ['\x00' for x in bs3] # set them all to \x00
- bs3 = ''.join(bs3) # make into a byte array
+ if sys.version_info[0] == 2:
+ bs1 = []
+ bs1[0:10 * 1024] = range(0, 10 * 1024) # add 100,000 entries.
+ bs1 = ['\x00' for x in bs1] # set them all to \x00
+ bs1 = ''.join(bs1) # make into a byte array
+
+ bs2 = []
+ bs2[0:99 * 1024] = range(0, 99 * 1024) # add 100,000 entries.
+ bs2 = ['\x00' for x in bs2] # set them all to \x00
+ bs2 = ''.join(bs2) # make into a byte array
+
+ bs3 = []
+ bs3[0:100 * 1024] = range(0, 100 * 1024) # add 100,000 entries.
+ bs3 = ['\x00' for x in bs3] # set them all to \x00
+ bs3 = ''.join(bs3) # make into a byte array
+ else:
+ bs1 = bytes([0 for x in range(0, 10 * 1024)])
+ bs2 = bytes([0 for x in range(0, 99 * 1024)])
+ bs3 = bytes([0 for x in range(0, 100 * 1024)])
try:
p.opByteSOneway(bs1)
diff --git a/py/test/Ice/operations/Client.py b/py/test/Ice/operations/Client.py
index 67c8ae96bf9..57450e3f8ac 100755
--- a/py/test/Ice/operations/Client.py
+++ b/py/test/Ice/operations/Client.py
@@ -14,7 +14,7 @@ import Ice
import Ice
slice_dir = Ice.getSliceDir()
if not slice_dir:
- print sys.argv[0] + ': Slice directory not found.'
+ print(sys.argv[0] + ': Slice directory not found.')
sys.exit(1)
Ice.loadSlice("'-I" + slice_dir + "' Test.ice")
@@ -27,13 +27,14 @@ def test(b):
def run(args, communicator):
myClass = AllTests.allTests(communicator, False)
- print "testing server shutdown...",
+ sys.stdout.write("testing server shutdown... ")
+ sys.stdout.flush()
myClass.shutdown()
try:
myClass.opVoid()
test(False)
except Ice.LocalException:
- print "ok"
+ print("ok")
return True
diff --git a/py/test/Ice/operations/Collocated.py b/py/test/Ice/operations/Collocated.py
index 975b0d90b83..c4665b05f5f 100755
--- a/py/test/Ice/operations/Collocated.py
+++ b/py/test/Ice/operations/Collocated.py
@@ -13,7 +13,7 @@ import os, sys, traceback
import Ice
slice_dir = Ice.getSliceDir()
if not slice_dir:
- print sys.argv[0] + ': Slice directory not found.'
+ print(sys.argv[0] + ': Slice directory not found.')
sys.exit(1)
Ice.loadSlice('"-I' + slice_dir + '" Test.ice')
diff --git a/py/test/Ice/operations/Oneways.py b/py/test/Ice/operations/Oneways.py
index a541a78eca8..800cfcd69a0 100644
--- a/py/test/Ice/operations/Oneways.py
+++ b/py/test/Ice/operations/Oneways.py
@@ -44,4 +44,3 @@ def oneways(communicator, p):
p.opByte(0xff, 0x0f)
except Ice.TwowayOnlyException:
pass
-
diff --git a/py/test/Ice/operations/Server.py b/py/test/Ice/operations/Server.py
index bc8fefe5e93..55d8b2f6304 100755
--- a/py/test/Ice/operations/Server.py
+++ b/py/test/Ice/operations/Server.py
@@ -12,7 +12,7 @@ import os, sys, traceback
import Ice
slice_dir = Ice.getSliceDir()
if not slice_dir:
- print sys.argv[0] + ': Slice directory not found.'
+ print(sys.argv[0] + ': Slice directory not found.')
sys.exit(1)
Ice.loadSlice('"-I' + slice_dir + '" Test.ice')
diff --git a/py/test/Ice/operations/ServerAMD.py b/py/test/Ice/operations/ServerAMD.py
index 4a4b1182a68..0ff9afd957a 100755
--- a/py/test/Ice/operations/ServerAMD.py
+++ b/py/test/Ice/operations/ServerAMD.py
@@ -13,7 +13,7 @@ import os, sys, traceback, threading
import Ice
slice_dir = Ice.getSliceDir()
if not slice_dir:
- print sys.argv[0] + ': Slice directory not found.'
+ print(sys.argv[0] + ': Slice directory not found.')
sys.exit(1)
Ice.loadSlice("'-I" + slice_dir + "' TestAMD.ice")
@@ -102,11 +102,15 @@ class MyDerivedClassI(Test.MyDerivedClass):
cb.ice_response(p2, p1)
def opByteS_async(self, cb, p1, p2, current=None):
- # By default sequence<byte> maps to a string.
- p3 = map(ord, p1)
- p3.reverse()
- r = map(ord, p1)
- r.extend(map(ord, p2))
+ if sys.version_info[0] == 2:
+ # By default sequence<byte> maps to a string.
+ p3 = map(ord, p1)
+ p3.reverse()
+ r = map(ord, p1)
+ r.extend(map(ord, p2))
+ else:
+ p3 = bytes(reversed(p1))
+ r = p1 + p2
cb.ice_response(r, p3)
def opBoolS_async(self, cb, p1, p2, current=None):
diff --git a/py/test/Ice/operations/TestI.py b/py/test/Ice/operations/TestI.py
index 58505a9d0b4..c03292e1a10 100644
--- a/py/test/Ice/operations/TestI.py
+++ b/py/test/Ice/operations/TestI.py
@@ -7,7 +7,7 @@
#
# **********************************************************************
-import Ice, Test
+import Ice, Test, sys
def test(b):
if not b:
@@ -63,11 +63,15 @@ class MyDerivedClassI(Test.MyDerivedClass):
return (p2, p1)
def opByteS(self, p1, p2, current=None):
- # By default sequence<byte> maps to a string.
- p3 = map(ord, p1)
- p3.reverse()
- r = map(ord, p1)
- r.extend(map(ord, p2))
+ if sys.version_info[0] == 2:
+ # By default sequence<byte> maps to a string.
+ p3 = map(ord, p1)
+ p3.reverse()
+ r = map(ord, p1)
+ r.extend(map(ord, p2))
+ else:
+ p3 = bytes(reversed(p1))
+ r = p1 + p2
return (r, p3)
def opBoolS(self, p1, p2, current=None):
diff --git a/py/test/Ice/operations/Twoways.py b/py/test/Ice/operations/Twoways.py
index fcd33454529..117a406628b 100644
--- a/py/test/Ice/operations/Twoways.py
+++ b/py/test/Ice/operations/Twoways.py
@@ -7,7 +7,7 @@
#
# **********************************************************************
-import Ice, math, Test, array
+import Ice, math, Test, array, sys
def test(b):
if not b:
@@ -92,9 +92,10 @@ def twoways(communicator, p):
r, s = p.opString("hello", "world")
test(s == "world hello")
test(r == "hello world")
- r, s = p.opString(u"hello", u"world")
- test(s == "world hello")
- test(r == "hello world")
+ if sys.version_info[0] == 2:
+ r, s = p.opString(unicode("hello"), unicode("world"))
+ test(s == "world hello")
+ test(r == "hello world")
#
# opMyEnum
@@ -158,19 +159,33 @@ def twoways(communicator, p):
rso, bso = p.opByteS(bsi1, bsi2)
test(len(bso) == 4)
- test(bso[0] == '\x22')
- test(bso[1] == '\x12')
- test(bso[2] == '\x11')
- test(bso[3] == '\x01')
test(len(rso) == 8)
- test(rso[0] == '\x01')
- test(rso[1] == '\x11')
- test(rso[2] == '\x12')
- test(rso[3] == '\x22')
- test(rso[4] == '\xf1')
- test(rso[5] == '\xf2')
- test(rso[6] == '\xf3')
- test(rso[7] == '\xf4')
+ if sys.version_info[0] == 2:
+ test(bso[0] == '\x22')
+ test(bso[1] == '\x12')
+ test(bso[2] == '\x11')
+ test(bso[3] == '\x01')
+ test(rso[0] == '\x01')
+ test(rso[1] == '\x11')
+ test(rso[2] == '\x12')
+ test(rso[3] == '\x22')
+ test(rso[4] == '\xf1')
+ test(rso[5] == '\xf2')
+ test(rso[6] == '\xf3')
+ test(rso[7] == '\xf4')
+ else:
+ test(bso[0] == 0x22)
+ test(bso[1] == 0x12)
+ test(bso[2] == 0x11)
+ test(bso[3] == 0x01)
+ test(rso[0] == 0x01)
+ test(rso[1] == 0x11)
+ test(rso[2] == 0x12)
+ test(rso[3] == 0x22)
+ test(rso[4] == 0xf1)
+ test(rso[5] == 0xf2)
+ test(rso[6] == 0xf3)
+ test(rso[7] == 0xf4)
#
# opByteS (array)
@@ -182,19 +197,33 @@ def twoways(communicator, p):
rso, bso = p.opByteS(bsi1, bsi2)
test(len(bso) == 4)
- test(bso[0] == '\x22')
- test(bso[1] == '\x12')
- test(bso[2] == '\x11')
- test(bso[3] == '\x01')
test(len(rso) == 8)
- test(rso[0] == '\x01')
- test(rso[1] == '\x11')
- test(rso[2] == '\x12')
- test(rso[3] == '\x22')
- test(rso[4] == '\xf1')
- test(rso[5] == '\xf2')
- test(rso[6] == '\xf3')
- test(rso[7] == '\xf4')
+ if sys.version_info[0] == 2:
+ test(bso[0] == '\x22')
+ test(bso[1] == '\x12')
+ test(bso[2] == '\x11')
+ test(bso[3] == '\x01')
+ test(rso[0] == '\x01')
+ test(rso[1] == '\x11')
+ test(rso[2] == '\x12')
+ test(rso[3] == '\x22')
+ test(rso[4] == '\xf1')
+ test(rso[5] == '\xf2')
+ test(rso[6] == '\xf3')
+ test(rso[7] == '\xf4')
+ else:
+ test(bso[0] == 0x22)
+ test(bso[1] == 0x12)
+ test(bso[2] == 0x11)
+ test(bso[3] == 0x01)
+ test(rso[0] == 0x01)
+ test(rso[1] == 0x11)
+ test(rso[2] == 0x12)
+ test(rso[3] == 0x22)
+ test(rso[4] == 0xf1)
+ test(rso[5] == 0xf2)
+ test(rso[6] == 0xf3)
+ test(rso[7] == 0xf4)
#
# opBoolS
@@ -362,23 +391,36 @@ def twoways(communicator, p):
rso, bso = p.opByteSS(bsi1, bsi2)
test(len(bso) == 2)
test(len(bso[0]) == 1)
- test(bso[0][0] == '\xff')
test(len(bso[1]) == 3)
- test(bso[1][0] == '\x01')
- test(bso[1][1] == '\x11')
- test(bso[1][2] == '\x12')
test(len(rso) == 4)
test(len(rso[0]) == 3)
- test(rso[0][0] == '\x01')
- test(rso[0][1] == '\x11')
- test(rso[0][2] == '\x12')
test(len(rso[1]) == 1)
- test(rso[1][0] == '\xff')
test(len(rso[2]) == 1)
- test(rso[2][0] == '\x0e')
test(len(rso[3]) == 2)
- test(rso[3][0] == '\xf2')
- test(rso[3][1] == '\xf1')
+ if sys.version_info[0] == 2:
+ test(bso[0][0] == '\xff')
+ test(bso[1][0] == '\x01')
+ test(bso[1][1] == '\x11')
+ test(bso[1][2] == '\x12')
+ test(rso[0][0] == '\x01')
+ test(rso[0][1] == '\x11')
+ test(rso[0][2] == '\x12')
+ test(rso[1][0] == '\xff')
+ test(rso[2][0] == '\x0e')
+ test(rso[3][0] == '\xf2')
+ test(rso[3][1] == '\xf1')
+ else:
+ test(bso[0][0] == 0xff)
+ test(bso[1][0] == 0x01)
+ test(bso[1][1] == 0x11)
+ test(bso[1][2] == 0x12)
+ test(rso[0][0] == 0x01)
+ test(rso[0][1] == 0x11)
+ test(rso[0][2] == 0x12)
+ test(rso[1][0] == 0xff)
+ test(rso[2][0] == 0x0e)
+ test(rso[3][0] == 0xf2)
+ test(rso[3][1] == 0xf1)
#
# opFloatDoubleSS
diff --git a/py/test/Ice/operations/TwowaysAMI.py b/py/test/Ice/operations/TwowaysAMI.py
index 5a231a52eb8..834f19748bd 100644
--- a/py/test/Ice/operations/TwowaysAMI.py
+++ b/py/test/Ice/operations/TwowaysAMI.py
@@ -7,7 +7,7 @@
#
# **********************************************************************
-import Ice, Test, math, threading
+import Ice, Test, math, sys, threading
def test(b):
if not b:
@@ -189,19 +189,33 @@ class AMI_MyClass_opByteSI(CallbackBase):
def ice_response(self, rso, bso):
test(len(bso) == 4)
- test(bso[0] == '\x22')
- test(bso[1] == '\x12')
- test(bso[2] == '\x11')
- test(bso[3] == '\x01')
test(len(rso) == 8)
- test(rso[0] == '\x01')
- test(rso[1] == '\x11')
- test(rso[2] == '\x12')
- test(rso[3] == '\x22')
- test(rso[4] == '\xf1')
- test(rso[5] == '\xf2')
- test(rso[6] == '\xf3')
- test(rso[7] == '\xf4')
+ if sys.version_info[0] == 2:
+ test(bso[0] == '\x22')
+ test(bso[1] == '\x12')
+ test(bso[2] == '\x11')
+ test(bso[3] == '\x01')
+ test(rso[0] == '\x01')
+ test(rso[1] == '\x11')
+ test(rso[2] == '\x12')
+ test(rso[3] == '\x22')
+ test(rso[4] == '\xf1')
+ test(rso[5] == '\xf2')
+ test(rso[6] == '\xf3')
+ test(rso[7] == '\xf4')
+ else:
+ test(bso[0] == 0x22)
+ test(bso[1] == 0x12)
+ test(bso[2] == 0x11)
+ test(bso[3] == 0x01)
+ test(rso[0] == 0x01)
+ test(rso[1] == 0x11)
+ test(rso[2] == 0x12)
+ test(rso[3] == 0x22)
+ test(rso[4] == 0xf1)
+ test(rso[5] == 0xf2)
+ test(rso[6] == 0xf3)
+ test(rso[7] == 0xf4)
self.called()
def ice_exception(self, ex):
@@ -305,23 +319,36 @@ class AMI_MyClass_opByteSSI(CallbackBase):
def ice_response(self, rso, bso):
test(len(bso) == 2)
test(len(bso[0]) == 1)
- test(bso[0][0] == '\xff')
test(len(bso[1]) == 3)
- test(bso[1][0] == '\x01')
- test(bso[1][1] == '\x11')
- test(bso[1][2] == '\x12')
test(len(rso) == 4)
test(len(rso[0]) == 3)
- test(rso[0][0] == '\x01')
- test(rso[0][1] == '\x11')
- test(rso[0][2] == '\x12')
test(len(rso[1]) == 1)
- test(rso[1][0] == '\xff')
test(len(rso[2]) == 1)
- test(rso[2][0] == '\x0e')
test(len(rso[3]) == 2)
- test(rso[3][0] == '\xf2')
- test(rso[3][1] == '\xf1')
+ if sys.version_info[0] == 2:
+ test(bso[0][0] == '\xff')
+ test(bso[1][0] == '\x01')
+ test(bso[1][1] == '\x11')
+ test(bso[1][2] == '\x12')
+ test(rso[0][0] == '\x01')
+ test(rso[0][1] == '\x11')
+ test(rso[0][2] == '\x12')
+ test(rso[1][0] == '\xff')
+ test(rso[2][0] == '\x0e')
+ test(rso[3][0] == '\xf2')
+ test(rso[3][1] == '\xf1')
+ else:
+ test(bso[0][0] == 0xff)
+ test(bso[1][0] == 0x01)
+ test(bso[1][1] == 0x11)
+ test(bso[1][2] == 0x12)
+ test(rso[0][0] == 0x01)
+ test(rso[0][1] == 0x11)
+ test(rso[0][2] == 0x12)
+ test(rso[1][0] == 0xff)
+ test(rso[2][0] == 0x0e)
+ test(rso[3][0] == 0xf2)
+ test(rso[3][1] == 0xf1)
self.called()
def ice_exception(self, ex):
diff --git a/py/test/Ice/operations/TwowaysNewAMI.py b/py/test/Ice/operations/TwowaysNewAMI.py
index ec510969a54..9ab205f238f 100644
--- a/py/test/Ice/operations/TwowaysNewAMI.py
+++ b/py/test/Ice/operations/TwowaysNewAMI.py
@@ -7,7 +7,7 @@
#
# **********************************************************************
-import Ice, Test, math, threading
+import Ice, Test, math, sys, threading
def test(b):
if not b:
@@ -117,19 +117,33 @@ class Callback(CallbackBase):
def opByteS(self, rso, bso):
test(len(bso) == 4)
- test(bso[0] == '\x22')
- test(bso[1] == '\x12')
- test(bso[2] == '\x11')
- test(bso[3] == '\x01')
test(len(rso) == 8)
- test(rso[0] == '\x01')
- test(rso[1] == '\x11')
- test(rso[2] == '\x12')
- test(rso[3] == '\x22')
- test(rso[4] == '\xf1')
- test(rso[5] == '\xf2')
- test(rso[6] == '\xf3')
- test(rso[7] == '\xf4')
+ if sys.version_info[0] == 2:
+ test(bso[0] == '\x22')
+ test(bso[1] == '\x12')
+ test(bso[2] == '\x11')
+ test(bso[3] == '\x01')
+ test(rso[0] == '\x01')
+ test(rso[1] == '\x11')
+ test(rso[2] == '\x12')
+ test(rso[3] == '\x22')
+ test(rso[4] == '\xf1')
+ test(rso[5] == '\xf2')
+ test(rso[6] == '\xf3')
+ test(rso[7] == '\xf4')
+ else:
+ test(bso[0] == 0x22)
+ test(bso[1] == 0x12)
+ test(bso[2] == 0x11)
+ test(bso[3] == 0x01)
+ test(rso[0] == 0x01)
+ test(rso[1] == 0x11)
+ test(rso[2] == 0x12)
+ test(rso[3] == 0x22)
+ test(rso[4] == 0xf1)
+ test(rso[5] == 0xf2)
+ test(rso[6] == 0xf3)
+ test(rso[7] == 0xf4)
self.called()
def opBoolS(self, rso, bso):
@@ -198,23 +212,36 @@ class Callback(CallbackBase):
def opByteSS(self, rso, bso):
test(len(bso) == 2)
test(len(bso[0]) == 1)
- test(bso[0][0] == '\xff')
test(len(bso[1]) == 3)
- test(bso[1][0] == '\x01')
- test(bso[1][1] == '\x11')
- test(bso[1][2] == '\x12')
test(len(rso) == 4)
test(len(rso[0]) == 3)
- test(rso[0][0] == '\x01')
- test(rso[0][1] == '\x11')
- test(rso[0][2] == '\x12')
test(len(rso[1]) == 1)
- test(rso[1][0] == '\xff')
test(len(rso[2]) == 1)
- test(rso[2][0] == '\x0e')
test(len(rso[3]) == 2)
- test(rso[3][0] == '\xf2')
- test(rso[3][1] == '\xf1')
+ if sys.version_info[0] == 2:
+ test(bso[0][0] == '\xff')
+ test(bso[1][0] == '\x01')
+ test(bso[1][1] == '\x11')
+ test(bso[1][2] == '\x12')
+ test(rso[0][0] == '\x01')
+ test(rso[0][1] == '\x11')
+ test(rso[0][2] == '\x12')
+ test(rso[1][0] == '\xff')
+ test(rso[2][0] == '\x0e')
+ test(rso[3][0] == '\xf2')
+ test(rso[3][1] == '\xf1')
+ else:
+ test(bso[0][0] == 0xff)
+ test(bso[1][0] == 0x01)
+ test(bso[1][1] == 0x11)
+ test(bso[1][2] == 0x12)
+ test(rso[0][0] == 0x01)
+ test(rso[0][1] == 0x11)
+ test(rso[0][2] == 0x12)
+ test(rso[1][0] == 0xff)
+ test(rso[2][0] == 0x0e)
+ test(rso[3][0] == 0xf2)
+ test(rso[3][1] == 0xf1)
self.called()
def opFloatDoubleSS(self, rso, fso, dso):
diff --git a/py/test/Ice/operations/run.py b/py/test/Ice/operations/run.py
index 8101d1c0729..29e1062ae3f 100755
--- a/py/test/Ice/operations/run.py
+++ b/py/test/Ice/operations/run.py
@@ -16,14 +16,13 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
-sys.path.append(os.path.join(path[0]))
-from scripts import *
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0], "scripts"))
+import TestUtil
-print "tests with regular server."
+print("tests with regular server.")
TestUtil.clientServerTest()
-print "tests with AMD server."
+print("tests with AMD server.")
TestUtil.clientServerTest(server="ServerAMD.py")
-print "tests with collocated server."
+print("tests with collocated server.")
TestUtil.collocatedTest(" --Ice.ThreadPool.Client.SizeMax=2 --Ice.ThreadPool.Client.SizeWarn=0")
-
diff --git a/py/test/Ice/properties/Client.py b/py/test/Ice/properties/Client.py
index 517c3b14205..49b2bde3982 100644
--- a/py/test/Ice/properties/Client.py
+++ b/py/test/Ice/properties/Client.py
@@ -27,7 +27,8 @@ class Client(Ice.Application):
test(self.appName() == properties.getProperty("Ice.ProgramName"))
-print "testing load properties from UTF-8 path... ",
+sys.stdout.write("testing load properties from UTF-8 path... ")
+sys.stdout.flush()
id = Ice.InitializationData()
id.properties = Ice.createProperties()
id.properties.load("./config/中国_client.config")
@@ -35,10 +36,11 @@ test(id.properties.getProperty("Ice.Trace.Network") == "1")
test(id.properties.getProperty("Ice.Trace.Protocol") == "1")
test(id.properties.getProperty("Config.Path") == "./config/中国_client.config")
test(id.properties.getProperty("Ice.ProgramName") == "PropertiesClient")
-print "ok"
-print "testing load properties from UTF-8 path using Ice::Application... ",
+print("ok")
+sys.stdout.write("testing load properties from UTF-8 path using Ice::Application... ")
+sys.stdout.flush()
c = Client()
c.main(sys.argv, "./config/中国_client.config")
-print "ok"
+print("ok")
-sys.exit(0) \ No newline at end of file
+sys.exit(0)
diff --git a/py/test/Ice/properties/run.py b/py/test/Ice/properties/run.py
index cd59de5b863..bd4e789bd08 100755
--- a/py/test/Ice/properties/run.py
+++ b/py/test/Ice/properties/run.py
@@ -17,21 +17,30 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
-sys.path.append(os.path.join(path[0]))
-from scripts import *
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0], "scripts"))
+import TestUtil
#
# Write config
#
-configPath = u"./config/中国_client.config"
-
-TestUtil.createConfig(configPath,
- ["# Automatically generated by Ice test driver.",
- "Ice.Trace.Protocol=1",
- "Ice.Trace.Network=1",
- "Ice.ProgramName=PropertiesClient",
- "Config.Path=./config/中国_client.config"])
+if sys.version_info[0] == 2:
+ configPath = "./config/\xe4\xb8\xad\xe5\x9b\xbd_client.config".decode("utf-8")
+ TestUtil.createConfig(configPath,
+ ["# Automatically generated by Ice test driver.",
+ "Ice.Trace.Protocol=1",
+ "Ice.Trace.Network=1",
+ "Ice.ProgramName=PropertiesClient",
+ "Config.Path=./config/中国_client.config"])
+else:
+ configPath = "./config/\u4e2d\u56fd_client.config"
+ TestUtil.createConfig(configPath,
+ ["# Automatically generated by Ice test driver.",
+ "Ice.Trace.Protocol=1",
+ "Ice.Trace.Network=1",
+ "Ice.ProgramName=PropertiesClient",
+ "Config.Path=" + configPath],
+ "utf-8")
TestUtil.simpleTest()
diff --git a/py/test/Ice/proxy/AllTests.py b/py/test/Ice/proxy/AllTests.py
index 84817d1cbd9..4880e4d6b98 100644
--- a/py/test/Ice/proxy/AllTests.py
+++ b/py/test/Ice/proxy/AllTests.py
@@ -7,14 +7,15 @@
#
# **********************************************************************
-import Ice, Test, threading
+import Ice, Test, sys, threading
def test(b):
if not b:
raise RuntimeError('test assertion failed')
def allTests(communicator, collocated):
- print "testing stringToProxy...",
+ sys.stdout.write("testing stringToProxy... ")
+ sys.stdout.flush()
#
# Test nil proxies.
@@ -192,9 +193,10 @@ def allTests(communicator, collocated):
test(False)
except Ice.EndpointParseException:
pass
- print "ok"
+ print("ok")
- print "testing propertyToProxy... ",
+ sys.stdout.write("testing propertyToProxy... ")
+ sys.stdout.flush()
prop = communicator.getProperties()
propertyPrefix = "Foo.Proxy"
prop.setProperty(propertyPrefix, "test:default -p 12010")
@@ -283,9 +285,10 @@ def allTests(communicator, collocated):
#test(not b1.ice_isCollocationOptimized())
#prop.setProperty(property, "")
- print "ok"
+ print("ok")
- print "testing proxyToProperty... ",
+ sys.stdout.write("testing proxyToProperty... ")
+ sys.stdout.flush()
b1 = communicator.stringToProxy("test")
#b1 = b1.ice_collocationOptimized(true)
@@ -335,14 +338,17 @@ def allTests(communicator, collocated):
test(proxyProps["Test.Locator.Router.EndpointSelection"] == "Random")
test(proxyProps["Test.Locator.Router.LocatorCacheTimeout"] == "200")
- print "ok"
+ print("ok")
- print "testing ice_getCommunicator...",
+ sys.stdout.write("testing ice_getCommunicator... ")
+ sys.stdout.flush()
test(base.ice_getCommunicator() == communicator)
- print "ok"
- print "testing proxy methods... ",
+ print("ok")
+
+ sys.stdout.write("testing proxy methods... ")
+ sys.stdout.flush()
test(communicator.identityToString(base.ice_identity(communicator.stringToIdentity("other")).ice_getIdentity()) \
== "other")
test(base.ice_facet("facet").ice_getFacet() == "facet")
@@ -358,9 +364,10 @@ def allTests(communicator, collocated):
#test(!base.ice_collocationOptimized(false)->ice_isCollocationOptimized())
test(base.ice_preferSecure(True).ice_isPreferSecure())
test(not base.ice_preferSecure(False).ice_isPreferSecure())
- print "ok"
+ print("ok")
- print "testing proxy comparison... ",
+ sys.stdout.write("testing proxy comparison... ")
+ sys.stdout.flush()
test(communicator.stringToProxy("foo") == communicator.stringToProxy("foo"))
test(communicator.stringToProxy("foo") != communicator.stringToProxy("foo2"))
@@ -495,9 +502,10 @@ def allTests(communicator, collocated):
# TODO: Ideally we should also test comparison of fixed proxies.
#
- print "ok"
+ print("ok")
- print "testing checked cast...",
+ sys.stdout.write("testing checked cast... ")
+ sys.stdout.flush()
cl = Test.MyClassPrx.checkedCast(base)
test(cl)
@@ -520,9 +528,10 @@ def allTests(communicator, collocated):
test(cl2 == obj)
test(cl2 == derived)
- print "ok"
+ print("ok")
- print "testing checked cast with context...",
+ sys.stdout.write("testing checked cast with context... ")
+ sys.stdout.flush()
tccp = Test.MyClassPrx.checkedCast(base)
c = tccp.getContext()
test(c == None or len(c) == 0)
@@ -533,9 +542,10 @@ def allTests(communicator, collocated):
tccp = Test.MyClassPrx.checkedCast(base, c)
c2 = tccp.getContext()
test(c == c2)
- print "ok"
+ print("ok")
- print "testing opaque endpoints... ",
+ sys.stdout.write("testing opaque endpoints... ")
+ sys.stdout.flush()
try:
# Invalid -x option
@@ -667,6 +677,6 @@ def allTests(communicator, collocated):
else:
test(pstr == "test -t:ssl -h 127.0.0.1 -p 10001:opaque -t 99 -v abch")
- print "ok"
+ print("ok")
return cl
diff --git a/py/test/Ice/proxy/Client.py b/py/test/Ice/proxy/Client.py
index 8dfe00d4e4a..422e2ed912d 100755
--- a/py/test/Ice/proxy/Client.py
+++ b/py/test/Ice/proxy/Client.py
@@ -13,7 +13,7 @@ import os, sys, traceback
import Ice
slice_dir = Ice.getSliceDir()
if not slice_dir:
- print sys.argv[0] + ': Slice directory not found.'
+ print(sys.argv[0] + ': Slice directory not found.')
sys.exit(1)
Ice.loadSlice("'-I" + slice_dir + "' Test.ice")
diff --git a/py/test/Ice/proxy/Collocated.py b/py/test/Ice/proxy/Collocated.py
index 729f2358d5f..48edb3fb70a 100755
--- a/py/test/Ice/proxy/Collocated.py
+++ b/py/test/Ice/proxy/Collocated.py
@@ -13,7 +13,7 @@ import os, sys, traceback
import Ice
slice_dir = Ice.getSliceDir()
if not slice_dir:
- print sys.argv[0] + ': Slice directory not found.'
+ print(sys.argv[0] + ': Slice directory not found.')
sys.exit(1)
Ice.loadSlice("'-I" + slice_dir + "' Test.ice")
diff --git a/py/test/Ice/proxy/Server.py b/py/test/Ice/proxy/Server.py
index a36a70e19b7..2629cae1e33 100755
--- a/py/test/Ice/proxy/Server.py
+++ b/py/test/Ice/proxy/Server.py
@@ -13,7 +13,7 @@ import os, sys, traceback
import Ice
slice_dir = Ice.getSliceDir()
if not slice_dir:
- print sys.argv[0] + ': Slice directory not found.'
+ print(sys.argv[0] + ': Slice directory not found.')
sys.exit(1)
Ice.loadSlice("'-I" + slice_dir + "' Test.ice")
diff --git a/py/test/Ice/proxy/ServerAMD.py b/py/test/Ice/proxy/ServerAMD.py
index 6723275d074..a7641fe6fbf 100755
--- a/py/test/Ice/proxy/ServerAMD.py
+++ b/py/test/Ice/proxy/ServerAMD.py
@@ -13,7 +13,7 @@ import os, sys, traceback, time
import Ice
slice_dir = Ice.getSliceDir()
if not slice_dir:
- print sys.argv[0] + ': Slice directory not found.'
+ print(sys.argv[0] + ': Slice directory not found.')
sys.exit(1)
Ice.loadSlice("'-I" + slice_dir + "' TestAMD.ice")
diff --git a/py/test/Ice/proxy/run.py b/py/test/Ice/proxy/run.py
index 8101d1c0729..29e1062ae3f 100755
--- a/py/test/Ice/proxy/run.py
+++ b/py/test/Ice/proxy/run.py
@@ -16,14 +16,13 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
-sys.path.append(os.path.join(path[0]))
-from scripts import *
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0], "scripts"))
+import TestUtil
-print "tests with regular server."
+print("tests with regular server.")
TestUtil.clientServerTest()
-print "tests with AMD server."
+print("tests with AMD server.")
TestUtil.clientServerTest(server="ServerAMD.py")
-print "tests with collocated server."
+print("tests with collocated server.")
TestUtil.collocatedTest(" --Ice.ThreadPool.Client.SizeMax=2 --Ice.ThreadPool.Client.SizeWarn=0")
-
diff --git a/py/test/Ice/retry/AllTests.py b/py/test/Ice/retry/AllTests.py
index d97ac2197b5..dfd1098b344 100644
--- a/py/test/Ice/retry/AllTests.py
+++ b/py/test/Ice/retry/AllTests.py
@@ -7,7 +7,7 @@
#
# **********************************************************************
-import Ice, Test, threading
+import Ice, Test, sys, threading
def test(b):
if not b:
@@ -49,54 +49,62 @@ class CallbackFail(CallbackBase):
self.called()
def allTests(communicator):
- print "testing stringToProxy...",
+ sys.stdout.write("testing stringToProxy... ")
+ sys.stdout.flush()
ref = "retry:default -p 12010"
base1 = communicator.stringToProxy(ref)
test(base1)
base2 = communicator.stringToProxy(ref)
test(base2)
- print "ok"
+ print("ok")
- print "testing checked cast...",
+ sys.stdout.write("testing checked cast... ")
+ sys.stdout.flush()
retry1 = Test.RetryPrx.checkedCast(base1)
test(retry1)
test(retry1 == base1)
retry2 = Test.RetryPrx.checkedCast(base2)
test(retry2)
test(retry2 == base2)
- print "ok"
+ print("ok")
- print "calling regular operation with first proxy...",
+ sys.stdout.write("calling regular operation with first proxy... ")
+ sys.stdout.flush()
retry1.op(False)
- print "ok"
+ print("ok")
- print "calling operation to kill connection with second proxy...",
+ sys.stdout.write("calling operation to kill connection with second proxy... ")
+ sys.stdout.flush()
try:
retry2.op(True)
test(False)
except Ice.ConnectionLostException:
- print "ok"
+ print("ok")
- print "calling regular operation with first proxy again...",
+ sys.stdout.write("calling regular operation with first proxy again... ")
+ sys.stdout.flush()
retry1.op(False)
- print "ok"
+ print("ok")
cb1 = CallbackSuccess()
cb2 = CallbackFail()
- print "calling regular AMI operation with first proxy...",
+ sys.stdout.write("calling regular AMI operation with first proxy... ")
+ sys.stdout.flush()
retry1.begin_op(False, cb1.response, cb1.exception)
cb1.check()
- print "ok"
+ print("ok")
- print "calling AMI operation to kill connection with second proxy...",
+ sys.stdout.write("calling AMI operation to kill connection with second proxy... ")
+ sys.stdout.flush()
retry2.begin_op(True, cb2.response, cb2.exception)
cb2.check()
- print "ok"
+ print("ok")
- print "calling regular AMI operation with first proxy again...",
+ sys.stdout.write("calling regular AMI operation with first proxy again... ")
+ sys.stdout.flush()
retry1.begin_op(False, cb1.response, cb1.exception)
cb1.check()
- print "ok"
+ print("ok")
return retry1
diff --git a/py/test/Ice/retry/Client.py b/py/test/Ice/retry/Client.py
index 1408a08ae86..a51c1fc414a 100755
--- a/py/test/Ice/retry/Client.py
+++ b/py/test/Ice/retry/Client.py
@@ -13,7 +13,7 @@ import os, sys, traceback
import Ice
slice_dir = Ice.getSliceDir()
if not slice_dir:
- print sys.argv[0] + ': Slice directory not found.'
+ print(sys.argv[0] + ': Slice directory not found.')
sys.exit(1)
Ice.loadSlice("'-I" + slice_dir + "' Test.ice")
diff --git a/py/test/Ice/retry/Server.py b/py/test/Ice/retry/Server.py
index a0d3abbb809..16acd4af64c 100755
--- a/py/test/Ice/retry/Server.py
+++ b/py/test/Ice/retry/Server.py
@@ -13,7 +13,7 @@ import os, sys, traceback
import Ice
slice_dir = Ice.getSliceDir()
if not slice_dir:
- print sys.argv[0] + ': Slice directory not found.'
+ print(sys.argv[0] + ': Slice directory not found.')
sys.exit(1)
Ice.loadSlice("'-I" + slice_dir + "' Test.ice")
diff --git a/py/test/Ice/retry/run.py b/py/test/Ice/retry/run.py
index 32ea526c3b4..2265a40ca12 100755
--- a/py/test/Ice/retry/run.py
+++ b/py/test/Ice/retry/run.py
@@ -16,9 +16,8 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
-sys.path.append(os.path.join(path[0]))
-from scripts import *
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0], "scripts"))
+import TestUtil
TestUtil.clientServerTest()
-
diff --git a/py/test/Ice/servantLocator/AllTests.py b/py/test/Ice/servantLocator/AllTests.py
index b21325b6eea..c4553cbca94 100644
--- a/py/test/Ice/servantLocator/AllTests.py
+++ b/py/test/Ice/servantLocator/AllTests.py
@@ -18,7 +18,7 @@ def testExceptions(obj, collocated):
try:
obj.requestFailedException()
test(False)
- except Ice.ObjectNotExistException, ex:
+ except Ice.ObjectNotExistException as ex:
if not collocated:
test(ex.id == obj.ice_getIdentity())
test(ex.facet == obj.ice_getFacet())
@@ -29,7 +29,7 @@ def testExceptions(obj, collocated):
try:
obj.unknownUserException()
test(False)
- except Ice.UnknownUserException, ex:
+ except Ice.UnknownUserException as ex:
test(ex.unknown == "reason")
except:
test(False)
@@ -37,7 +37,7 @@ def testExceptions(obj, collocated):
try:
obj.unknownLocalException()
test(False)
- except Ice.UnknownLocalException, ex:
+ except Ice.UnknownLocalException as ex:
test(ex.unknown == "reason")
except:
test(False)
@@ -45,14 +45,14 @@ def testExceptions(obj, collocated):
try:
obj.unknownException()
test(False)
- except Ice.UnknownException, ex:
+ except Ice.UnknownException as ex:
test(ex.unknown == "reason")
pass
try:
obj.userException()
test(False)
- except Ice.UnknownUserException, ex:
+ except Ice.UnknownUserException as ex:
test(ex.unknown.find("Test::TestIntfUserException") >= 0)
except:
test(False)
@@ -60,7 +60,7 @@ def testExceptions(obj, collocated):
try:
obj.localException()
test(False)
- except Ice.UnknownLocalException, ex:
+ except Ice.UnknownLocalException as ex:
test(not collocated)
test(ex.unknown.find("Ice.SocketException") >= 0)
except SocketException:
@@ -71,7 +71,7 @@ def testExceptions(obj, collocated):
try:
obj.pythonException()
test(False)
- except Ice.UnknownException, ex:
+ except Ice.UnknownException as ex:
test(ex.unknown.find("RuntimeError: message") >= 0)
except:
test(False)
@@ -79,7 +79,7 @@ def testExceptions(obj, collocated):
try:
obj.unknownExceptionWithServantException()
test(False)
- except Ice.UnknownException, ex:
+ except Ice.UnknownException as ex:
test(ex.unknown == "reason")
except:
test(False)
@@ -121,26 +121,26 @@ def testExceptions(obj, collocated):
test(False)
def allTests(communicator, collocated):
- print "testing stringToProxy...",
+ sys.stdout.write("testing stringToProxy... ")
sys.stdout.flush()
base = communicator.stringToProxy("asm:default -p 12010")
test(base)
- print "ok"
+ print("ok")
- print "testing checked cast...",
+ sys.stdout.write("testing checked cast... ")
sys.stdout.flush()
obj = Test.TestIntfPrx.checkedCast(base)
test(obj)
test(obj == base)
- print "ok"
+ print("ok")
- print "testing ice_ids...",
+ sys.stdout.write("testing ice_ids... ")
sys.stdout.flush()
try:
obj = communicator.stringToProxy("category/locate:default -p 12010")
obj.ice_ids()
test(False)
- except Ice.UnknownUserException, ex:
+ except Ice.UnknownUserException as ex:
test(ex.unknown == "Test::TestIntfUserException")
except:
test(False)
@@ -149,13 +149,13 @@ def allTests(communicator, collocated):
obj = communicator.stringToProxy("category/finished:default -p 12010")
obj.ice_ids()
test(False)
- except Ice.UnknownUserException, ex:
+ except Ice.UnknownUserException as ex:
test(ex.unknown == "Test::TestIntfUserException")
except:
test(False)
- print "ok"
+ print("ok")
- print "testing servant locator...",
+ sys.stdout.write("testing servant locator... ")
sys.stdout.flush()
base = communicator.stringToProxy("category/locate:default -p 12010")
obj = Test.TestIntfPrx.checkedCast(base)
@@ -163,9 +163,9 @@ def allTests(communicator, collocated):
Test.TestIntfPrx.checkedCast(communicator.stringToProxy("category/unknown:default -p 12010"))
except Ice.ObjectNotExistException:
pass
- print "ok"
+ print("ok")
- print "testing default servant locator...",
+ sys.stdout.write("testing default servant locator... ")
sys.stdout.flush()
base = communicator.stringToProxy("anothercat/locate:default -p 12010")
obj = Test.TestIntfPrx.checkedCast(base)
@@ -179,23 +179,23 @@ def allTests(communicator, collocated):
Test.TestIntfPrx.checkedCast(communicator.stringToProxy("unknown:default -p 12010"))
except Ice.ObjectNotExistException:
pass
- print "ok"
+ print("ok")
- print "testing locate exceptions...",
+ sys.stdout.write("testing locate exceptions... ")
sys.stdout.flush()
base = communicator.stringToProxy("category/locate:default -p 12010")
obj = Test.TestIntfPrx.checkedCast(base)
testExceptions(obj, collocated)
- print "ok"
+ print("ok")
- print "testing finished exceptions...",
+ sys.stdout.write("testing finished exceptions... ")
sys.stdout.flush()
base = communicator.stringToProxy("category/finished:default -p 12010")
obj = Test.TestIntfPrx.checkedCast(base)
testExceptions(obj, collocated)
- print "ok"
+ print("ok")
- print "testing servant locator removal...",
+ sys.stdout.write("testing servant locator removal... ")
sys.stdout.flush()
base = communicator.stringToProxy("test/activation:default -p 12010")
activation = Test.TestActivationPrx.checkedCast(base)
@@ -205,15 +205,15 @@ def allTests(communicator, collocated):
test(False)
except Ice.ObjectNotExistException:
pass
- print "ok"
+ print("ok")
- print "testing servant locator addition...",
+ sys.stdout.write("testing servant locator addition... ")
sys.stdout.flush()
activation.activateServantLocator(True)
try:
obj.ice_ping()
except:
test(False)
- print "ok"
+ print("ok")
return obj
diff --git a/py/test/Ice/servantLocator/run.py b/py/test/Ice/servantLocator/run.py
index 8101d1c0729..29e1062ae3f 100755
--- a/py/test/Ice/servantLocator/run.py
+++ b/py/test/Ice/servantLocator/run.py
@@ -16,14 +16,13 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
-sys.path.append(os.path.join(path[0]))
-from scripts import *
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0], "scripts"))
+import TestUtil
-print "tests with regular server."
+print("tests with regular server.")
TestUtil.clientServerTest()
-print "tests with AMD server."
+print("tests with AMD server.")
TestUtil.clientServerTest(server="ServerAMD.py")
-print "tests with collocated server."
+print("tests with collocated server.")
TestUtil.collocatedTest(" --Ice.ThreadPool.Client.SizeMax=2 --Ice.ThreadPool.Client.SizeWarn=0")
-
diff --git a/py/test/Ice/slicing/exceptions/AllTests.py b/py/test/Ice/slicing/exceptions/AllTests.py
index 9e44f294a3a..5bedb5d4f71 100644
--- a/py/test/Ice/slicing/exceptions/AllTests.py
+++ b/py/test/Ice/slicing/exceptions/AllTests.py
@@ -44,7 +44,7 @@ class Callback(CallbackBase):
def exception_baseAsBase(self, exc):
try:
raise exc
- except Test.Base, b:
+ except Test.Base as b:
test(b.b == "Base.b")
test(b.ice_name() =="Test::Base")
except:
@@ -54,7 +54,7 @@ class Callback(CallbackBase):
def exception_unknownDerivedAsBase(self, exc):
try:
raise exc
- except Test.Base, b:
+ except Test.Base as b:
test(b.b == "UnknownDerived.b")
test(b.ice_name() =="Test::Base")
except:
@@ -64,7 +64,7 @@ class Callback(CallbackBase):
def exception_knownDerivedAsBase(self, exc):
try:
raise exc
- except Test.KnownDerived, k:
+ except Test.KnownDerived as k:
test(k.b == "KnownDerived.b")
test(k.kd == "KnownDerived.kd")
test(k.ice_name() =="Test::KnownDerived")
@@ -75,7 +75,7 @@ class Callback(CallbackBase):
def exception_knownDerivedAsKnownDerived(self, exc):
try:
raise exc
- except Test.KnownDerived, k:
+ except Test.KnownDerived as k:
test(k.b == "KnownDerived.b")
test(k.kd == "KnownDerived.kd")
test(k.ice_name() =="Test::KnownDerived")
@@ -86,7 +86,7 @@ class Callback(CallbackBase):
def exception_unknownIntermediateAsBase(self, exc):
try:
raise exc
- except Test.Base, b:
+ except Test.Base as b:
test(b.b == "UnknownIntermediate.b")
test(b.ice_name() =="Test::Base")
except:
@@ -96,7 +96,7 @@ class Callback(CallbackBase):
def exception_knownIntermediateAsBase(self, exc):
try:
raise exc
- except Test.KnownIntermediate, ki:
+ except Test.KnownIntermediate as ki:
test(ki.b == "KnownIntermediate.b")
test(ki.ki == "KnownIntermediate.ki")
test(ki.ice_name() =="Test::KnownIntermediate")
@@ -107,7 +107,7 @@ class Callback(CallbackBase):
def exception_knownMostDerivedAsBase(self, exc):
try:
raise exc
- except Test.KnownMostDerived, kmd:
+ except Test.KnownMostDerived as kmd:
test(kmd.b == "KnownMostDerived.b")
test(kmd.ki == "KnownMostDerived.ki")
test(kmd.kmd == "KnownMostDerived.kmd")
@@ -119,7 +119,7 @@ class Callback(CallbackBase):
def exception_knownIntermediateAsKnownIntermediate(self, exc):
try:
raise exc
- except Test.KnownIntermediate, ki:
+ except Test.KnownIntermediate as ki:
test(ki.b == "KnownIntermediate.b")
test(ki.ki == "KnownIntermediate.ki")
test(ki.ice_name() =="Test::KnownIntermediate")
@@ -130,7 +130,7 @@ class Callback(CallbackBase):
def exception_knownMostDerivedAsKnownMostDerived(self, exc):
try:
raise exc
- except Test.KnownMostDerived, kmd:
+ except Test.KnownMostDerived as kmd:
test(kmd.b == "KnownMostDerived.b")
test(kmd.ki == "KnownMostDerived.ki")
test(kmd.kmd == "KnownMostDerived.kmd")
@@ -142,7 +142,7 @@ class Callback(CallbackBase):
def exception_knownMostDerivedAsKnownIntermediate(self, exc):
try:
raise exc
- except Test.KnownMostDerived, kmd:
+ except Test.KnownMostDerived as kmd:
test(kmd.b == "KnownMostDerived.b")
test(kmd.ki == "KnownMostDerived.ki")
test(kmd.kmd == "KnownMostDerived.kmd")
@@ -154,7 +154,7 @@ class Callback(CallbackBase):
def exception_unknownMostDerived1AsBase(self, exc):
try:
raise exc
- except Test.KnownIntermediate, ki:
+ except Test.KnownIntermediate as ki:
test(ki.b == "UnknownMostDerived1.b")
test(ki.ki == "UnknownMostDerived1.ki")
test(ki.ice_name() =="Test::KnownIntermediate")
@@ -165,7 +165,7 @@ class Callback(CallbackBase):
def exception_unknownMostDerived1AsKnownIntermediate(self, exc):
try:
raise exc
- except Test.KnownIntermediate, ki:
+ except Test.KnownIntermediate as ki:
test(ki.b == "UnknownMostDerived1.b")
test(ki.ki == "UnknownMostDerived1.ki")
test(ki.ice_name() =="Test::KnownIntermediate")
@@ -176,7 +176,7 @@ class Callback(CallbackBase):
def exception_unknownMostDerived2AsBase(self, exc):
try:
raise exc
- except Test.Base, b:
+ except Test.Base as b:
test(b.b == "UnknownMostDerived2.b")
test(b.ice_name() =="Test::Base")
except:
@@ -187,237 +187,263 @@ def allTests(communicator):
obj = communicator.stringToProxy("Test:default -p 12010")
t = Test.TestIntfPrx.checkedCast(obj)
- print "base... ",
+ sys.stdout.write("base... ")
+ sys.stdout.flush()
try:
t.baseAsBase()
test(false)
- except Test.Base, b:
+ except Test.Base as b:
test(b.b == "Base.b")
test(b.ice_name() == "Test::Base")
except:
test(False)
- print "ok"
+ print("ok")
- print "base (AMI)... ",
+ sys.stdout.write("base (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_baseAsBase(cb.response, cb.exception_baseAsBase)
cb.check()
- print "ok"
+ print("ok")
- print "slicing of unknown derived... ",
+ sys.stdout.write("slicing of unknown derived... ")
+ sys.stdout.flush()
try:
t.unknownDerivedAsBase()
test(false)
- except Test.Base, b:
+ except Test.Base as b:
test(b.b == "UnknownDerived.b")
test(b.ice_name() == "Test::Base")
except:
test(False)
- print "ok"
+ print("ok")
- print "slicing of unknown derived (AMI)... ",
+ sys.stdout.write("slicing of unknown derived (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_unknownDerivedAsBase(cb.response, cb.exception_unknownDerivedAsBase)
cb.check()
- print "ok"
+ print("ok")
- print "non-slicing of known derived as base... ",
+ sys.stdout.write("non-slicing of known derived as base... ")
+ sys.stdout.flush()
try:
t.knownDerivedAsBase()
test(false)
- except Test.KnownDerived, k:
+ except Test.KnownDerived as k:
test(k.b == "KnownDerived.b")
test(k.kd == "KnownDerived.kd")
test(k.ice_name() == "Test::KnownDerived")
except:
test(False)
- print "ok"
+ print("ok")
- print "non-slicing of known derived as base (AMI)... ",
+ sys.stdout.write("non-slicing of known derived as base (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_knownDerivedAsBase(cb.response, cb.exception_knownDerivedAsBase)
cb.check()
- print "ok"
+ print("ok")
- print "non-slicing of known derived as derived... ",
+ sys.stdout.write("non-slicing of known derived as derived... ")
+ sys.stdout.flush()
try:
t.knownDerivedAsKnownDerived()
test(false)
- except Test.KnownDerived, k:
+ except Test.KnownDerived as k:
test(k.b == "KnownDerived.b")
test(k.kd == "KnownDerived.kd")
test(k.ice_name() == "Test::KnownDerived")
except:
test(False)
- print "ok"
+ print("ok")
- print "non-slicing of known derived as derived (AMI)... ",
+ sys.stdout.write("non-slicing of known derived as derived (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_knownDerivedAsKnownDerived(cb.response, cb.exception_knownDerivedAsKnownDerived)
cb.check()
- print "ok"
+ print("ok")
- print "slicing of unknown intermediate as base... ",
+ sys.stdout.write("slicing of unknown intermediate as base... ")
+ sys.stdout.flush()
try:
t.unknownIntermediateAsBase()
test(false)
- except Test.Base, b:
+ except Test.Base as b:
test(b.b == "UnknownIntermediate.b")
test(b.ice_name() == "Test::Base")
except:
test(False)
- print "ok"
+ print("ok")
- print "slicing of unknown intermediate as base (AMI)... ",
+ sys.stdout.write("slicing of unknown intermediate as base (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_unknownIntermediateAsBase(cb.response, cb.exception_unknownIntermediateAsBase)
cb.check()
- print "ok"
+ print("ok")
- print "slicing of known intermediate as base... ",
+ sys.stdout.write("slicing of known intermediate as base... ")
+ sys.stdout.flush()
try:
t.knownIntermediateAsBase()
test(false)
- except Test.KnownIntermediate, ki:
+ except Test.KnownIntermediate as ki:
test(ki.b == "KnownIntermediate.b")
test(ki.ki == "KnownIntermediate.ki")
test(ki.ice_name() == "Test::KnownIntermediate")
except:
test(False)
- print "ok"
+ print("ok")
- print "slicing of known intermediate as base (AMI)... ",
+ sys.stdout.write("slicing of known intermediate as base (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_knownIntermediateAsBase(cb.response, cb.exception_knownIntermediateAsBase)
cb.check()
- print "ok"
+ print("ok")
- print "slicing of known most derived as base... ",
+ sys.stdout.write("slicing of known most derived as base... ")
+ sys.stdout.flush()
try:
t.knownMostDerivedAsBase()
test(false)
- except Test.KnownMostDerived, kmd:
+ except Test.KnownMostDerived as kmd:
test(kmd.b == "KnownMostDerived.b")
test(kmd.ki == "KnownMostDerived.ki")
test(kmd.kmd == "KnownMostDerived.kmd")
test(kmd.ice_name() == "Test::KnownMostDerived")
except:
test(False)
- print "ok"
+ print("ok")
- print "slicing of known most derived as base (AMI)... ",
+ sys.stdout.write("slicing of known most derived as base (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_knownMostDerivedAsBase(cb.response, cb.exception_knownMostDerivedAsBase)
cb.check()
- print "ok"
+ print("ok")
- print "non-slicing of known intermediate as intermediate... ",
+ sys.stdout.write("non-slicing of known intermediate as intermediate... ")
+ sys.stdout.flush()
try:
t.knownIntermediateAsKnownIntermediate()
test(false)
- except Test.KnownIntermediate, ki:
+ except Test.KnownIntermediate as ki:
test(ki.b == "KnownIntermediate.b")
test(ki.ki == "KnownIntermediate.ki")
test(ki.ice_name() == "Test::KnownIntermediate")
except:
test(False)
- print "ok"
+ print("ok")
- print "non-slicing of known intermediate as intermediate (AMI)... ",
+ sys.stdout.write("non-slicing of known intermediate as intermediate (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_knownIntermediateAsKnownIntermediate(cb.response, cb.exception_knownIntermediateAsKnownIntermediate)
cb.check()
- print "ok"
+ print("ok")
- print "non-slicing of known most derived exception as intermediate... ",
+ sys.stdout.write("non-slicing of known most derived exception as intermediate... ")
+ sys.stdout.flush()
try:
t.knownMostDerivedAsKnownIntermediate()
test(false)
- except Test.KnownMostDerived, kmd:
+ except Test.KnownMostDerived as kmd:
test(kmd.b == "KnownMostDerived.b")
test(kmd.ki == "KnownMostDerived.ki")
test(kmd.kmd == "KnownMostDerived.kmd")
test(kmd.ice_name() == "Test::KnownMostDerived")
except:
test(False)
- print "ok"
+ print("ok")
- print "non-slicing of known most derived as intermediate (AMI)... ",
+ sys.stdout.write("non-slicing of known most derived as intermediate (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_knownMostDerivedAsKnownIntermediate(cb.response, cb.exception_knownMostDerivedAsKnownIntermediate)
cb.check()
- print "ok"
+ print("ok")
- print "non-slicing of known most derived as most derived... ",
+ sys.stdout.write("non-slicing of known most derived as most derived... ")
+ sys.stdout.flush()
try:
t.knownMostDerivedAsKnownMostDerived()
test(false)
- except Test.KnownMostDerived, kmd:
+ except Test.KnownMostDerived as kmd:
test(kmd.b == "KnownMostDerived.b")
test(kmd.ki == "KnownMostDerived.ki")
test(kmd.kmd == "KnownMostDerived.kmd")
test(kmd.ice_name() == "Test::KnownMostDerived")
except:
test(False)
- print "ok"
+ print("ok")
- print "non-slicing of known most derived as most derived (AMI)... ",
+ sys.stdout.write("non-slicing of known most derived as most derived (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_knownMostDerivedAsKnownMostDerived(cb.response, cb.exception_knownMostDerivedAsKnownMostDerived)
cb.check()
- print "ok"
+ print("ok")
- print "slicing of unknown most derived, known intermediate as base... ",
+ sys.stdout.write("slicing of unknown most derived, known intermediate as base... ")
+ sys.stdout.flush()
try:
t.unknownMostDerived1AsBase()
test(false)
- except Test.KnownIntermediate, ki:
+ except Test.KnownIntermediate as ki:
test(ki.b == "UnknownMostDerived1.b")
test(ki.ki == "UnknownMostDerived1.ki")
test(ki.ice_name() == "Test::KnownIntermediate")
except:
test(False)
- print "ok"
+ print("ok")
- print "slicing of unknown most derived, known intermediate as base (AMI)... ",
+ sys.stdout.write("slicing of unknown most derived, known intermediate as base (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_unknownMostDerived1AsBase(cb.response, cb.exception_unknownMostDerived1AsBase)
cb.check()
- print "ok"
+ print("ok")
- print "slicing of unknown most derived, known intermediate as intermediate... ",
+ sys.stdout.write("slicing of unknown most derived, known intermediate as intermediate... ")
+ sys.stdout.flush()
try:
t.unknownMostDerived1AsKnownIntermediate()
test(false)
- except Test.KnownIntermediate, ki:
+ except Test.KnownIntermediate as ki:
test(ki.b == "UnknownMostDerived1.b")
test(ki.ki == "UnknownMostDerived1.ki")
test(ki.ice_name() == "Test::KnownIntermediate")
except:
test(False)
- print "ok"
+ print("ok")
- print "slicing of unknown most derived, known intermediate as intermediate (AMI)... ",
+ sys.stdout.write("slicing of unknown most derived, known intermediate as intermediate (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_unknownMostDerived1AsKnownIntermediate(cb.response, cb.exception_unknownMostDerived1AsKnownIntermediate)
cb.check()
- print "ok"
+ print("ok")
- print "slicing of unknown most derived, unknown intermediate as base... ",
+ sys.stdout.write("slicing of unknown most derived, unknown intermediate as base... ")
+ sys.stdout.flush()
try:
t.unknownMostDerived2AsBase()
test(false)
- except Test.Base, b:
+ except Test.Base as b:
test(b.b == "UnknownMostDerived2.b")
test(b.ice_name() == "Test::Base")
except:
test(False)
- print "ok"
+ print("ok")
- print "slicing of unknown most derived, unknown intermediate as base (AMI)... ",
+ sys.stdout.write("slicing of unknown most derived, unknown intermediate as base (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_unknownMostDerived2AsBase(cb.response, cb.exception_unknownMostDerived2AsBase)
cb.check()
- print "ok"
+ print("ok")
return t
diff --git a/py/test/Ice/slicing/exceptions/run.py b/py/test/Ice/slicing/exceptions/run.py
index 141e2be507d..6af6dc0cb43 100755
--- a/py/test/Ice/slicing/exceptions/run.py
+++ b/py/test/Ice/slicing/exceptions/run.py
@@ -16,12 +16,11 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
-sys.path.append(os.path.join(path[0]))
-from scripts import *
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0], "scripts"))
+import TestUtil
-print "tests with regular server."
+print("tests with regular server.")
TestUtil.clientServerTest()
-print "tests with AMD server."
+print("tests with AMD server.")
TestUtil.clientServerTest(server="ServerAMD.py")
-
diff --git a/py/test/Ice/slicing/objects/AllTests.py b/py/test/Ice/slicing/objects/AllTests.py
index e510a4e52d1..db796665cf0 100644
--- a/py/test/Ice/slicing/objects/AllTests.py
+++ b/py/test/Ice/slicing/objects/AllTests.py
@@ -274,7 +274,8 @@ def allTests(communicator):
obj = communicator.stringToProxy("Test:default -p 12010")
t = Test.TestIntfPrx.checkedCast(obj)
- print "base as Object... ",
+ sys.stdout.write("base as Object... ")
+ sys.stdout.flush()
o = None
try:
o = t.SBaseAsObject()
@@ -286,29 +287,33 @@ def allTests(communicator):
test(isinstance(sb, Test.SBase))
test(sb)
test(sb.sb == "SBase.sb")
- print "ok"
+ print("ok")
- print "base as Object (AMI)... ",
+ sys.stdout.write("base as Object (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_SBaseAsObject(cb.response_SBaseAsObject, cb.exception)
cb.check()
- print "ok"
+ print("ok")
- print "base as base... ",
+ sys.stdout.write("base as base... ")
+ sys.stdout.flush()
try:
sb = t.SBaseAsSBase()
test(sb.sb == "SBase.sb")
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "base as base (AMI)... ",
+ sys.stdout.write("base as base (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_SBaseAsSBase(cb.response_SBaseAsSBase, cb.exception)
cb.check()
- print "ok"
+ print("ok")
- print "base with known derived as base... ",
+ sys.stdout.write("base with known derived as base... ")
+ sys.stdout.flush()
try:
sb = t.SBSKnownDerivedAsSBase()
test(sb.sb == "SBSKnownDerived.sb")
@@ -318,43 +323,49 @@ def allTests(communicator):
test(isinstance(sbskd, Test.SBSKnownDerived))
test(sbskd)
test(sbskd.sbskd == "SBSKnownDerived.sbskd")
- print "ok"
+ print("ok")
- print "base with known derived as base (AMI)... ",
+ sys.stdout.write("base with known derived as base (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_SBSKnownDerivedAsSBase(cb.response_SBSKnownDerivedAsSBase, cb.exception)
cb.check()
- print "ok"
+ print("ok")
- print "base with known derived as known derived... ",
+ sys.stdout.write("base with known derived as known derived... ")
+ sys.stdout.flush()
try:
sbskd = t.SBSKnownDerivedAsSBSKnownDerived()
test(sbskd.sbskd == "SBSKnownDerived.sbskd")
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "base with known derived as known derived (AMI)... ",
+ sys.stdout.write("base with known derived as known derived (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_SBSKnownDerivedAsSBSKnownDerived(cb.response_SBSKnownDerivedAsSBSKnownDerived, cb.exception)
cb.check()
- print "ok"
+ print("ok")
- print "base with unknown derived as base... ",
+ sys.stdout.write("base with unknown derived as base... ")
+ sys.stdout.flush()
try:
sb = t.SBSUnknownDerivedAsSBase()
test(sb.sb == "SBSUnknownDerived.sb")
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "base with unknown derived as base (AMI)... ",
+ sys.stdout.write("base with unknown derived as base (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_SBSUnknownDerivedAsSBase(cb.response_SBSUnknownDerivedAsSBase, cb.exception)
cb.check()
- print "ok"
+ print("ok")
- print "unknown with Object as Object... ",
+ sys.stdout.write("unknown with Object as Object... ")
+ sys.stdout.flush()
try:
o = t.SUnknownAsObject()
test(False)
@@ -362,9 +373,10 @@ def allTests(communicator):
pass
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "unknown with Object as Object (AMI)... ",
+ sys.stdout.write("unknown with Object as Object (AMI)... ")
+ sys.stdout.flush()
try:
cb = Callback()
t.begin_SUnknownAsObject(cb.response_SUnknownAsObject, cb.exception_SUnknownAsObject)
@@ -373,9 +385,10 @@ def allTests(communicator):
pass
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "one-element cycle... ",
+ sys.stdout.write("one-element cycle... ")
+ sys.stdout.flush()
try:
b = t.oneElementCycle()
test(b)
@@ -384,15 +397,17 @@ def allTests(communicator):
test(b.pb == b)
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "one-element cycle (AMI)... ",
+ sys.stdout.write("one-element cycle (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_oneElementCycle(cb.response_oneElementCycle, cb.exception)
cb.check()
- print "ok"
+ print("ok")
- print "two-element cycle... ",
+ sys.stdout.write("two-element cycle... ")
+ sys.stdout.flush()
try:
b1 = t.twoElementCycle()
test(b1)
@@ -406,15 +421,17 @@ def allTests(communicator):
test(b2.pb == b1)
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "two-element cycle (AMI)... ",
+ sys.stdout.write("two-element cycle (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_twoElementCycle(cb.response_twoElementCycle, cb.exception)
cb.check()
- print "ok"
+ print("ok")
- print "known derived pointer slicing as base... ",
+ sys.stdout.write("known derived pointer slicing as base... ")
+ sys.stdout.flush()
try:
b1 = t.D1AsB()
test(b1)
@@ -436,15 +453,17 @@ def allTests(communicator):
test(b2.ice_id() == "::Test::B")
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "known derived pointer slicing as base (AMI)... ",
+ sys.stdout.write("known derived pointer slicing as base (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_D1AsB(cb.response_D1AsB, cb.exception)
cb.check()
- print "ok"
+ print("ok")
- print "known derived pointer slicing as derived... ",
+ sys.stdout.write("known derived pointer slicing as derived... ")
+ sys.stdout.flush()
try:
d1 = t.D1AsD1()
test(d1)
@@ -460,15 +479,17 @@ def allTests(communicator):
test(b2.pb == d1)
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "known derived pointer slicing as derived (AMI)... ",
+ sys.stdout.write("known derived pointer slicing as derived (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_D1AsD1(cb.response_D1AsD1, cb.exception)
cb.check()
- print "ok"
+ print("ok")
- print "unknown derived pointer slicing as base... ",
+ sys.stdout.write("unknown derived pointer slicing as base... ")
+ sys.stdout.flush()
try:
b2 = t.D2AsB()
test(b2)
@@ -488,15 +509,17 @@ def allTests(communicator):
test(d1.pd1 == b2)
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "unknown derived pointer slicing as base (AMI)... ",
+ sys.stdout.write("unknown derived pointer slicing as base (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_D2AsB(cb.response_D2AsB, cb.exception)
cb.check()
- print "ok"
+ print("ok")
- print "param ptr slicing with known first... ",
+ sys.stdout.write("param ptr slicing with known first... ")
+ sys.stdout.flush()
try:
b1, b2 = t.paramTest1()
@@ -515,15 +538,17 @@ def allTests(communicator):
test(b2.pb == b1)
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "param ptr slicing with known first (AMI)... ",
+ sys.stdout.write("param ptr slicing with known first (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_paramTest1(cb.response_paramTest1, cb.exception)
cb.check()
- print "ok"
+ print("ok")
- print "param ptr slicing with unknown first... ",
+ sys.stdout.write("param ptr slicing with unknown first... ")
+ sys.stdout.flush()
try:
b2, b1 = t.paramTest2()
@@ -544,37 +569,42 @@ def allTests(communicator):
import traceback
traceback.print_exc()
test(False)
- print "ok"
+ print("ok")
- print "return value identity with known first... ",
+ sys.stdout.write("return value identity with known first... ")
+ sys.stdout.flush()
try:
r, p1, p2 = t.returnTest1()
test(r == p1)
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "return value identity with known first (AMI)... ",
+ sys.stdout.write("return value identity with known first (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_returnTest1(cb.response_returnTest1, cb.exception)
cb.check()
- print "ok"
+ print("ok")
- print "return value identity with unknown first... ",
+ sys.stdout.write("return value identity with unknown first... ")
+ sys.stdout.flush()
try:
r, p1, p2 = t.returnTest2()
test(r == p1)
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "return value identity with unknown first (AMI)... ",
+ sys.stdout.write("return value identity with unknown first (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_returnTest2(cb.response_returnTest2, cb.exception)
cb.check()
- print "ok"
+ print("ok")
- print "return value identity for input params known first... ",
+ sys.stdout.write("return value identity for input params known first... ")
+ sys.stdout.flush()
try:
d1 = Test.D1()
d1.sb = "D1.sb"
@@ -611,9 +641,10 @@ def allTests(communicator):
test(b2 != d3)
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "return value identity for input params known first (AMI)... ",
+ sys.stdout.write("return value identity for input params known first (AMI)... ")
+ sys.stdout.flush()
try:
d1 = Test.D1()
d1.sb = "D1.sb"
@@ -653,9 +684,10 @@ def allTests(communicator):
test(b2 != d3)
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "return value identity for input params unknown first... ",
+ sys.stdout.write("return value identity for input params unknown first... ")
+ sys.stdout.flush()
try:
d1 = Test.D1()
d1.sb = "D1.sb"
@@ -692,9 +724,10 @@ def allTests(communicator):
test(b2 != d3)
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "return value identity for input params unknown first (AMI)... ",
+ sys.stdout.write("return value identity for input params unknown first (AMI)... ")
+ sys.stdout.flush()
try:
d1 = Test.D1()
d1.sb = "D1.sb"
@@ -734,9 +767,10 @@ def allTests(communicator):
test(b2 != d3)
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "remainder unmarshaling (3 instances)... ",
+ sys.stdout.write("remainder unmarshaling (3 instances)... ")
+ sys.stdout.flush()
try:
ret, p1, p2 = t.paramTest3()
@@ -756,15 +790,17 @@ def allTests(communicator):
test(ret.ice_id() == "::Test::D1")
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "remainder unmarshaling (3 instances) (AMI)... ",
+ sys.stdout.write("remainder unmarshaling (3 instances) (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_paramTest3(cb.response_paramTest3, cb.exception)
cb.check()
- print "ok"
+ print("ok")
- print "remainder unmarshaling (4 instances)... ",
+ sys.stdout.write("remainder unmarshaling (4 instances)... ")
+ sys.stdout.flush()
try:
ret, b = t.paramTest4()
@@ -779,15 +815,17 @@ def allTests(communicator):
test(ret.ice_id() == "::Test::B")
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "remainder unmarshaling (4 instances) (AMI)... ",
+ sys.stdout.write("remainder unmarshaling (4 instances) (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_paramTest4(cb.response_paramTest4, cb.exception)
cb.check()
- print "ok"
+ print("ok")
- print "param ptr slicing, instance marshaled in unknown derived as base... ",
+ sys.stdout.write("param ptr slicing, instance marshaled in unknown derived as base... ")
+ sys.stdout.flush()
try:
b1 = Test.B()
b1.sb = "B.sb(1)"
@@ -811,9 +849,10 @@ def allTests(communicator):
test(r.pb == r)
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "param ptr slicing, instance marshaled in unknown derived as base (AMI)... ",
+ sys.stdout.write("param ptr slicing, instance marshaled in unknown derived as base (AMI)... ")
+ sys.stdout.flush()
try:
b1 = Test.B()
b1.sb = "B.sb(1)"
@@ -840,9 +879,10 @@ def allTests(communicator):
test(r.pb == r)
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "param ptr slicing, instance marshaled in unknown derived as derived... ",
+ sys.stdout.write("param ptr slicing, instance marshaled in unknown derived as derived... ")
+ sys.stdout.flush()
try:
d11 = Test.D1()
d11.sb = "D1.sb(1)"
@@ -869,9 +909,10 @@ def allTests(communicator):
test(r.pb == r)
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "param ptr slicing, instance marshaled in unknown derived as derived (AMI)... ",
+ sys.stdout.write("param ptr slicing, instance marshaled in unknown derived as derived (AMI)... ")
+ sys.stdout.flush()
try:
d11 = Test.D1()
d11.sb = "D1.sb(1)"
@@ -902,9 +943,10 @@ def allTests(communicator):
test(r.pb == r)
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "sequence slicing... ",
+ sys.stdout.write("sequence slicing... ")
+ sys.stdout.flush()
try:
ss = Test.SS()
ss1b = Test.B()
@@ -977,9 +1019,10 @@ def allTests(communicator):
test(ss2d3.ice_id() == "::Test::B")
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "sequence slicing (AMI)... ",
+ sys.stdout.write("sequence slicing (AMI)... ")
+ sys.stdout.flush()
try:
ss = Test.SS()
ss1b = Test.B()
@@ -1055,9 +1098,10 @@ def allTests(communicator):
test(ss2d3.ice_id() == "::Test::B")
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "dictionary slicing... ",
+ sys.stdout.write("dictionary slicing... ")
+ sys.stdout.flush()
try:
bin = {}
for i in range(0, 10):
@@ -1098,9 +1142,10 @@ def allTests(communicator):
test(d1.pd1 == d1)
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "dictionary slicing (AMI)... ",
+ sys.stdout.write("dictionary slicing (AMI)... ")
+ sys.stdout.flush()
try:
bin = {}
for i in range(0, 10):
@@ -1145,13 +1190,14 @@ def allTests(communicator):
test(d1.pd1 == d1)
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "base exception thrown as base exception... ",
+ sys.stdout.write("base exception thrown as base exception... ")
+ sys.stdout.flush()
try:
t.throwBaseAsBase()
test(False)
- except Test.BaseException, e:
+ except Test.BaseException as e:
test(e.ice_name() == "Test::BaseException")
test(e.sbe == "sbe")
test(e.pb)
@@ -1159,19 +1205,21 @@ def allTests(communicator):
test(e.pb.pb == e.pb)
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "base exception thrown as base exception (AMI)... ",
+ sys.stdout.write("base exception thrown as base exception (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_throwBaseAsBase(cb.response, cb.exception_throwBaseAsBase)
cb.check()
- print "ok"
+ print("ok")
- print "derived exception thrown as base exception... ",
+ sys.stdout.write("derived exception thrown as base exception... ")
+ sys.stdout.flush()
try:
t.throwDerivedAsBase()
test(False)
- except Test.DerivedException, e:
+ except Test.DerivedException as e:
test(e.ice_name() == "Test::DerivedException")
test(e.sbe == "sbe")
test(e.pb)
@@ -1185,19 +1233,21 @@ def allTests(communicator):
test(e.pd1.pd1 == e.pd1)
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "derived exception thrown as base exception (AMI)... ",
+ sys.stdout.write("derived exception thrown as base exception (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_throwDerivedAsBase(cb.response, cb.exception_throwDerivedAsBase)
cb.check()
- print "ok"
+ print("ok")
- print "derived exception thrown as derived exception... ",
+ sys.stdout.write("derived exception thrown as derived exception... ")
+ sys.stdout.flush()
try:
t.throwDerivedAsDerived()
test(False)
- except Test.DerivedException, e:
+ except Test.DerivedException as e:
test(e.ice_name() == "Test::DerivedException")
test(e.sbe == "sbe")
test(e.pb)
@@ -1211,19 +1261,21 @@ def allTests(communicator):
test(e.pd1.pd1 == e.pd1)
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "derived exception thrown as derived exception (AMI)... ",
+ sys.stdout.write("derived exception thrown as derived exception (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_throwDerivedAsDerived(cb.response, cb.exception_throwDerivedAsDerived)
cb.check()
- print "ok"
+ print("ok")
- print "unknown derived exception thrown as base exception... ",
+ sys.stdout.write("unknown derived exception thrown as base exception... ")
+ sys.stdout.flush()
try:
t.throwUnknownDerivedAsBase()
test(False)
- except Test.BaseException, e:
+ except Test.BaseException as e:
test(e.ice_name() == "Test::BaseException")
test(e.sbe == "sbe")
test(e.pb)
@@ -1231,26 +1283,29 @@ def allTests(communicator):
test(e.pb.pb == e.pb)
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "unknown derived exception thrown as base exception (AMI)... ",
+ sys.stdout.write("unknown derived exception thrown as base exception (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_throwUnknownDerivedAsBase(cb.response, cb.exception_throwUnknownDerivedAsBase)
cb.check()
- print "ok"
+ print("ok")
- print "forward-declared class... ",
+ sys.stdout.write("forward-declared class... ")
+ sys.stdout.flush()
try:
f = t.useForward()
test(f)
except Ice.Exception:
test(False)
- print "ok"
+ print("ok")
- print "forward-declared class (AMI)... ",
+ sys.stdout.write("forward-declared class (AMI)... ")
+ sys.stdout.flush()
cb = Callback()
t.begin_useForward(cb.response_useForward, cb.exception)
cb.check()
- print "ok"
+ print("ok")
return t
diff --git a/py/test/Ice/slicing/objects/run.py b/py/test/Ice/slicing/objects/run.py
index 141e2be507d..6af6dc0cb43 100755
--- a/py/test/Ice/slicing/objects/run.py
+++ b/py/test/Ice/slicing/objects/run.py
@@ -16,12 +16,11 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
-sys.path.append(os.path.join(path[0]))
-from scripts import *
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0], "scripts"))
+import TestUtil
-print "tests with regular server."
+print("tests with regular server.")
TestUtil.clientServerTest()
-print "tests with AMD server."
+print("tests with AMD server.")
TestUtil.clientServerTest(server="ServerAMD.py")
-
diff --git a/py/test/Ice/timeout/AllTests.py b/py/test/Ice/timeout/AllTests.py
index 3ee89608261..0beb723a97b 100644
--- a/py/test/Ice/timeout/AllTests.py
+++ b/py/test/Ice/timeout/AllTests.py
@@ -7,7 +7,7 @@
#
# **********************************************************************
-import Ice, Test, threading
+import Ice, Test, sys, threading
def test(b):
if not b:
@@ -53,7 +53,8 @@ def allTests(communicator, collocated):
timeout = Test.TimeoutPrx.checkedCast(obj)
test(timeout != None)
- print "testing connect timeout... ",
+ sys.stdout.write("testing connect timeout... ")
+ sys.stdout.flush()
#
# Expect ConnectTimeoutException.
#
@@ -76,9 +77,10 @@ def allTests(communicator, collocated):
to.op()
except Ice.ConnectTimeoutException:
test(False)
- print "ok"
+ print("ok")
- print "testing read timeout... ",
+ sys.stdout.write("testing read timeout... ")
+ sys.stdout.flush()
#
# Expect TimeoutException.
#
@@ -97,18 +99,22 @@ def allTests(communicator, collocated):
to.sleep(500)
except Ice.TimeoutException:
test(False)
- print "ok"
+ print("ok")
- print "testing write timeout... ",
+ sys.stdout.write("testing write timeout... ")
+ sys.stdout.flush()
#
# Expect TimeoutException.
#
to = Test.TimeoutPrx.uncheckedCast(obj.ice_timeout(500))
to.holdAdapter(2000)
- seq = []
- seq[0:100000] = range(0, 100000) # add 100,000 entries.
- seq = ['\x00' for x in seq] # set them all to \x00
- seq = ''.join(seq) # make into a byte array
+ if sys.version_info[0] == 2:
+ seq = []
+ seq[0:100000] = range(0, 100000) # add 100,000 entries.
+ seq = ['\x00' for x in seq] # set them all to \x00
+ seq = ''.join(seq) # make into a byte array
+ else:
+ seq = bytes([0 for x in range(0, 100000)])
try:
to.sendData(seq)
test(False)
@@ -124,9 +130,10 @@ def allTests(communicator, collocated):
to.sendData(seq)
except Ice.TimeoutException:
test(False)
- print "ok"
+ print("ok")
- print "testing AMI read timeout... ",
+ sys.stdout.write("testing AMI read timeout... ")
+ sys.stdout.flush()
#
# Expect TimeoutException.
#
@@ -142,9 +149,10 @@ def allTests(communicator, collocated):
cb = Callback()
to.begin_sleep(500, cb.response, cb.exception)
cb.check()
- print "ok"
+ print("ok")
- print "testing AMI write timeout... ",
+ sys.stdout.write("testing AMI write timeout... ")
+ sys.stdout.flush()
#
# Expect TimeoutException.
#
@@ -162,9 +170,10 @@ def allTests(communicator, collocated):
cb = Callback()
to.begin_sendData(seq, cb.response, cb.exception)
cb.check()
- print "ok"
+ print("ok")
- print "testing timeout overrides... ",
+ sys.stdout.write("testing timeout overrides... ")
+ sys.stdout.flush()
#
# Test Ice.Override.Timeout. This property overrides all
# endpoint timeouts.
@@ -225,6 +234,6 @@ def allTests(communicator, collocated):
except Ice.TimeoutException:
pass # Expected.
comm.destroy()
- print "ok"
+ print("ok")
return timeout
diff --git a/py/test/Ice/timeout/Client.py b/py/test/Ice/timeout/Client.py
index 1d4ace1a579..c891a54acec 100755
--- a/py/test/Ice/timeout/Client.py
+++ b/py/test/Ice/timeout/Client.py
@@ -13,7 +13,7 @@ import os, sys, traceback
import Ice
slice_dir = Ice.getSliceDir()
if not slice_dir:
- print sys.argv[0] + ': Slice directory not found.'
+ print(sys.argv[0] + ': Slice directory not found.')
sys.exit(1)
Ice.loadSlice("'-I" + slice_dir + "' Test.ice")
import AllTests
diff --git a/py/test/Ice/timeout/Server.py b/py/test/Ice/timeout/Server.py
index 96c5ab449f4..80e9020b31c 100755
--- a/py/test/Ice/timeout/Server.py
+++ b/py/test/Ice/timeout/Server.py
@@ -13,7 +13,7 @@ import os, sys, traceback, time, threading
import Ice
slice_dir = Ice.getSliceDir()
if not slice_dir:
- print sys.argv[0] + ': Slice directory not found.'
+ print(sys.argv[0] + ': Slice directory not found.')
sys.exit(1)
Ice.loadSlice("'-I" + slice_dir + "' Test.ice")
diff --git a/py/test/Ice/timeout/run.py b/py/test/Ice/timeout/run.py
index 32ea526c3b4..2265a40ca12 100755
--- a/py/test/Ice/timeout/run.py
+++ b/py/test/Ice/timeout/run.py
@@ -16,9 +16,8 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
-sys.path.append(os.path.join(path[0]))
-from scripts import *
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0], "scripts"))
+import TestUtil
TestUtil.clientServerTest()
-
diff --git a/py/test/Slice/keyword/Client.py b/py/test/Slice/keyword/Client.py
index 2ce1dc42280..96c20d5b3f9 100755
--- a/py/test/Slice/keyword/Client.py
+++ b/py/test/Slice/keyword/Client.py
@@ -15,7 +15,7 @@ for toplevel in [".", "..", "../..", "../../..", "../../../.."]:
if os.path.exists(os.path.join(toplevel, "python", "Ice.py")):
break
else:
- raise "can't find toplevel directory!"
+ raise RuntimeError("can't find toplevel directory!")
import Ice
@@ -47,7 +47,8 @@ class printI(_and._print):
pass
def testtypes():
- print("Testing generated type names... "),
+ sys.stdout.write("Testing generated type names... ")
+ sys.stdout.flush()
a = _and._assert._break
b = _and._continue
b._def = 0
@@ -74,7 +75,7 @@ def testtypes():
i = printI()
j = _and._lambda;
en = _and.EnumNone._None
- print "ok"
+ print("ok")
def run(args, communicator):
communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010:udp")
@@ -82,11 +83,12 @@ def run(args, communicator):
adapter.add(execI(), communicator.stringToIdentity("test"))
adapter.activate()
- print("Testing operation name... "),
+ sys.stdout.write("Testing operation name... ")
+ sys.stdout.flush()
p = _and.execPrx.uncheckedCast(
adapter.createProxy(communicator.stringToIdentity("test")));
p._finally();
- print "ok"
+ print("ok")
testtypes()
diff --git a/py/test/Slice/keyword/run.py b/py/test/Slice/keyword/run.py
index 9e43cca975f..9408d16c691 100755
--- a/py/test/Slice/keyword/run.py
+++ b/py/test/Slice/keyword/run.py
@@ -16,13 +16,13 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
-sys.path.append(os.path.join(path[0]))
-from scripts import *
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0], "scripts"))
+import TestUtil
-print "starting client...",
+sys.stdout.write("starting client... ")
+sys.stdout.flush()
clientProc = TestUtil.startClient("Client.py", "--Ice.Default.Host=127.0.0.1", startReader = False)
-print "ok"
+print("ok")
clientProc.startReader()
clientProc.waitTestSuccess()
-
diff --git a/py/test/Slice/structure/Client.py b/py/test/Slice/structure/Client.py
index 9d11ff5f1ea..5db17fbb946 100755
--- a/py/test/Slice/structure/Client.py
+++ b/py/test/Slice/structure/Client.py
@@ -15,7 +15,7 @@ for toplevel in [".", "..", "../..", "../../..", "../../../.."]:
if os.path.exists(os.path.join(toplevel, "python", "Ice.py")):
break
else:
- raise "can't find toplevel directory!"
+ raise RuntimeError("can't find toplevel directory!")
import Ice
@@ -27,7 +27,8 @@ def test(b):
raise RuntimeError('test assertion failed')
def allTests(communicator):
- print("testing equals() for Slice structures..."),
+ sys.stdout.write("testing equals() for Slice structures... ")
+ sys.stdout.flush()
#
# Define some default values.
@@ -210,7 +211,7 @@ def allTests(communicator):
v2.prx = None
test(v1 != v2)
- print "ok"
+ print("ok")
def run(args, communicator):
allTests(communicator)
diff --git a/py/test/Slice/structure/run.py b/py/test/Slice/structure/run.py
index 9e43cca975f..9408d16c691 100755
--- a/py/test/Slice/structure/run.py
+++ b/py/test/Slice/structure/run.py
@@ -16,13 +16,13 @@ if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
- raise "can't find toplevel directory!"
-sys.path.append(os.path.join(path[0]))
-from scripts import *
+ raise RuntimeError("can't find toplevel directory!")
+sys.path.append(os.path.join(path[0], "scripts"))
+import TestUtil
-print "starting client...",
+sys.stdout.write("starting client... ")
+sys.stdout.flush()
clientProc = TestUtil.startClient("Client.py", "--Ice.Default.Host=127.0.0.1", startReader = False)
-print "ok"
+print("ok")
clientProc.startReader()
clientProc.waitTestSuccess()
-