You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@qpid.apache.org by kg...@apache.org on 2018/06/01 15:00:11 UTC

[01/11] qpid-dispatch git commit: DISPATCH-965: port python code to Python 3. Stay compatible with 2.6-7

Repository: qpid-dispatch
Updated Branches:
  refs/heads/master 91def8472 -> 561f210f4


http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_http.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_http.py b/tests/system_tests_http.py
index d162cd4..a436e3a 100644
--- a/tests/system_tests_http.py
+++ b/tests/system_tests_http.py
@@ -87,7 +87,7 @@ class RouterTestHttp(TestCase):
                 self.start()
             def run(self):
                 try: test(self.port)
-                except Exception, e: self.ex = e
+                except Exception as e: self.ex = e
         threads = [TestThread(p) for p in r.ports + r.ports]
         for t in threads: t.join()
         for t in threads:

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_link_routes.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_link_routes.py b/tests/system_tests_link_routes.py
index da48d6d..713d8f2 100644
--- a/tests/system_tests_link_routes.py
+++ b/tests/system_tests_link_routes.py
@@ -167,7 +167,8 @@ class LinkRouteTest(TestCase):
             cmd = cmd + args
         p = self.popen(
             cmd,
-            name='qdstat-'+self.id(), stdout=PIPE, expect=None)
+            name='qdstat-'+self.id(), stdout=PIPE, expect=None,
+            universal_newlines=True)
 
         out = p.communicate()[0]
         assert p.returncode == 0, "qdstat exit status %s, output:\n%s" % (p.returncode, out)
@@ -176,11 +177,12 @@ class LinkRouteTest(TestCase):
     def run_qdmanage(self, cmd, input=None, expect=Process.EXIT_OK, address=None):
         p = self.popen(
             ['qdmanage'] + cmd.split(' ') + ['--bus', address or self.address(), '--indent=-1', '--timeout', str(TIMEOUT)],
-            stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=expect)
+            stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=expect,
+            universal_newlines=True)
         out = p.communicate(input)[0]
         try:
             p.teardown()
-        except Exception, e:
+        except Exception as e:
             raise Exception("%s\n%s" % (e, out))
         return out
 
@@ -216,9 +218,9 @@ class LinkRouteTest(TestCase):
             # This identity should not be found
             cmd = 'READ --type=linkRoute --identity=9999'
             out = self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
-        except Exception, e:
+        except Exception as e:
             exception_occurred = True
-            self.assertTrue("NotFoundStatus: Not Found" in e.message)
+            self.assertTrue("NotFoundStatus: Not Found" in str(e))
 
         self.assertTrue(exception_occurred)
 
@@ -227,9 +229,9 @@ class LinkRouteTest(TestCase):
             # There is no identity specified, this is a bad request
             cmd = 'READ --type=linkRoute'
             out = self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
-        except Exception, e:
+        except Exception as e:
             exception_occurred = True
-            self.assertTrue("BadRequestStatus: No name or identity provided" in e.message)
+            self.assertTrue("BadRequestStatus: No name or identity provided" in str(e))
 
         self.assertTrue(exception_occurred)
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_log_message_components.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_log_message_components.py b/tests/system_tests_log_message_components.py
index 1b7e4b4..e66dcce 100644
--- a/tests/system_tests_log_message_components.py
+++ b/tests/system_tests_log_message_components.py
@@ -24,6 +24,7 @@ from system_test import TestCase, Qdrouterd, Process, TIMEOUT
 from subprocess import PIPE, STDOUT
 from proton.handlers import MessagingHandler
 from proton.reactor import Container
+from qpid_dispatch_internal.compat import BINARY
 
 
 
@@ -35,11 +36,12 @@ class RouterMessageLogTestBase(TestCase):
             ['--bus',
              address or self.address(),
              '--indent=-1', '--timeout', str(TIMEOUT)],
-            stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=expect)
+            stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=expect,
+            universal_newlines=True)
         out = p.communicate(input)[0]
         try:
             p.teardown()
-        except Exception, e:
+        except Exception as e:
             raise Exception("%s\n%s" % (e, out))
         return out
 
@@ -181,7 +183,7 @@ class LogMessageTest(MessagingHandler):
             msg = Message()
             msg.address = self.address
             msg.id = '123455'
-            msg.user_id = 'testuser'
+            msg.user_id = BINARY('testuser')
             msg.subject = 'test-subject'
             msg.content_type = 'text/html; charset=utf-8'
             msg.correlation_id = 89
@@ -208,4 +210,4 @@ class LogMessageTest(MessagingHandler):
 
 
 if __name__ == '__main__':
-    unittest.main(main_module())
\ No newline at end of file
+    unittest.main()

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_management.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_management.py b/tests/system_tests_management.py
index c349002..51e8ad3 100644
--- a/tests/system_tests_management.py
+++ b/tests/system_tests_management.py
@@ -27,6 +27,7 @@ from proton import Message
 from qpid_dispatch.management.client import Node, ManagementError, Url, BadRequestStatus, NotImplementedStatus, NotFoundStatus
 from qpid_dispatch_internal.management.qdrouter import QdSchema
 from qpid_dispatch_internal.compat import dictify
+from qpid_dispatch_internal.compat import BINARY
 from system_test import Qdrouterd, message, Process
 from itertools import chain
 
@@ -138,7 +139,7 @@ class ManagementTest(system_test.TestCase):
         attribute_names=['type', 'name', 'port']
         response = self.node.query(type=LISTENER, attribute_names=attribute_names)
         self.assertEqual(attribute_names, response.attribute_names)
-        expect = [[LISTENER, 'l%s' % i, str(self.router.ports[i])] for i in xrange(3)]
+        expect = [[LISTENER, 'l%s' % i, str(self.router.ports[i])] for i in range(3)]
         for r in expect: # We might have extras in results due to create tests
             self.assertTrue(r in response.results)
             self.assertTrue(dict(zip(attribute_names, r)) in response.get_dicts())
@@ -148,7 +149,7 @@ class ManagementTest(system_test.TestCase):
         attribute_names=['type', 'name', 'port']
         response = self.node.query(attribute_names=attribute_names)
         self.assertEqual(attribute_names, response.attribute_names)
-        expect = [[LISTENER, 'l%s' % i, str(self.router.ports[i])] for i in xrange(3)]
+        expect = [[LISTENER, 'l%s' % i, str(self.router.ports[i])] for i in range(3)]
         for r in expect: # We might have extras in results due to create tests
             self.assertTrue(r in response.results)
         for name in ['router/' + self.router.name, 'log/DEFAULT']:
@@ -322,15 +323,14 @@ class ManagementTest(system_test.TestCase):
         self.assertEqual(dummy.attributes, dummy2.attributes)
 
         integers = [0, 1, 42, (2**63)-1, -1, -42, -(2**63)]
-        test_data = ["bytes", u"string"] + integers
+        test_data = [BINARY("bytes"), u"string"] + integers
         for data in test_data:
             try:
                 self.assertEqual(
                     {u'operation': u'callme', u'type': DUMMY, u'identity': identity, u'data': data},
                     dummy.call('callme', data=data))
-            except TypeError:
-                extype, value, trace = sys.exc_info()
-                raise extype, "data=%r: %s" % (data, value), trace
+            except TypeError as exc:
+                raise TypeError("data=%r: %s" % (data, exc))
 
         dummy.badattribute = 'Bad'
         self.assertRaises(BadRequestStatus, dummy.update)

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_multi_tenancy.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_multi_tenancy.py b/tests/system_tests_multi_tenancy.py
index 950ecbe..78dc1d8 100644
--- a/tests/system_tests_multi_tenancy.py
+++ b/tests/system_tests_multi_tenancy.py
@@ -22,6 +22,7 @@ from proton import Message, Timeout
 from system_test import TestCase, Qdrouterd, main_module, TIMEOUT
 from proton.handlers import MessagingHandler
 from proton.reactor import Container, DynamicNodeProperties
+from qpid_dispatch_internal.compat import UNICODE
 
 # PROTON-828:
 try:
@@ -707,7 +708,8 @@ class LinkRouteTest(MessagingHandler):
         if self.dynamic:
             self.first_receiver = event.container.create_receiver(self.first_conn,
                                                                   dynamic=True,
-                                                                  options=DynamicNodeProperties({"x-opt-qd.address": unicode(self.first_address)}))
+                                                                  options=DynamicNodeProperties({"x-opt-qd.address":
+                                                                                                 UNICODE(self.first_address)}))
         else:
             self.first_receiver = event.container.create_receiver(self.first_conn, self.first_address)
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_one_router.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_one_router.py b/tests/system_tests_one_router.py
index 22a9d36..a15866f 100644
--- a/tests/system_tests_one_router.py
+++ b/tests/system_tests_one_router.py
@@ -28,7 +28,7 @@ from qpid_dispatch.management.client import Node
 CONNECTION_PROPERTIES_UNICODE_STRING = {u'connection': u'properties', u'int_property': 6451}
 CONNECTION_PROPERTIES_SYMBOL = dict()
 CONNECTION_PROPERTIES_SYMBOL[symbol("connection")] = symbol("properties")
-CONNECTION_PROPERTIES_BINARY = {'client_identifier': 'policy_server'}
+CONNECTION_PROPERTIES_BINARY = {b'client_identifier': b'policy_server'}
 
 
 #====================================================
@@ -986,7 +986,7 @@ class MulticastUnsettled ( MessagingHandler ) :
         self.recv_conn = event.container.connect ( self.addr )
 
         self.sender = event.container.create_sender   ( self.send_conn, self.addr )
-        for i in xrange ( self.n_receivers ) :
+        for i in range ( self.n_receivers ) :
             rcvr = event.container.create_receiver ( self.send_conn, self.addr, name = "receiver_" + str(i) )
             self.receivers.append ( rcvr )
             rcvr.flow ( self.n_messages )
@@ -999,7 +999,7 @@ class MulticastUnsettled ( MessagingHandler ) :
         while self.n_sent < self.n_messages :
             if event.sender.credit < 1 :
                 break
-            for i in xrange ( self.n_messages ) :
+            for i in range ( self.n_messages ) :
                 msg = Message ( body = i )
                 # The sender does not settle, but the 
                 # receivers will..
@@ -1011,7 +1011,7 @@ class MulticastUnsettled ( MessagingHandler ) :
         if self.bailing :
             return
         event.delivery.settle()
-        for i in xrange ( self.n_receivers ) :
+        for i in range ( self.n_receivers ) :
             if event.receiver == self.receivers [ i ] :
                 # Body conetnts of the messages count from 0 ... n,
                 # so the contents of this message should be same as
@@ -1026,7 +1026,7 @@ class MulticastUnsettled ( MessagingHandler ) :
 
 
     def check_n_received ( self ) :
-        for i in xrange ( self.n_receivers ) :
+        for i in range ( self.n_receivers ) :
             if self.n_received [ i ] < self.n_messages :
                 return
         # All messages have been received by all receivers.
@@ -1714,10 +1714,10 @@ class StripMessageAnnotationsNoAddTrace ( MessagingHandler ) :
             if event.sender.credit < 1 :
                 break
             msg = Message ( body = self.n_sent )
-            annotations = { 'x-opt-qd.ingress': 'ingress-router',
-                            'x-opt-qd.trace': ['0/QDR.1'],
-                            'Canis_meus' : 'id_comedit'
-                          }
+            annotations = {'Canis_meus' : 'id_comedit',
+                           'x-opt-qd.ingress': 'ingress-router',
+                           'x-opt-qd.trace': ['0/QDR.1']
+            }
             self.n_sent += 1
             # This test has no added annotations.
             # The receiver should get the expected standard annotations anyway,
@@ -1809,9 +1809,9 @@ class StripMessageAnnotationsBoth ( MessagingHandler ) :
             if event.sender.credit < 1 :
                 break
             msg = Message ( body = self.n_sent )
-            annotations = { 'x-opt-qd.ingress': 'ingress-router',
+            annotations = { 'Canis_meus' : 'id_comedit',
+                            'x-opt-qd.ingress': 'ingress-router',
                             'x-opt-qd.trace': ['0/QDR.1'],
-                            'Canis_meus' : 'id_comedit'
                           }
             self.n_sent += 1
             # This test has no added annotations.
@@ -1846,8 +1846,6 @@ class StripMessageAnnotationsBoth ( MessagingHandler ) :
             self.bail ( None )
 
 
-
-
 class StripMessageAnnotationsOut ( MessagingHandler ) :
     def __init__ ( self,
                    addr,
@@ -2493,7 +2491,7 @@ class BatchedSettlementTest(MessagingHandler):
             outs = local_node.query(type='org.apache.qpid.dispatch.router')
             pos = outs.attribute_names.index("acceptedDeliveries")
             results = outs.results[0]
-            if results >= self.count:
+            if results[pos] >= self.count:
                 self.accepted_count_match = True
 
             self.timer.cancel()

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_policy.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_policy.py b/tests/system_tests_policy.py
index 93c7d6a..4c81496 100644
--- a/tests/system_tests_policy.py
+++ b/tests/system_tests_policy.py
@@ -24,6 +24,7 @@ from subprocess import PIPE, STDOUT
 from proton import ConnectionException
 from proton.utils import BlockingConnection, LinkDetached
 from qpid_dispatch_internal.policy.policy_util import is_ipv6_enabled
+from qpid_dispatch_internal.compat import dict_iteritems
 
 class AbsoluteConnectionCountLimit(TestCase):
     """
@@ -89,7 +90,7 @@ class LoadPolicyFromFolder(TestCase):
                 with open(policy_config_path+"/"+f[:-3], 'w') as outfile:
                     with open(policy_config_path + "/" + f) as infile:
                         for line in infile:
-                            for src, target in replacements.iteritems():
+                            for src, target in dict_iteritems(replacements):
                                 if ipv6_enabled:
                                     line = line.replace(src, target)
                                 else:
@@ -110,11 +111,12 @@ class LoadPolicyFromFolder(TestCase):
     def run_qdmanage(self, cmd, input=None, expect=Process.EXIT_OK):
         p = self.popen(
             ['qdmanage'] + cmd.split(' ') + ['--bus', 'u1:password@' + self.address(), '--indent=-1', '--timeout', str(TIMEOUT)],
-            stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=expect)
+            stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=expect,
+            universal_newlines=True)
         out = p.communicate(input)[0]
         try:
             p.teardown()
-        except Exception, e:
+        except Exception as e:
             raise Exception("%s\n%s" % (e, out))
         return out
 
@@ -371,7 +373,7 @@ class VhostPolicyNameField(TestCase):
                 with open(policy_config_path+"/"+f[:-3], 'w') as outfile:
                     with open(policy_config_path + "/" + f) as infile:
                         for line in infile:
-                            for src, target in replacements.iteritems():
+                            for src, target in dict_iteritems(replacements):
                                 if ipv6_enabled:
                                     line = line.replace(src, target)
                                 else:
@@ -392,11 +394,12 @@ class VhostPolicyNameField(TestCase):
     def run_qdmanage(self, cmd, input=None, expect=Process.EXIT_OK):
         p = self.popen(
             ['qdmanage'] + cmd.split(' ') + ['--bus', 'u1:password@' + self.address(), '--indent=-1', '--timeout', str(TIMEOUT)],
-            stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=expect)
+            stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=expect,
+            universal_newlines=True)
         out = p.communicate(input)[0]
         try:
             p.teardown()
-        except Exception, e:
+        except Exception as e:
             raise Exception("%s\n%s" % (e, out))
         return out
 
@@ -542,8 +545,8 @@ class VhostPolicyNameField(TestCase):
         try:
             self.run_qdmanage('update --type=vhost --name=dispatch-918 --stdin',
                               input=self.both_policy())
-            self.assertTrue(false) # should not be able to update 'id'
-        except Exception,  e:
+            self.assertTrue(False) # should not be able to update 'id'
+        except Exception as e:
             pass
 
         # update using neither
@@ -585,7 +588,7 @@ class PolicyWarnings(TestCase):
         cls.router = cls.tester.qdrouterd('PolicyWarnings', config, wait=False)
         try:
             cls.router.wait_ready(timeout = 5)
-        except Exception,  e:
+        except Exception as e:
             pass
 
     def test_03_policy_warnings(self):
@@ -615,7 +618,7 @@ class PolicyLinkNamePatternTest(TestCase):
         cls.router = cls.tester.qdrouterd('PolicyLinkNamePatternTest', config, wait=False)
         try:
             cls.router.wait_ready(timeout = 5)
-        except Exception,  e:
+        except Exception as e:
             pass
 
     def address(self):
@@ -624,11 +627,12 @@ class PolicyLinkNamePatternTest(TestCase):
     def run_qdmanage(self, cmd, input=None, expect=Process.EXIT_OK):
         p = self.popen(
             ['qdmanage'] + cmd.split(' ') + ['--bus', 'u1:password@' + self.address(), '--indent=-1', '--timeout', str(TIMEOUT)],
-            stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=expect)
+            stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=expect,
+            universal_newlines=True)
         out = p.communicate(input)[0]
         try:
             p.teardown()
-        except Exception, e:
+        except Exception as e:
             raise Exception("%s\n%s" % (e, out))
         return out
 
@@ -720,8 +724,8 @@ class PolicyLinkNamePatternTest(TestCase):
         qdm_out = "<not written>"
         try:
             qdm_out = self.run_qdmanage('update --type=vhost --name=vhost/$default --stdin', input=self.default_patterns())
-        except Exception, e:
-            self.assertTrue(False, msg=('Error running qdmanage %s' % e.message))
+        except Exception as e:
+            self.assertTrue(False, msg=('Error running qdmanage %s' % str(e)))
         self.assertFalse("PolicyError" in qdm_out)
 
         # attempt an create that should be rejected
@@ -729,9 +733,9 @@ class PolicyLinkNamePatternTest(TestCase):
         exception = False
         try:
             qdm_out = self.run_qdmanage('create --type=vhost --name=DISPATCH-1993-2 --stdin', input=self.disallowed_source())
-        except Exception, e:
+        except Exception as e:
             exception = True
-            self.assertTrue("InternalServerErrorStatus: PolicyError: \"Policy 'DISPATCH-1993-2' is invalid:" in e.message)
+            self.assertTrue("InternalServerErrorStatus: PolicyError: \"Policy 'DISPATCH-1993-2' is invalid:" in str(e))
         self.assertTrue(exception)
 
         # attempt another create that should be rejected
@@ -739,9 +743,9 @@ class PolicyLinkNamePatternTest(TestCase):
         exception = False
         try:
             qdm_out = self.run_qdmanage('create --type=vhost --name=DISPATCH-1993-3 --stdin', input=self.disallowed_target())
-        except Exception, e:
+        except Exception as e:
             exception = True
-            self.assertTrue("InternalServerErrorStatus: PolicyError: \"Policy 'DISPATCH-1993-3' is invalid:" in e.message)
+            self.assertTrue("InternalServerErrorStatus: PolicyError: \"Policy 'DISPATCH-1993-3' is invalid:" in str(e))
         self.assertTrue(exception)
 
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_protocol_settings.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_protocol_settings.py b/tests/system_tests_protocol_settings.py
index 6d09dee..523a03b 100644
--- a/tests/system_tests_protocol_settings.py
+++ b/tests/system_tests_protocol_settings.py
@@ -25,7 +25,8 @@ X86_64_ARCH = "x86_64"
 skip_test = True
 
 # Dont skip tests on 64 bit architectures.
-p = subprocess.Popen("uname -m", shell=True, stdout=subprocess.PIPE)
+p = subprocess.Popen("uname -m", shell=True, stdout=subprocess.PIPE,
+                     universal_newlines=True)
 if X86_64_ARCH in p.communicate()[0]:
     skip_test = False
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_qdmanage.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_qdmanage.py b/tests/system_tests_qdmanage.py
index febd6cb..0275e53 100644
--- a/tests/system_tests_qdmanage.py
+++ b/tests/system_tests_qdmanage.py
@@ -67,12 +67,13 @@ class QdmanageTest(TestCase):
     def run_qdmanage(self, cmd, input=None, expect=Process.EXIT_OK, address=None):
         p = self.popen(
             ['qdmanage'] + cmd.split(' ') + ['--bus', address or self.address(), '--indent=-1', '--timeout', str(TIMEOUT)],
-            stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=expect)
+            stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=expect,
+            universal_newlines=True)
         out = p.communicate(input)[0]
         try:
             p.teardown()
-        except Exception, e:
-            raise Exception("%s\n%s" % (e, out))
+        except Exception as e:
+            raise Exception(out if out else str(e))
         return out
 
     def assert_entity_equal(self, expect, actual, copy=None):
@@ -122,14 +123,14 @@ class QdmanageTest(TestCase):
         expect = {'type': DUMMY, 'name': 'mydummyx', 'arg1': 'foo'}
         check('create', expect, json.dumps(expect), copy=['identity'])
 
-        expect_list = [{'type': DUMMY, 'name': 'mydummyx%s' % i} for i in xrange(3)]
+        expect_list = [{'type': DUMMY, 'name': 'mydummyx%s' % i} for i in range(3)]
         check_list('create', expect_list, json.dumps(expect_list), copy=['identity'])
 
         expect['arg1'] = 'bar'
         expect['num1'] = 42
         check('update', expect, json.dumps(expect))
 
-        for i in xrange(3):
+        for i in range(3):
             expect_list[i]['arg1'] = 'bar'
             expect_list[i]['num1'] = i
         check_list('update', expect_list, json.dumps(expect_list))
@@ -260,7 +261,7 @@ class QdmanageTest(TestCase):
             json.loads(self.run_qdmanage("UPDATE --type org.apache.qpid.dispatch.log --name log/DEFAULT outputFile="))
         except Exception as e:
             exception = True
-            self.assertTrue("InternalServerErrorStatus: CError: Configuration: Failed to open log file ''" in e.message)
+            self.assertTrue("InternalServerErrorStatus: CError: Configuration: Failed to open log file ''" in str(e))
         self.assertTrue(exception)
 
         # Set a valid 'output'
@@ -407,7 +408,7 @@ class QdmanageTest(TestCase):
             self.run_qdmanage(delete_command)
         except Exception as e:
             exception_occurred = True
-            self.assertTrue("NotFoundStatus: No entity with name='" + name + "'" in e.message)
+            self.assertTrue("NotFoundStatus: No entity with name='" + name + "'" in str(e))
 
         self.assertTrue(exception_occurred)
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_qdstat.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_qdstat.py b/tests/system_tests_qdstat.py
index 5868cca..c786598 100644
--- a/tests/system_tests_qdstat.py
+++ b/tests/system_tests_qdstat.py
@@ -40,7 +40,8 @@ class QdstatTest(system_test.TestCase):
     def run_qdstat(self, args, regexp=None, address=None):
         p = self.popen(
             ['qdstat', '--bus', str(address or self.router.addresses[0]), '--timeout', str(system_test.TIMEOUT) ] + args,
-            name='qdstat-'+self.id(), stdout=PIPE, expect=None)
+            name='qdstat-'+self.id(), stdout=PIPE, expect=None,
+            universal_newlines=True)
 
         out = p.communicate()[0]
         assert p.returncode == 0, \
@@ -140,7 +141,8 @@ try:
             p = self.popen(
                 ['qdstat', '--bus', str(address or self.router.addresses[0]), '--ssl-disable-peer-name-verify',
                  '--timeout', str(system_test.TIMEOUT) ] + args,
-                name='qdstat-'+self.id(), stdout=PIPE, expect=None)
+                name='qdstat-'+self.id(), stdout=PIPE, expect=None,
+                universal_newlines=True)
 
             out = p.communicate()[0]
             assert p.returncode == 0, \
@@ -164,11 +166,10 @@ try:
             See test_ssl_* below.
             """
             args = self.get_ssl_args()
-            addrs = [self.router.addresses[i] for i in xrange(4)];
-            urls = dict(zip(['none', 'strict', 'unsecured', 'auth'], addrs) +
-                        zip(['none_s', 'strict_s', 'unsecured_s', 'auth_s'],
+            addrs = [self.router.addresses[i] for i in range(4)];
+            urls = dict(zip(['none', 'strict', 'unsecured', 'auth'], addrs))
+            urls.update(zip(['none_s', 'strict_s', 'unsecured_s', 'auth_s'],
                             (Url(a, scheme="amqps") for a in addrs)))
-
             self.run_qdstat(['--general'] + sum([args[n] for n in arg_names], []),
                             regexp=r'(?s)Router Statistics.*Mode\s*Standalone',
                             address=str(urls[url_name]))
@@ -313,7 +314,8 @@ try:
         def run_qdstat(self, args, regexp=None, address=None):
             p = self.popen(
                 ['qdstat', '--bus', str(address or self.router.addresses[0]), '--timeout', str(system_test.TIMEOUT) ] + args,
-                name='qdstat-'+self.id(), stdout=PIPE, expect=None)
+                name='qdstat-'+self.id(), stdout=PIPE, expect=None,
+                universal_newlines=True)
             out = p.communicate()[0]
             assert p.returncode == 0, \
                 "qdstat exit status %s, output:\n%s" % (p.returncode, out)
@@ -332,9 +334,9 @@ try:
                 client_pass = ['--ssl-password', 'client-password'])
             args['client_cert_all'] = args['client_cert'] + args['client_key'] + args['client_pass']
 
-            addrs = [self.router.addresses[i] for i in xrange(4)];
-            urls = dict(zip(['none', 'strict', 'unsecured', 'auth'], addrs) +
-                        zip(['none_s', 'strict_s', 'unsecured_s', 'auth_s'],
+            addrs = [self.router.addresses[i] for i in range(4)];
+            urls = dict(zip(['none', 'strict', 'unsecured', 'auth'], addrs))
+            urls.update(zip(['none_s', 'strict_s', 'unsecured_s', 'auth_s'],
                             (Url(a, scheme="amqps") for a in addrs)))
 
             self.run_qdstat(['--general'] + sum([args[n] for n in arg_names], []),

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_sasl_plain.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_sasl_plain.py b/tests/system_tests_sasl_plain.py
index dfb1df5..1b67b2c 100644
--- a/tests/system_tests_sasl_plain.py
+++ b/tests/system_tests_sasl_plain.py
@@ -36,7 +36,7 @@ class RouterTestPlainSaslCommon(TestCase):
     def createSaslFiles(cls):
         # Create a sasl database.
         p = Popen(['saslpasswd2', '-c', '-p', '-f', 'qdrouterd.sasldb', '-u', 'domain.com', 'test'],
-                  stdin=PIPE, stdout=PIPE, stderr=PIPE)
+                  stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True)
         result = p.communicate('password')
         assert p.returncode == 0, \
             "saslpasswd2 exit status %s, output:\n%s" % (p.returncode, result)
@@ -121,7 +121,8 @@ class RouterTestPlainSasl(RouterTestPlainSaslCommon):
 
         p = self.popen(
             ['qdstat', '-b', str(self.routers[0].addresses[1]), '-c'],
-            name='qdstat-'+self.id(), stdout=PIPE, expect=None)
+            name='qdstat-'+self.id(), stdout=PIPE, expect=None,
+            universal_newlines=True)
         out = p.communicate()[0]
         assert p.returncode == 0, \
             "qdstat exit status %s, output:\n%s" % (p.returncode, out)
@@ -140,7 +141,8 @@ class RouterTestPlainSasl(RouterTestPlainSaslCommon):
         p = self.popen(
             ['qdstat', '-b', str(self.routers[0].addresses[2]), '-c', '--sasl-mechanisms=PLAIN',
              '--sasl-username=test@domain.com', '--sasl-password=password'],
-            name='qdstat-'+self.id(), stdout=PIPE, expect=None)
+            name='qdstat-'+self.id(), stdout=PIPE, expect=None,
+            universal_newlines=True)
 
         out = p.communicate()[0]
         assert p.returncode == 0, \
@@ -171,7 +173,8 @@ class RouterTestPlainSasl(RouterTestPlainSaslCommon):
         p = self.popen(
             ['qdstat', '-b', str(self.routers[0].addresses[2]), '-c', '--sasl-mechanisms=PLAIN',
              '--sasl-username=test@domain.com', '--sasl-password-file=' + password_file],
-            name='qdstat-'+self.id(), stdout=PIPE, expect=None)
+            name='qdstat-'+self.id(), stdout=PIPE, expect=None,
+            universal_newlines=True)
 
         out = p.communicate()[0]
         assert p.returncode == 0, \
@@ -279,7 +282,8 @@ class RouterTestPlainSaslOverSsl(RouterTestPlainSaslCommon):
              '--ssl-certificate=' + self.ssl_file('client-certificate.pem'),
              '--ssl-key=' + self.ssl_file('client-private-key.pem'),
              '--ssl-password=client-password'],
-            name='qdstat-'+self.id(), stdout=PIPE, expect=None)
+            name='qdstat-'+self.id(), stdout=PIPE, expect=None,
+            universal_newlines=True)
 
         out = p.communicate()[0]
         assert p.returncode == 0, \

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_topology.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_topology.py b/tests/system_tests_topology.py
index 4dd7ecf..e5af286 100644
--- a/tests/system_tests_topology.py
+++ b/tests/system_tests_topology.py
@@ -17,6 +17,7 @@
 # under the License.
 #
 
+from __future__ import print_function
 
 import unittest2 as unittest
 from proton          import Message, Timeout
@@ -399,7 +400,7 @@ class TopologyFailover ( MessagingHandler ):
 
     def debug_print ( self, text ) :
         if self.debug == True:
-            print time.time(), text
+            print("%s %s" % (time.time(), text))
 
 
     # Shut down everything and exit.

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_topology_addition.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_topology_addition.py b/tests/system_tests_topology_addition.py
index 5b3ceb4..51d2643 100644
--- a/tests/system_tests_topology_addition.py
+++ b/tests/system_tests_topology_addition.py
@@ -161,7 +161,7 @@ class TopologyAdditionTests ( TestCase ):
                                      'role': 'inter-router',
                                      'port': cls.inter_router_ports['A'],
                                      'verifyHostname': 'no',
-                                     'cost':  lower_cost / 2,
+                                     'cost':  int(lower_cost / 2),
                                      'stripAnnotations': 'no',
                                      'linkCapacity' : 1000
                                   }
@@ -171,7 +171,7 @@ class TopologyAdditionTests ( TestCase ):
                                      'role': 'inter-router',
                                      'port': cls.inter_router_ports['B'],
                                      'verifyHostname': 'no',
-                                     'cost':  lower_cost / 2,
+                                     'cost':  int(lower_cost / 2),
                                      'stripAnnotations': 'no',
                                      'linkCapacity' : 1000
                                   }
@@ -193,7 +193,7 @@ class TopologyAdditionTests ( TestCase ):
                                      'role': 'inter-router',
                                      'port': cls.inter_router_ports['A'],
                                      'verifyHostname': 'no',
-                                     'cost':  higher_cost / 2,
+                                     'cost':  int(higher_cost / 2),
                                      'stripAnnotations': 'no',
                                      'linkCapacity' : 1000
                                   }
@@ -203,7 +203,7 @@ class TopologyAdditionTests ( TestCase ):
                                      'role': 'inter-router',
                                      'port': cls.inter_router_ports['B'],
                                      'verifyHostname': 'no',
-                                     'cost':  higher_cost / 2,
+                                     'cost':  int(higher_cost / 2),
                                      'stripAnnotations': 'no',
                                      'linkCapacity' : 1000
                                   }
@@ -381,7 +381,7 @@ class AddRouter ( MessagingHandler ):
         # Make a little data structure that
         # will keep track of how many times each trace was seen.
         self.expected_trace_counts = list()
-        for i in xrange ( len(expected_traces )) :
+        for i in range ( len(expected_traces )) :
             self.expected_trace_counts.append ( [ expected_traces[i], 0 ] )
 
 
@@ -450,7 +450,7 @@ class AddRouter ( MessagingHandler ):
             return
 
         # Send little bursts of 3 messages every sender-timeout.
-        for _ in xrange(3) :
+        for _ in range(3) :
             msg = Message(body=self.n_sent)
             self.sender.send(msg)
             self.n_sent += 1

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_topology_disposition.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_topology_disposition.py b/tests/system_tests_topology_disposition.py
index 5108e1d..d902ad5 100644
--- a/tests/system_tests_topology_disposition.py
+++ b/tests/system_tests_topology_disposition.py
@@ -17,6 +17,8 @@
 # under the License.
 #
 
+from __future__ import print_function
+
 import unittest, os, json
 from subprocess      import PIPE, STDOUT
 from proton          import Message, PENDING, ACCEPTED, REJECTED, RELEASED, SSLDomain, SSLUnavailable, Timeout
@@ -25,6 +27,7 @@ from proton.handlers import MessagingHandler
 from proton.reactor  import Container, AtMostOnce, AtLeastOnce, DynamicNodeProperties, LinkOption, ApplicationEvent, EventInjector
 from proton.utils    import BlockingConnection
 from qpid_dispatch.management.client import Node
+from qpid_dispatch_internal.compat import UNICODE
 
 import time
 import datetime
@@ -95,17 +98,17 @@ class ManagementMessageHelper ( object ) :
                   'type':       'org.amqp.management'
                 }
         attrs = []
-        attrs.append ( unicode('linkType') )
-        attrs.append ( unicode('linkDir') )
-        attrs.append ( unicode('linkName') )
-        attrs.append ( unicode('owningAddr') )
-        attrs.append ( unicode('capacity') )
-        attrs.append ( unicode('undeliveredCount') )
-        attrs.append ( unicode('unsettledCount') )
-        attrs.append ( unicode('acceptedCount') )
-        attrs.append ( unicode('rejectedCount') )
-        attrs.append ( unicode('releasedCount') )
-        attrs.append ( unicode('modifiedCount') )
+        attrs.append ( UNICODE('linkType') )
+        attrs.append ( UNICODE('linkDir') )
+        attrs.append ( UNICODE('linkName') )
+        attrs.append ( UNICODE('owningAddr') )
+        attrs.append ( UNICODE('capacity') )
+        attrs.append ( UNICODE('undeliveredCount') )
+        attrs.append ( UNICODE('unsettledCount') )
+        attrs.append ( UNICODE('acceptedCount') )
+        attrs.append ( UNICODE('rejectedCount') )
+        attrs.append ( UNICODE('releasedCount') )
+        attrs.append ( UNICODE('modifiedCount') )
 
         msg_body = { }
         msg_body [ 'attributeNames' ] = attrs
@@ -435,7 +438,7 @@ class DeleteSpuriousConnector ( MessagingHandler ):
 
     def debug_print ( self, text ) :
         if self.debug == True:
-            print "%.6lf %s" % ( time.time(), text )
+            print("%.6lf %s" % ( time.time(), text ))
 
 
     # Shut down everything and exit.
@@ -568,7 +571,7 @@ class DeleteSpuriousConnector ( MessagingHandler ):
         if self.n_sent >= self.n_messages :
             return
 
-        for _ in xrange ( self.burst_size ) :
+        for _ in range ( self.burst_size ) :
             if self.sender.credit > 0 and self.n_sent < self.n_messages :
                 msg = Message ( body=self.n_sent )
                 self.n_sent += 1
@@ -764,7 +767,7 @@ class TopologyDisposition ( MessagingHandler ):
 
     def debug_print ( self, text ) :
         if self.debug == True:
-            print "%.6lf %s" % ( time.time(), text )
+            print("%.6lf %s" % ( time.time(), text ))
 
 
     # Shut down everything and exit.
@@ -899,7 +902,7 @@ class TopologyDisposition ( MessagingHandler ):
             self.debug_print ( "send called while state is %s" % self.state )
             return
 
-        for _ in xrange ( self.send_burst_size ) :
+        for _ in range ( self.send_burst_size ) :
             if self.sender.credit > 0 :
                 msg = Message ( body=self.n_sent )
                 msg_tag=str(self.n_sent)
@@ -1031,25 +1034,25 @@ class TopologyDisposition ( MessagingHandler ):
     def print_message_status ( self ) :
         for i in range ( self.n_sent ) :
             tag = str ( i )
-            print tag, self.message_status [ tag ]
+            print("%s %s" % (tag, self.message_status [ tag ]))
 
 
     # Used during debugging.
     def print_unknown_messages ( self ) :
         count = 0
-        print "Messages with unknown status: "
+        print("Messages with unknown status: ")
         for i in range ( self.n_sent ) :
             tag = str ( i )
             if self.message_status [ tag ] == 'sent' :
               count = count + 1
-              print '    ', tag, 'sent:', self.message_times [ tag ]
-        print "    total: ", count
+              print('    %s sent: %s' % (tag, self.message_times [ tag ]))
+        print("    total: %s" % count)
 
 
     # Used during debugging.
     def quick_print_unknown_messages ( self ) :
         count = 0
-        print "Messages with unknown status: "
+        print("Messages with unknown status: ")
 
         first = -1
         last  =  0
@@ -1063,9 +1066,9 @@ class TopologyDisposition ( MessagingHandler ):
               if i > last :
                 last = i
 
-        print '    first : ', first, 'sent : %.6lf' % self.message_times [ str(first) ]
-        print '    last  : ', last,  'sent : %.6lf' % self.message_times [ str(last)  ]
-        print "    total : ", count
+        print('    first : %s sent : %.6lf' % (first, self.message_times[str(first)]))
+        print('    last  : %s sent : %.6lf' % (last, self.message_times[str(last)]))
+        print("    total : %s" % count)
 
 
     def run(self):

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_user_id_proxy.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_user_id_proxy.py b/tests/system_tests_user_id_proxy.py
index f9271d1..ecea4cc 100644
--- a/tests/system_tests_user_id_proxy.py
+++ b/tests/system_tests_user_id_proxy.py
@@ -24,6 +24,7 @@ from system_test import TestCase, Qdrouterd, DIR, main_module
 import proton
 from proton import SSLDomain, Delivery
 from proton.utils import BlockingConnection
+from qpid_dispatch_internal.compat import BINARY
 
 
 class QdSSLUseridTest(TestCase):
@@ -252,7 +253,7 @@ class QdSSLUseridProxy(QdSSLUseridTest):
         blocking_sender = blocking_connection.create_sender("$management")
 
         request = proton.Message()
-        request.user_id = u"bad-user-id"
+        request.user_id = BINARY("bad-user-id")
 
         result = Delivery.ACCEPTED
         try:
@@ -284,7 +285,7 @@ class QdSSLUseridProxy(QdSSLUseridTest):
         blocking_sender = blocking_connection.create_sender("$management")
 
         request = proton.Message()
-        request.user_id = u"bad-user-id"
+        request.user_id = BINARY("bad-user-id")
 
         for i in range(0, credit_limit+1):
             result = Delivery.ACCEPTED

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tools/qdmanage
----------------------------------------------------------------------
diff --git a/tools/qdmanage b/tools/qdmanage
index 35b4485..bacef3c 100755
--- a/tools/qdmanage
+++ b/tools/qdmanage
@@ -19,6 +19,8 @@
 # under the License.
 #
 
+from __future__ import print_function
+
 import sys, json, re
 import  qpid_dispatch_site
 from qpid_dispatch.management.client import Node, Url
@@ -27,6 +29,8 @@ from optparse import OptionGroup
 from qpid_dispatch_internal.tools.command import OptionParser, Option, UsageError, connection_options, check_args, \
     main, opts_ssl_domain, opts_url, opts_sasl
 from qpid_dispatch_internal.management.qdrouter import QdSchema
+from qpid_dispatch_internal.compat import PY_TEXT_TYPE
+from qpid_dispatch_internal.compat import PY_STRING_TYPE
 
 INTEGER_TYPE = "integer"
 
@@ -78,7 +82,9 @@ class QdManage():
 
     def run(self, argv):
         # Make all args unicode to avoid encoding arg values as AMQP bytes.
-        self.opts, self.args = self.op.parse_args([unicode(x) for x in argv[1:]])
+        al = [x.decode() if not isinstance(x, PY_TEXT_TYPE) else x
+              for x in argv[1:]]
+        self.opts, self.args = self.op.parse_args(al)
         self.clean_opts()
         if self.opts.indent == -1:
             self.opts.indent = None
@@ -100,18 +106,18 @@ class QdManage():
 
     def print_json(self, data):
         """Print data as JSON"""
-        print json.dumps(data, indent=self.opts.indent)
+        print("%s" % json.dumps(data, indent=self.opts.indent))
 
     def print_result(self, result):
         """Print a string result as-is, else try json dump, else print as-is"""
         if not result: return
-        if isinstance(result, basestring):
-            print result
+        if isinstance(result, (PY_STRING_TYPE, PY_TEXT_TYPE)):
+            print("%s" % result)
         else:
             try:
                 self.print_json(result)
             except ValueError:
-                print result
+                print("%s" % result)
 
     def long_type(self, type):
         if not type or "." in type:
@@ -213,7 +219,7 @@ class QdManage():
     def json_arg(self, value):
         try:
             return json.loads(value)
-        except ValueError, e:
+        except ValueError as e:
             if not re.search(r'["{}\[\]]', value): # Doesn't look like attempted JSON.
                 return value    # Just treat as plain string
             raise ValueError("Invalid JSON '%s': %s" % (value, e))

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tools/qdstat
----------------------------------------------------------------------
diff --git a/tools/qdstat b/tools/qdstat
index b980d9d..6b8db4d 100755
--- a/tools/qdstat
+++ b/tools/qdstat
@@ -19,6 +19,8 @@
 # under the License.
 #
 
+from __future__ import print_function
+
 import os
 from optparse import OptionGroup
 import sys
@@ -32,6 +34,7 @@ from qpid_dispatch_internal.management.qdrouter import QdSchema
 from qpid_dispatch_internal.tools import Display, Header, Sorter, YN, Commas, TimeLong
 from qpid_dispatch_internal.tools.command import connection_options, main, OptionParser, opts_ssl_domain, opts_sasl, \
         opts_url
+from qpid_dispatch_internal.compat import UNICODE
 
 def parse_args(argv):
     """ Set global variables for options, return arguments """
@@ -88,7 +91,7 @@ class BusManager(Node):
         if attribute_names:
             unames = []
             for a in attribute_names:
-                unames.append(unicode(a))
+                unames.append(UNICODE(a))
             attribute_names = unames
         return super(BusManager, self).query(entity_type, attribute_names, count=limit).get_entities()
 
@@ -386,7 +389,7 @@ class BusManager(Node):
             dispRows = sort.getSorted()
             disp.formattedTable(title, heads, dispRows)
         else:
-            print "Router is Standalone - No Router List"
+            print("Router is Standalone - No Router List")
 
     def displayAddresses(self):
         disp = Display(prefix="  ")
@@ -517,7 +520,7 @@ class BusManager(Node):
             rows.append(row)
         if not rows:
             # router built w/o memory pools:
-            print "No memory statistics available"
+            print("No memory statistics available")
             return
         title = "Types"
         sorter = Sorter(heads, rows, 'type', 0, True)
@@ -527,7 +530,7 @@ class BusManager(Node):
     def displayLog(self):
         log = self.get_log(limit=self.opts.limit)
         for line in log:
-            print "%s %s (%s) %s" % (ctime(line[5]), line[0], line[1], line[2])
+            print("%s %s (%s) %s" % (ctime(line[5]), line[0], line[1], line[2]))
 
     def displayMain(self, identitys, main):
         if   main == 'l': self.displayRouterLinks()

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tox.ini
----------------------------------------------------------------------
diff --git a/tox.ini b/tox.ini
new file mode 100644
index 0000000..879569f
--- /dev/null
+++ b/tox.ini
@@ -0,0 +1,33 @@
+[tox]
+envlist = py26,py27,py35,py36
+skipsdist = True
+minversion = 1.4
+# note: when minversion is >= 1.7.2, uncomment the
+# following and remove the PASS/FAIL regular expression
+# property in CMakeLists.txt
+# This setting makes tox not treat missing environments as errors:
+#skip_missing_interpreters = True
+
+[testenv]
+commands = flake8 --count python console doc tests tools
+deps = hacking
+
+[testenv:py26]
+basepython = python2.6
+
+[testenv:py27]
+basepython = python2.7
+
+[testenv:py35]
+basepython = python3.5
+
+[testenv:py36]
+basepython = python3.6
+
+[flake8]
+show-source = True
+# we really need to check for some of these, but the
+# code will need lots of work to correct this issues
+ignore = E111,E114,E121,E122,E123,E124,E126,E127,E128,E131,E201,E202,E203,E211,E221,E222,E225,E226,E228,E231,E241,E251,E261,E266,E265,E271,E272,E301,E302,E303,E401,E402,E501,E502,E701,E702,E703,E704,E711,E712,E713,E714,E731,F401,F403,F405,F811,F841,H101,H102,H104,H201,H202,H234,H237,H238,H301,H306,H401,H403,H404,H405,W291,W292,W293,W391,W503
+
+


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org


[07/11] qpid-dispatch git commit: DISPATCH-965: Let's fix the Ubuntu build! :)

Posted by kg...@apache.org.
DISPATCH-965: Let's fix the Ubuntu build! :)


Project: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/repo
Commit: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/commit/9d3cecf9
Tree: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/tree/9d3cecf9
Diff: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/diff/9d3cecf9

Branch: refs/heads/master
Commit: 9d3cecf993daf7a0a59ee9afb00bac7d9fb26ee4
Parents: a5c40da
Author: Kenneth Giusti <kg...@apache.org>
Authored: Wed May 16 17:04:56 2018 -0400
Committer: Kenneth Giusti <kg...@apache.org>
Committed: Wed May 16 17:04:56 2018 -0400

----------------------------------------------------------------------
 src/error.c | 16 +++++++++++++---
 1 file changed, 13 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/9d3cecf9/src/error.c
----------------------------------------------------------------------
diff --git a/src/error.c b/src/error.c
index b62ae1d..4a7c815 100644
--- a/src/error.c
+++ b/src/error.c
@@ -23,13 +23,20 @@
 #include <qpid/dispatch/enum.h>
 #include <qpid/dispatch/log.h>
 #include <stdarg.h>
-#include <stdio.h>
 #include <errno.h>
 #include <string.h>
 #include "log_private.h"
 #include "aprintf.h"
 #include "python_private.h"
 
+// force the use of the non-gnu version of strerror_r
+#undef _POSIX_C_SOURCE
+#undef _GNU_SOURCE
+#define _POSIX_C_SOURCE 200112L
+#define _GNU_SOURCE 0
+#include <stdio.h>
+
+
 static const char *qd_error_names[] = {
  "No Error",
  "Not found",
@@ -198,8 +205,11 @@ qd_error_t qd_error_errno_impl(int errnum, const char *file, int line, const cha
         vaprintf(&begin, end, fmt, arglist);
         va_end(arglist);
         aprintf(&begin, end, ": ", errnum);
-        (void)strerror_r(errnum, begin, end - begin);
-        qd_log_impl(log_source, QD_LOG_ERROR, file, line, "%s", ts.error_message);
+        char *em = ts.error_message;
+        if(strerror_r(errnum, begin, end - begin) != 0) {
+            snprintf(begin, end - begin, "Unknown error %d", errnum);
+        }
+        qd_log_impl(log_source, QD_LOG_ERROR, file, line, "%s", em);
         return qd_error_code();
     }
     else


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org


[11/11] qpid-dispatch git commit: DISPATCH-965: fix exception syntax

Posted by kg...@apache.org.
DISPATCH-965: fix exception syntax

This closes #305


Project: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/repo
Commit: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/commit/561f210f
Tree: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/tree/561f210f
Diff: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/diff/561f210f

Branch: refs/heads/master
Commit: 561f210f48a670a2ebe8f709daea4587f4a9b1b6
Parents: 234be47
Author: Kenneth Giusti <kg...@apache.org>
Authored: Thu May 31 15:17:17 2018 -0400
Committer: Kenneth Giusti <kg...@apache.org>
Committed: Fri Jun 1 10:54:17 2018 -0400

----------------------------------------------------------------------
 tests/system_tests_policy.py | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/561f210f/tests/system_tests_policy.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_policy.py b/tests/system_tests_policy.py
index 846e935..5ab99d5 100644
--- a/tests/system_tests_policy.py
+++ b/tests/system_tests_policy.py
@@ -773,7 +773,7 @@ class PolicyHostamePatternTest(TestCase):
         cls.router = cls.tester.qdrouterd('PolicyVhostNamePatternTest', config, wait=True)
         try:
             cls.router.wait_ready(timeout = 5)
-        except Exception,  e:
+        except Exception:
             pass
 
     def address(self):
@@ -786,7 +786,7 @@ class PolicyHostamePatternTest(TestCase):
         out = p.communicate(input)[0]
         try:
             p.teardown()
-        except Exception, e:
+        except Exception as e:
             raise Exception("%s\n%s" % (e, out))
         return out
 
@@ -824,7 +824,7 @@ class PolicyHostamePatternTest(TestCase):
         qdm_out = "<not written>"
         try:
             qdm_out = self.run_qdmanage('create --type=vhost --name=#.#.0.0 --stdin', input=self.disallowed_hostname())
-        except Exception, e:
+        except Exception as e:
             self.assertTrue("pattern conflicts" in e.message, msg=('Error running qdmanage %s' % e.message))
         self.assertFalse("222222" in qdm_out)
 


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org


[05/11] qpid-dispatch git commit: DISPATCH-965: restrict tox version, fixup 2.6 issues

Posted by kg...@apache.org.
DISPATCH-965: restrict tox version, fixup 2.6 issues


Project: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/repo
Commit: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/commit/fb363cb5
Tree: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/tree/fb363cb5
Diff: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/diff/fb363cb5

Branch: refs/heads/master
Commit: fb363cb55411eb96667f63637d0a1cacb56df655
Parents: 7bdd55c
Author: Kenneth Giusti <kg...@redhat.com>
Authored: Tue May 15 20:56:12 2018 -0400
Committer: Kenneth Giusti <kg...@redhat.com>
Committed: Wed May 16 00:24:41 2018 -0400

----------------------------------------------------------------------
 .../qpid_dispatch_internal/management/schema.py |  1 +
 src/entity.c                                    |  7 ++++
 tests/CMakeLists.txt                            | 37 ++++++++++++++------
 tests/tox.ini.in                                | 27 ++++++++++++++
 tox.ini                                         | 34 ------------------
 5 files changed, 62 insertions(+), 44 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/fb363cb5/python/qpid_dispatch_internal/management/schema.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/management/schema.py b/python/qpid_dispatch_internal/management/schema.py
index 227f96a..f42cf10 100644
--- a/python/qpid_dispatch_internal/management/schema.py
+++ b/python/qpid_dispatch_internal/management/schema.py
@@ -116,6 +116,7 @@ class EnumValue(str):
 
     def __hash__(self): return super(EnumValue, self).__hash__()
     def __int__(self): return self.value
+    def __long__(self): return self.value
     def __eq__(self, x): return str(self) == x or int(self) == x
     def __ne__(self, x): return not self == x
     def __repr__(self): return "EnumValue('%s', %s)"%(str(self), int(self))

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/fb363cb5/src/entity.c
----------------------------------------------------------------------
diff --git a/src/entity.c b/src/entity.c
index 59717ab..9bcf6fa 100644
--- a/src/entity.c
+++ b/src/entity.c
@@ -54,6 +54,13 @@ char *qd_entity_get_string(qd_entity_t *entity, const char* attribute) {
 long qd_entity_get_long(qd_entity_t *entity, const char* attribute) {
     qd_error_clear();
     PyObject *py_obj = qd_entity_get_py(entity, attribute);
+    if (py_obj && !PyLong_Check(py_obj)) {
+        // 2.6 PyLong_AsLong fails to 'cast' non-long types
+        // so we have to manually cast it first:
+        PyObject *py_tmp = PyNumber_Long(py_obj);
+        Py_XDECREF(py_obj);
+        py_obj = py_tmp;
+    }
     long result = py_obj ? PyLong_AsLong(py_obj) : -1;
     Py_XDECREF(py_obj);
     qd_error_py();

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/fb363cb5/tests/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 11bf33c..77c4c4d 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -117,19 +117,36 @@ foreach(py_test_module
 endforeach()
 
 # Use tox to run the flake8 python linter tool on all the python
-# sources. Highly recommended if you're hacking the python code
+# sources. Highly recommended if you're hacking the python code.
+# Unfortunately this can only be done for versions of tox >= 1.9.0
+# since that version allows us to skip the install step (we have
+# no modules thus no setup.py)
 #
 find_program(TOX_EXE "tox")
 if (TOX_EXE)
-  add_test (NAME python-checker
-            COMMAND ${TOX_EXE}
-            WORKING_DIRECTORY ${CMAKE_SOURCE_DIR})
-  # Once we move to tox >= v1.7.2 we can remove the next
-  # line.  See tox.ini file for details
-  set_tests_properties(python-checker
-                       PROPERTIES
-                       PASS_REGULAR_EXPRESSION "commands succeeded"
-                       FAIL_REGULAR_EXPRESSION "commands failed")
+  set(TOX_MIN_VERSION 1.9.0)
+  execute_process(COMMAND ${PYTHON_EXECUTABLE} -c "import tox, sys; print('%s' % tox.__version__); sys.exit(0)"
+                  RESULT_VARIABLE TOX_STATUS
+                  OUTPUT_VARIABLE TOX_VERSION)
+  if (TOX_STATUS EQUAL 0)
+    string(STRIP ${TOX_VERSION} TOX_VERSION)
+    if (TOX_VERSION STRLESS TOX_MIN_VERSION)
+      message( STATUS "tox version ${TOX_VERSION} < required version ${TOX_MIN_VERSION} - skipping python-checker")
+    else (TOX_VERSION STRLESS TOX_MIN_VERSION)
+      configure_file(${CMAKE_CURRENT_SOURCE_DIR}/tox.ini.in ${CMAKE_CURRENT_BINARY_DIR}/tox.ini)
+      add_test (NAME python-checker
+                COMMAND ${TOX_EXE}
+                WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
+      # Once we move to tox >= v1.7.2 we can remove the next
+      # line.  See tox.ini file for details
+      set_tests_properties(python-checker
+                           PROPERTIES
+                           PASS_REGULAR_EXPRESSION "commands succeeded"
+                           FAIL_REGULAR_EXPRESSION "commands failed")
+    endif (TOX_VERSION STRLESS TOX_MIN_VERSION)
+  else (TOX_STATUS EQUAL 0)
+    message(STATUS "Cannot determine tox version - skipping python-checker")
+  endif (TOX_STATUS EQUAL 0)
 
 else (TOX_EXE)
   message(STATUS "Could NOT find 'tox' tool - unable to validate python code")

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/fb363cb5/tests/tox.ini.in
----------------------------------------------------------------------
diff --git a/tests/tox.ini.in b/tests/tox.ini.in
new file mode 100644
index 0000000..d431628
--- /dev/null
+++ b/tests/tox.ini.in
@@ -0,0 +1,27 @@
+[tox]
+envlist = py27,py35,py36
+skipsdist = True
+minversion = ${TOX_VERSION}
+skip_missing_interpreters = True
+skip_install = True
+
+[testenv]
+# we ignore lots of errors/warnings we probably should not,
+# but it will take a lot of effort to make the code PEP8 compliant...
+commands = flake8 --count ${CMAKE_SOURCE_DIR}/python ${CMAKE_SOURCE_DIR}/console ${CMAKE_SOURCE_DIR}/doc ${CMAKE_SOURCE_DIR}/tests ${CMAKE_SOURCE_DIR}/tools --show-source --ignore=E111,E114,E121,E122,E123,E124,E126,E127,E128,E131,E201,E202,E203,E211,E221,E222,E225,E226,E228,E231,E241,E251,E261,E266,E265,E271,E272,E301,E302,E303,E401,E402,E501,E502,E701,E702,E703,E704,E711,E712,E713,E714,E731,F401,F403,F405,F811,F841,H101,H102,H104,H201,H202,H234,H237,H238,H301,H306,H401,H403,H404,H405,W291,W292,W293,W391,W503
+deps = hacking>=1.1.0
+
+# flake8 no longer supports python2.6
+# [testenv:py26]
+# basepython = python2.6
+
+[testenv:py27]
+basepython = python2.7
+
+[testenv:py35]
+basepython = python3.5
+
+[testenv:py36]
+basepython = python3.6
+
+

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/fb363cb5/tox.ini
----------------------------------------------------------------------
diff --git a/tox.ini b/tox.ini
deleted file mode 100644
index 6f749fd..0000000
--- a/tox.ini
+++ /dev/null
@@ -1,34 +0,0 @@
-[tox]
-envlist = py27,py35,py36
-skipsdist = True
-minversion = 1.4
-# note: when minversion is >= 1.7.2, uncomment the
-# following and remove the PASS/FAIL regular expression
-# property in CMakeLists.txt
-# This setting makes tox not treat missing environments as errors:
-#skip_missing_interpreters = True
-
-[testenv]
-commands = flake8 --count python console doc tests tools
-deps = hacking
-
-# flake8 no longer supports python2.6
-# [testenv:py26]
-# basepython = python2.6
-
-[testenv:py27]
-basepython = python2.7
-
-[testenv:py35]
-basepython = python3.5
-
-[testenv:py36]
-basepython = python3.6
-
-[flake8]
-show-source = True
-# we really need to check for some of these, but the
-# code will need lots of work to correct this issues
-ignore = E111,E114,E121,E122,E123,E124,E126,E127,E128,E131,E201,E202,E203,E211,E221,E222,E225,E226,E228,E231,E241,E251,E261,E266,E265,E271,E272,E301,E302,E303,E401,E402,E501,E502,E701,E702,E703,E704,E711,E712,E713,E714,E731,F401,F403,F405,F811,F841,H101,H102,H104,H201,H202,H234,H237,H238,H301,H306,H401,H403,H404,H405,W291,W292,W293,W391,W503
-
-


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org


[10/11] qpid-dispatch git commit: Merge branch 'master' into DISPATCH-965

Posted by kg...@apache.org.
Merge branch 'master' into DISPATCH-965


Project: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/repo
Commit: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/commit/234be477
Tree: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/tree/234be477
Diff: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/diff/234be477

Branch: refs/heads/master
Commit: 234be477019c20ad4f70fb4c0e03625ce0f447f3
Parents: 85ef129 91def84
Author: Kenneth Giusti <kg...@apache.org>
Authored: Thu May 31 15:14:14 2018 -0400
Committer: Kenneth Giusti <kg...@apache.org>
Committed: Thu May 31 15:14:14 2018 -0400

----------------------------------------------------------------------
 .gitignore                                      |     1 +
 CMakeLists.txt                                  |     5 +-
 README                                          |     4 +-
 console/README.md                               |    24 +
 console/config/.gitignore                       |     2 -
 console/config/README                           |    28 -
 console/config/config.py                        |   467 -
 console/config/css/brokers.ttf                  |   Bin 2272 -> 0 bytes
 console/config/css/dispatch.css                 |   738 -
 console/config/css/mock.css                     |   165 -
 console/config/css/plugin.css                   |   986 -
 console/config/css/site-base.css                |  4706 ---
 console/config/deploy                           |    38 -
 .../config/deployments/install_dispatch.yaml    |    78 -
 console/config/deployments/run_dispatch.yaml    |    37 -
 console/config/favicon-32x32.png                |   Bin 1055 -> 0 bytes
 console/config/html/qdrTopology.html            |   279 -
 console/config/index.html                       |    91 -
 console/config/js/dispatchPlugin.js             |   157 -
 console/config/js/qdrNewNode.js                 |   329 -
 console/config/js/qdrService.js                 |   282 -
 console/config/js/qdrTopology.js                |  2034 --
 console/config/mock/__init__.py                 |    23 -
 console/config/mock/schema.py                   |    59 -
 console/config/mock/section.py                  |   116 -
 console/config/package.json                     |    37 -
 console/config/schema.json                      |  1814 --
 console/config/topologies/config-2/A.conf       |    40 -
 console/config/topologies/config-2/B.conf       |    31 -
 console/dispatch-dashboard/MANIFEST.in          |     3 -
 console/dispatch-dashboard/README.rst           |    59 -
 console/dispatch-dashboard/dispatch/__init__.py |    18 -
 .../dispatch-dashboard/dispatch/dashboard.py    |    28 -
 .../dispatch/overv/__init__.py                  |    18 -
 .../dispatch-dashboard/dispatch/overv/panel.py  |    25 -
 .../dispatch/overv/templates/overv/index.html   |    32 -
 .../dispatch-dashboard/dispatch/overv/tests.py  |    24 -
 .../dispatch-dashboard/dispatch/overv/urls.py   |    25 -
 .../dispatch-dashboard/dispatch/overv/views.py  |    27 -
 .../static/dashboard/dispatch/connect.json      |     2 -
 .../dashboard/dispatch/dispatch.comService.js   |   937 -
 .../dashboard/dispatch/dispatch.module.js       |   256 -
 .../static/dashboard/dispatch/dispatch.scss     |  2135 --
 .../dashboard/dispatch/jquery.dynatree.min.js   |     4 -
 .../static/dashboard/dispatch/lib/d3.v3.min.js  |     5 -
 .../static/dashboard/dispatch/lib/rhea-min.js   |     4 -
 .../static/dashboard/dispatch/lib/slider.js     |   233 -
 .../static/dashboard/dispatch/lib/ui-grid.js    | 28540 -----------------
 .../dispatch/overv/overview.controller.js       |  1430 -
 .../dashboard/dispatch/overv/overview.module.js |   178 -
 .../dashboard/dispatch/qdrChartService.js       |  1109 -
 .../dispatch/topology/config-file-header.html   |    17 -
 .../topology/download-dialog-template.html      |    42 -
 .../dispatch/topology/node-config-template.html |    70 -
 .../dispatch/topology/topology.controller.js    |  1703 -
 .../topology/topology.download-controller.js    |   150 -
 .../topology/topology.form-controller.js        |    73 -
 .../dispatch/topology/topology.module.js        |   112 -
 .../topology/topology.node-controller.js        |   294 -
 .../dispatch/templates/dispatch/base.html       |    29 -
 .../dispatch/topology/__init__.py               |    18 -
 .../dispatch/topology/panel.py                  |    25 -
 .../topology/templates/topology/index.html      |    54 -
 .../dispatch/topology/tests.py                  |    24 -
 .../dispatch/topology/urls.py                   |    25 -
 .../dispatch/topology/views.py                  |    27 -
 .../enabled/_4000_dispatch.py                   |    38 -
 .../enabled/_4030_dispatch_overv_panel.py       |    33 -
 .../enabled/_4050_dispatch_topology_panel.py    |    33 -
 console/dispatch-dashboard/setup.py             |    42 -
 console/stand-alone/index.html                  |    35 +-
 console/stand-alone/package.json                |     3 +-
 console/stand-alone/plugin/css/brokers.ttf      |   Bin 0 -> 2272 bytes
 console/stand-alone/plugin/css/dispatch.css     |  2164 ++
 console/stand-alone/plugin/html/qdrCharts.html  |    48 +
 console/stand-alone/plugin/html/qdrConnect.html |   105 +
 console/stand-alone/plugin/html/qdrList.html    |   144 +
 .../stand-alone/plugin/html/qdrOverview.html    |   283 +
 console/stand-alone/plugin/html/qdrSchema.html  |    60 +
 .../stand-alone/plugin/html/qdrTopology.html    |   280 +
 .../plugin/html/tmplChartConfig.html            |    85 +
 .../stand-alone/plugin/html/tmplListChart.html  |    40 +
 .../stand-alone/plugin/html/tmplListTree.html   |    42 +
 .../plugin/html/tmplOverviewTree.html           |    48 +
 console/stand-alone/plugin/js/chord/matrix.js   |    19 +-
 console/stand-alone/plugin/js/chord/qdrChord.js |     2 +-
 console/stand-alone/plugin/js/dispatchPlugin.js |    10 +-
 .../stand-alone/plugin/js/dlgChartController.js |   204 +
 .../stand-alone/plugin/js/qdrChartService.js    |   859 +
 console/stand-alone/plugin/js/qdrCharts.js      |   160 +
 console/stand-alone/plugin/js/qdrGlobals.js     |    46 +
 console/stand-alone/plugin/js/qdrList.js        |   940 +
 console/stand-alone/plugin/js/qdrListChart.js   |   146 +
 console/stand-alone/plugin/js/qdrOverview.js    |  1774 +
 .../plugin/js/qdrOverviewChartsController.js    |   134 +
 .../plugin/js/qdrOverviewLogsController.js      |    70 +
 console/stand-alone/plugin/js/qdrSchema.js      |    83 +
 console/stand-alone/plugin/js/qdrService.js     |   269 +
 console/stand-alone/plugin/js/qdrSettings.js    |   176 +
 .../plugin/js/qdrTopAddressesController.js      |   218 +
 .../plugin/js/topology/qdrTopology.js           |  1608 +
 .../stand-alone/plugin/js/topology/traffic.js   |   440 +
 doc/book/policy.adoc                            |    59 +
 include/qpid/dispatch/message.h                 |    12 +-
 python/qpid_dispatch/management/qdrouter.json   |     7 +
 python/qpid_dispatch_internal/dispatch.py       |     4 +
 .../qpid_dispatch_internal/management/config.py |    17 +-
 .../policy/policy_local.py                      |    33 +-
 .../policy/policy_manager.py                    |     8 +
 src/dispatch.c                                  |    15 +
 src/http-libwebsockets.c                        |    16 +-
 src/message.c                                   |    18 +-
 src/message_private.h                           |     1 +
 src/policy.c                                    |   109 +-
 src/policy.h                                    |    25 +
 src/router_core/connections.c                   |     2 +
 src/router_core/forwarder.c                     |     9 +-
 src/router_core/router_core_private.h           |     2 +-
 src/router_core/transfer.c                      |    60 +-
 tests/CMakeLists.txt                            |     1 +
 tests/parse_tree_tests.c                        |    67 +
 tests/policy-8/management-access.json           |    46 +
 ..._tests_disallow_link_resumable_link_route.py |     3 +-
 tests/system_tests_one_router.py                |   141 +-
 tests/system_tests_policy.py                    |    75 +
 tests/system_tests_ssl.py                       |   592 +
 126 files changed, 11675 insertions(+), 50614 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/234be477/.gitignore
----------------------------------------------------------------------
diff --cc .gitignore
index 52d844c,4ab831e..0b06144
--- a/.gitignore
+++ b/.gitignore
@@@ -13,4 -13,4 +13,5 @@@ tests/policy-1/policy-*.jso
  .settings
  console/test/topolgies/config-*
  .history
 +.tox
+ .vscode

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/234be477/python/qpid_dispatch_internal/dispatch.py
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/234be477/python/qpid_dispatch_internal/management/config.py
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/234be477/python/qpid_dispatch_internal/policy/policy_local.py
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/234be477/python/qpid_dispatch_internal/policy/policy_manager.py
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/234be477/src/policy.c
----------------------------------------------------------------------
diff --cc src/policy.c
index 35f3fb8,c7f9e50..31d31da
--- a/src/policy.c
+++ b/src/policy.c
@@@ -558,16 -574,15 +583,16 @@@ bool _qd_policy_approve_link_name(cons
  
      // Create a temporary writable copy of incoming allowed list
      char t_allow[QPALN_SIZE + 1]; // temporary buffer for normal allow lists
 +    int buflen = sizeof(t_allow);
      char * pa = t_allow;
 -    if (a_len > QPALN_SIZE) {
 -        pa = (char *)malloc(a_len + 1); // malloc a buffer for larger allow lists
 +    if (a_len >= buflen) {
 +        buflen = a_len + 1;
 +        pa = (char *)malloc(buflen); // malloc a buffer for larger allow lists
 +        if (!pa)
 +            return false;
      }
-     strcpy(pa, allowed);
 -    if (!pa)
 -        return false;
--
+     strcpy(pa, allowed);        /* We know we have allocated enoough space */
+     pa[a_len] = 0;
      // Do reverse user substitution into proposed
      char substbuf[QPALN_USERBUFSIZE];
      char * prop2 = _qd_policy_link_user_name_subst(username, proposed, substbuf, QPALN_USERBUFSIZE);

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/234be477/tests/CMakeLists.txt
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/234be477/tests/system_tests_disallow_link_resumable_link_route.py
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/234be477/tests/system_tests_one_router.py
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/234be477/tests/system_tests_policy.py
----------------------------------------------------------------------


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org


[09/11] qpid-dispatch git commit: DISPATCH-965: make the apache-rat happy

Posted by kg...@apache.org.
DISPATCH-965: make the apache-rat happy


Project: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/repo
Commit: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/commit/85ef129a
Tree: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/tree/85ef129a
Diff: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/diff/85ef129a

Branch: refs/heads/master
Commit: 85ef129a041210152f44874a262044f6dc3849ac
Parents: 7293938
Author: Kenneth Giusti <kg...@apache.org>
Authored: Wed May 16 17:30:45 2018 -0400
Committer: Kenneth Giusti <kg...@apache.org>
Committed: Wed May 16 17:30:45 2018 -0400

----------------------------------------------------------------------
 tests/tox.ini.in | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/85ef129a/tests/tox.ini.in
----------------------------------------------------------------------
diff --git a/tests/tox.ini.in b/tests/tox.ini.in
index d431628..deb4ee8 100644
--- a/tests/tox.ini.in
+++ b/tests/tox.ini.in
@@ -1,3 +1,22 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
 [tox]
 envlist = py27,py35,py36
 skipsdist = True


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org


[06/11] qpid-dispatch git commit: DISPATCH-965: fix the 2.x fixes for 3.x

Posted by kg...@apache.org.
DISPATCH-965: fix the 2.x fixes for 3.x


Project: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/repo
Commit: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/commit/a5c40dae
Tree: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/tree/a5c40dae
Diff: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/diff/a5c40dae

Branch: refs/heads/master
Commit: a5c40dae9ac1f075c98826f1e1305cb506669672
Parents: fb363cb
Author: Kenneth Giusti <kg...@redhat.com>
Authored: Wed May 16 13:12:12 2018 -0400
Committer: Kenneth Giusti <kg...@redhat.com>
Committed: Wed May 16 13:34:16 2018 -0400

----------------------------------------------------------------------
 tests/system_tests_link_routes.py | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/a5c40dae/tests/system_tests_link_routes.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_link_routes.py b/tests/system_tests_link_routes.py
index 8740c80..57e6d41 100644
--- a/tests/system_tests_link_routes.py
+++ b/tests/system_tests_link_routes.py
@@ -776,7 +776,10 @@ class DeliveryTagsTest(MessagingHandler):
         self.delivery_tag_verified = False
         # The delivery tag we are going to send in the transfer frame
         # We will later make sure that the same delivery tag shows up on the receiving end in the link routed case.
-        self.delivery_tag = b'92319'
+        # KAG: force the literal to type 'str' due to SWIG weirdness: on 2.X a
+        # delivery tag cannot be unicode (must be binary), but on 3.X it must
+        # be unicode!  See https://issues.apache.org/jira/browse/PROTON-1843
+        self.delivery_tag = str('92319')
         self.error = None
 
     def timeout(self):


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org


[02/11] qpid-dispatch git commit: DISPATCH-965: port python code to Python 3. Stay compatible with 2.6-7

Posted by kg...@apache.org.
http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/src/error.c
----------------------------------------------------------------------
diff --git a/src/error.c b/src/error.c
index b837a65..e3009cb 100644
--- a/src/error.c
+++ b/src/error.c
@@ -19,11 +19,10 @@
 
 
 /* Make sure we get the XSI compliant strerror_r from string.h not the GNU one. */
-#define _POSIX_C_SOURCE 200112L
-#undef _GNU_SOURCE
+/*#define _POSIX_C_SOURCE 200112L
+  #undef _GNU_SOURCE*/
 #include <string.h>
 
-#include <Python.h>
 #include <qpid/dispatch/error.h>
 #include <qpid/dispatch/enum.h>
 #include <qpid/dispatch/log.h>
@@ -33,6 +32,7 @@
 #include <errno.h>
 #include "log_private.h"
 #include "aprintf.h"
+#include "python_private.h"
 
 static const char *qd_error_names[] = {
  "No Error",
@@ -108,7 +108,7 @@ qd_error_t qd_error_code() {
 }
 
 static void py_set_item(PyObject *dict, const char* name, PyObject *value) {
-    PyObject *py_name = PyString_FromString(name);
+    PyObject *py_name = PyUnicode_FromString(name);
     PyDict_SetItem(dict, py_name, value);
     Py_DECREF(py_name);
 }
@@ -138,17 +138,21 @@ static void log_trace_py(PyObject *type, PyObject *value, PyObject* trace, qd_lo
 
 
     if (result) {
-        const char* trace = PyString_AsString(result);
-        if (strlen(trace) < QD_LOG_TEXT_MAX) {
-            qd_log_impl(log_source, level, file, line, "%s", trace);
-        } else {
-            // Keep as much of the the tail of the trace as we can.
-            const char *tail = trace;
-            while (tail && strlen(tail) > QD_LOG_TEXT_MAX) {
-                tail = strchr(tail, '\n');
-                if (tail) ++tail;
+	char *trace = py_string_2_c(result);
+	if (trace) {
+            if (strlen(trace) < QD_LOG_TEXT_MAX) {
+                qd_log_impl(log_source, level, file, line, "%s", trace);
+            } else {
+                // Keep as much of the the tail of the trace as we can.
+                const char *tail = trace;
+                while (tail && strlen(tail) > QD_LOG_TEXT_MAX) {
+                    tail = strchr(tail, '\n');
+                    if (tail) ++tail;
+                }
+                qd_log_impl(log_source, level, file, line,
+                            "Traceback truncated:\n%s", tail ? tail : "");
             }
-            qd_log_impl(log_source, level, file, line, "Traceback truncated:\n%s", tail ? tail : "");
+            free(trace);
         }
         Py_DECREF(result);
     }
@@ -161,19 +165,21 @@ qd_error_t qd_error_py_impl(const char *file, int line) {
         PyErr_Fetch(&type, &value, &trace); /* Note clears the python error indicator */
 
         PyObject *py_type_name = type ? PyObject_GetAttrString(type, "__name__") : NULL;
-        const char *type_name = py_type_name ? PyString_AsString(py_type_name) : NULL;
-
+        char *type_name = py_type_name ? py_string_2_c(py_type_name) : NULL;
         PyObject *py_value_str = value ? PyObject_Str(value) : NULL;
-        const char *value_str = py_value_str ? PyString_AsString(py_value_str) : NULL;
-        if (!value_str) value_str = "Unknown";
+        char *value_str = py_string_2_c(py_value_str);
 
         PyErr_Clear(); /* Ignore errors while we're trying to build the values. */
         if (type_name)
-            qd_error_impl(QD_ERROR_PYTHON, file, line, "%s: %s", type_name, value_str);
+            qd_error_impl(QD_ERROR_PYTHON, file, line, "%s: %s", type_name,
+                          (value_str) ? value_str : "Unknown");
         else
-            qd_error_impl(QD_ERROR_PYTHON, file, line, "%s", value_str);
+            qd_error_impl(QD_ERROR_PYTHON, file, line, "%s",
+                          (value_str) ? value_str : "Unknown");
         Py_XDECREF(py_value_str);
+        free(value_str);
         Py_XDECREF(py_type_name);
+        free(type_name);
 
         log_trace_py(type, value, trace, QD_LOG_ERROR, file, line);
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/src/log.c
----------------------------------------------------------------------
diff --git a/src/log.c b/src/log.c
index e8b4b74..fbb757a 100644
--- a/src/log.c
+++ b/src/log.c
@@ -17,8 +17,6 @@
  * under the License.
  */
 
-#include <Python.h>
-
 #include "log_private.h"
 #include "entity.h"
 #include "entity_cache.h"
@@ -34,6 +32,7 @@
 #include <string.h>
 #include <time.h>
 #include <syslog.h>
+#include "python_private.h"
 
 #define TEXT_MAX QD_LOG_TEXT_MAX
 #define LOG_MAX (QD_LOG_TEXT_MAX+128)
@@ -444,11 +443,11 @@ PyObject *qd_log_recent_py(long limit) {
         if (!py_entry) goto error;
         int i = 0;
         // NOTE: PyList_SetItem steals a reference so no leak here.
-        PyList_SetItem(py_entry, i++, PyString_FromString(entry->module));
+        PyList_SetItem(py_entry, i++, PyUnicode_FromString(entry->module));
         const char* level = level_name(entry->level);
-        PyList_SetItem(py_entry, i++, level ? PyString_FromString(level) : inc_none());
-        PyList_SetItem(py_entry, i++, PyString_FromString(entry->text));
-        PyList_SetItem(py_entry, i++, entry->file ? PyString_FromString(entry->file) : inc_none());
+        PyList_SetItem(py_entry, i++, level ? PyUnicode_FromString(level) : inc_none());
+        PyList_SetItem(py_entry, i++, PyUnicode_FromString(entry->text));
+        PyList_SetItem(py_entry, i++, entry->file ? PyUnicode_FromString(entry->file) : inc_none());
         PyList_SetItem(py_entry, i++, entry->file ? PyLong_FromLong(entry->line) : inc_none());
         PyList_SetItem(py_entry, i++, PyLong_FromLongLong((PY_LONG_LONG)entry->time.tv_sec));
         assert(i == ENTRY_SIZE);

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/src/parse.c
----------------------------------------------------------------------
diff --git a/src/parse.c b/src/parse.c
index 4aed853..1dc726b 100644
--- a/src/parse.c
+++ b/src/parse.c
@@ -22,6 +22,10 @@
 #include <qpid/dispatch/parse.h>
 #include <qpid/dispatch/amqp.h>
 
+#include <stdio.h>
+#include <limits.h>
+#include <assert.h>
+
 DEQ_DECLARE(qd_parsed_field_t, qd_parsed_field_list_t);
 
 struct qd_parsed_field_t {
@@ -357,29 +361,9 @@ qd_iterator_t *qd_parse_typed(qd_parsed_field_t *field)
 uint32_t qd_parse_as_uint(qd_parsed_field_t *field)
 {
     uint32_t result = 0;
-
-    qd_iterator_reset(field->raw_iter);
-
-    switch (field->tag) {
-    case QD_AMQP_UINT:
-        result |= ((uint32_t) qd_iterator_octet(field->raw_iter)) << 24;
-        result |= ((uint32_t) qd_iterator_octet(field->raw_iter)) << 16;
-        // fallthrough
-
-    case QD_AMQP_USHORT:
-        result |= ((uint32_t) qd_iterator_octet(field->raw_iter)) << 8;
-        // Fall Through...
-
-    case QD_AMQP_UBYTE:
-    case QD_AMQP_SMALLUINT:
-    case QD_AMQP_BOOLEAN:
-        result |= (uint32_t) qd_iterator_octet(field->raw_iter);
-        break;
-
-    case QD_AMQP_TRUE:
-        result = 1;
-        break;
-    }
+    uint64_t tmp = qd_parse_as_ulong(field);
+    if (tmp <= UINT_MAX)
+        result = tmp;
 
     return result;
 }
@@ -398,17 +382,50 @@ uint64_t qd_parse_as_ulong(qd_parsed_field_t *field)
         result |= ((uint64_t) qd_iterator_octet(field->raw_iter)) << 48;
         result |= ((uint64_t) qd_iterator_octet(field->raw_iter)) << 40;
         result |= ((uint64_t) qd_iterator_octet(field->raw_iter)) << 32;
+        // Fall Through...
+
+    case QD_AMQP_UINT:
         result |= ((uint64_t) qd_iterator_octet(field->raw_iter)) << 24;
         result |= ((uint64_t) qd_iterator_octet(field->raw_iter)) << 16;
+        // Fall Through...
+
+    case QD_AMQP_USHORT:
         result |= ((uint64_t) qd_iterator_octet(field->raw_iter)) << 8;
         // Fall Through...
 
+    case QD_AMQP_BOOLEAN:
+    case QD_AMQP_UBYTE:
+    case QD_AMQP_SMALLUINT:
     case QD_AMQP_SMALLULONG:
         result |= (uint64_t) qd_iterator_octet(field->raw_iter);
-        // Fall Through...
+        break;
+
+    case QD_AMQP_TRUE:
+        result = 1;
+        break;
 
+    case QD_AMQP_FALSE:
+    case QD_AMQP_UINT0:
     case QD_AMQP_ULONG0:
+        // already zeroed
+        break;
+
+    case QD_AMQP_STR8_UTF8:
+    case QD_AMQP_STR32_UTF8:
+    case QD_AMQP_SYM8:
+    case QD_AMQP_SYM32:
+        {
+            char buf[72];
+            unsigned long tmp;
+            qd_iterator_strncpy(field->raw_iter, buf, sizeof(buf));
+            if (sscanf(buf, "%lu", &tmp) == 1)
+                result = tmp;
+        }
         break;
+
+    default:
+        // catch any missing types during development
+        assert(false);
     }
 
     return result;
@@ -418,32 +435,9 @@ uint64_t qd_parse_as_ulong(qd_parsed_field_t *field)
 int32_t qd_parse_as_int(qd_parsed_field_t *field)
 {
     int32_t result = 0;
-
-    qd_iterator_reset(field->raw_iter);
-
-    switch (field->tag) {
-    case QD_AMQP_INT:
-        result |= ((int32_t) qd_iterator_octet(field->raw_iter)) << 24;
-        result |= ((int32_t) qd_iterator_octet(field->raw_iter)) << 16;
-        // Fall Through...
-
-    case QD_AMQP_SHORT:
-        result |= ((int32_t) qd_iterator_octet(field->raw_iter)) << 8;
-        // Fall Through...
-
-    case QD_AMQP_BYTE:
-    case QD_AMQP_BOOLEAN:
-        result |= (int32_t) qd_iterator_octet(field->raw_iter);
-        break;
-
-    case QD_AMQP_SMALLINT:
-        result = (int8_t) qd_iterator_octet(field->raw_iter);
-        break;
-
-    case QD_AMQP_TRUE:
-        result = 1;
-        break;
-    }
+    int64_t tmp = qd_parse_as_long(field);
+    if (INT_MIN <= tmp && tmp <= INT_MAX)
+        result = tmp;
 
     return result;
 }
@@ -467,9 +461,56 @@ int64_t qd_parse_as_long(qd_parsed_field_t *field)
         result |= (uint64_t) qd_iterator_octet(field->raw_iter);
         break;
 
+    case QD_AMQP_INT:
+        {
+            int32_t i32 = ((int32_t) qd_iterator_octet(field->raw_iter)) << 24;
+            i32 |= ((int32_t) qd_iterator_octet(field->raw_iter)) << 16;
+            i32 |= ((int32_t) qd_iterator_octet(field->raw_iter)) << 8;
+            i32 |= ((int32_t) qd_iterator_octet(field->raw_iter));
+            result = i32;
+        }
+        break;
+
+    case QD_AMQP_SHORT:
+        {
+            int16_t i16 = ((int16_t) qd_iterator_octet(field->raw_iter)) << 8;
+            i16 |= ((int16_t) qd_iterator_octet(field->raw_iter));
+            result = i16;
+        } break;
+
+    case QD_AMQP_BYTE:
+    case QD_AMQP_BOOLEAN:
     case QD_AMQP_SMALLLONG:
+    case QD_AMQP_SMALLINT:
         result = (int8_t) qd_iterator_octet(field->raw_iter);
         break;
+
+    case QD_AMQP_TRUE:
+        result = 1;
+        break;
+
+    case QD_AMQP_FALSE:
+    case QD_AMQP_UINT0:
+    case QD_AMQP_ULONG0:
+        // already zeroed
+        break;
+
+    case QD_AMQP_STR8_UTF8:
+    case QD_AMQP_STR32_UTF8:
+    case QD_AMQP_SYM8:
+    case QD_AMQP_SYM32:
+        {
+            char buf[64];
+            long int tmp;
+            qd_iterator_strncpy(field->raw_iter, buf, sizeof(buf));
+            if (sscanf(buf, "%li", &tmp) == 1)
+                result = tmp;
+        }
+        break;
+
+    default:
+        // catch any missing types during development
+        assert(false);
     }
 
     return result;

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/src/policy.c
----------------------------------------------------------------------
diff --git a/src/policy.c b/src/policy.c
index a7e31cf..35f3fb8 100644
--- a/src/policy.c
+++ b/src/policy.c
@@ -17,7 +17,6 @@
  * under the License.
  */
 
-#include <Python.h>
 #include "qpid/dispatch/python_embedded.h"
 #include "policy.h"
 #include "policy_internal.h"
@@ -33,6 +32,7 @@
 #include <proton/transport.h>
 #include <proton/error.h>
 #include <proton/event.h>
+#include "python_private.h"
 
 
 //
@@ -312,6 +312,7 @@ bool qd_policy_open_lookup_user(
 {
     // Lookup the user/host/vhost for allow/deny and to get settings name
     bool res = false;
+    name_buf[0] = 0;
     qd_python_lock_state_t lock_state = qd_python_lock();
     PyObject *module = PyImport_ImportModule("qpid_dispatch_internal.policy.policy_manager");
     if (module) {
@@ -321,10 +322,17 @@ bool qd_policy_open_lookup_user(
                                                      (PyObject *)policy->py_policy_manager,
                                                      username, hostip, vhost, conn_name, conn_id);
             if (result) {
-                const char *res_string = PyString_AsString(result);
-                strncpy(name_buf, res_string, name_buf_size);
+                char *res_string = py_obj_2_c_string(result);
+                const size_t res_len = res_string ? strlen(res_string) : 0;
+                if (res_len < name_buf_size) {
+                    strcpy(name_buf, res_string);
+                } else {
+                    qd_log(policy->log_source, QD_LOG_ERROR,
+                           "Internal: lookup_user: insufficient buffer for name");
+                }
                 Py_XDECREF(result);
-                res = true; // settings name returned
+                free(res_string);
+                res = !!name_buf[0]; // settings name returned
             } else {
                 qd_log(policy->log_source, QD_LOG_DEBUG, "Internal: lookup_user: result");
             }
@@ -503,40 +511,25 @@ void _qd_policy_deny_amqp_receiver_link(pn_link_t *pn_link, qd_connection_t *qd_
 //
 #define MIN(a,b) (((a)<(b))?(a):(b))
 
+// substitute "${user}" in place of uname in proposed
 char * _qd_policy_link_user_name_subst(const char *uname, const char *proposed, char *obuf, int osize)
 {
     if (strlen(uname) == 0)
         return NULL;
 
-    const char *duser = "${user}";
-    char *retptr = obuf;
-    const char *wiptr = proposed;
     const char *findptr = strstr(proposed, uname);
     if (findptr == NULL) {
         return NULL;
     }
 
-    // Copy leading before match
-    int segsize = findptr - wiptr;
-    int copysize = MIN(osize, segsize);
-    if (copysize)
-        strncpy(obuf, wiptr, copysize);
-    wiptr += copysize;
-    osize -= copysize;
-    obuf  += copysize;
-
-    // Copy the substitution string
-    segsize = strlen(duser);
-    copysize = MIN(osize, segsize);
-    if (copysize)
-        strncpy(obuf, duser, copysize);
-    wiptr += strlen(uname);
-    osize -= copysize;
-    obuf  += copysize;
-
-    // Copy trailing after match
-    strncpy(obuf, wiptr, osize);
-    return retptr;
+    // Copy leading before match and trailing after
+    int segsize = findptr - proposed;
+    const char *suffix = findptr + strlen(uname);
+    int rc = snprintf(obuf, osize,
+                      "%.*s${user}%s",
+                      segsize, proposed,
+                      suffix);
+    return (rc < osize) ? obuf : NULL;
 }
 
 
@@ -565,15 +558,16 @@ bool _qd_policy_approve_link_name(const char *username, const char *allowed, con
 
     // Create a temporary writable copy of incoming allowed list
     char t_allow[QPALN_SIZE + 1]; // temporary buffer for normal allow lists
+    int buflen = sizeof(t_allow);
     char * pa = t_allow;
-    if (a_len > QPALN_SIZE) {
-        pa = (char *)malloc(a_len + 1); // malloc a buffer for larger allow lists
+    if (a_len >= buflen) {
+        buflen = a_len + 1;
+        pa = (char *)malloc(buflen); // malloc a buffer for larger allow lists
+        if (!pa)
+            return false;
     }
-    if (!pa)
-        return false;
+    strcpy(pa, allowed);
 
-    strncpy(pa, allowed, a_len);
-    pa[a_len] = 0;
     // Do reverse user substitution into proposed
     char substbuf[QPALN_USERBUFSIZE];
     char * prop2 = _qd_policy_link_user_name_subst(username, proposed, substbuf, QPALN_USERBUFSIZE);

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/src/python_embedded.c
----------------------------------------------------------------------
diff --git a/src/python_embedded.c b/src/python_embedded.c
index eafd486..027f280 100644
--- a/src/python_embedded.c
+++ b/src/python_embedded.c
@@ -18,6 +18,7 @@
  */
 
 #include "entity_cache.h"
+#include "python_private.h"
 #include <qpid/dispatch/python_embedded.h>
 #include <qpid/dispatch/threading.h>
 #include <qpid/dispatch/log.h>
@@ -51,7 +52,7 @@ void qd_python_initialize(qd_dispatch_t *qd, const char *python_pkgdir)
     dispatch = qd;
     ilock = sys_mutex();
     if (python_pkgdir)
-        dispatch_python_pkgdir = PyString_FromString(python_pkgdir);
+        dispatch_python_pkgdir = PyUnicode_FromString(python_pkgdir);
 
     qd_python_lock_state_t ls = qd_python_lock();
     Py_Initialize();
@@ -89,7 +90,8 @@ void qd_python_check_lock(void)
 
 static PyObject *parsed_to_py_string(qd_parsed_field_t *field)
 {
-    switch (qd_parse_tag(field)) {
+    uint8_t tag = qd_parse_tag(field);
+    switch (tag) {
       case QD_AMQP_VBIN8:
       case QD_AMQP_VBIN32:
       case QD_AMQP_STR8_UTF8:
@@ -103,7 +105,7 @@ static PyObject *parsed_to_py_string(qd_parsed_field_t *field)
 
 #define SHORT_BUF 1024
     uint8_t short_buf[SHORT_BUF];
-    PyObject *result;
+    PyObject *result = NULL;
     qd_iterator_t *raw = qd_parse_raw(field);
     qd_iterator_reset(raw);
     uint32_t length = qd_iterator_remaining(raw);
@@ -119,10 +121,37 @@ static PyObject *parsed_to_py_string(qd_parsed_field_t *field)
     ptr = buffer;
     while (!qd_iterator_end(raw))
         *(ptr++) = qd_iterator_octet(raw);
-    result = PyString_FromStringAndSize((char*) buffer, ptr - buffer);
+
+    switch (tag) {
+      case QD_AMQP_VBIN8:
+      case QD_AMQP_VBIN32:
+          result = PyBytes_FromStringAndSize((char *)buffer,
+                                             ptr - buffer);
+          break;
+
+      case QD_AMQP_STR8_UTF8:
+      case QD_AMQP_STR32_UTF8:
+          // UTF-8 decoding
+          result = PyUnicode_FromStringAndSize((char *)buffer,
+                                               ptr - buffer);
+          break;
+
+      case QD_AMQP_SYM8:
+      case QD_AMQP_SYM32:
+          // ascii
+          result = PyUnicode_DecodeASCII((char *)buffer,
+                                         ptr - buffer, NULL);
+          break;
+    }
+
     if (alloc)
         free(buffer);
 
+    if (!result)
+        qd_log(log_source, QD_LOG_DEBUG,
+               "Cannot convert field type 0x%X to python string object",
+               tag);
+
     return result;
 }
 
@@ -135,17 +164,43 @@ qd_error_t qd_py_to_composed(PyObject *value, qd_composed_field_t *field)
         qd_compose_insert_null(field);
     }
     else if (PyBool_Check(value)) {
-        qd_compose_insert_bool(field, PyInt_AS_LONG(value) ? 1 : 0);
+        qd_compose_insert_bool(field, PyLong_AS_LONG(value) ? 1 : 0);
     }
-    else if (PyInt_Check(value)) {
-        // We are now sure that the value is an int
-        qd_compose_insert_int(field, (int32_t) PyInt_AS_LONG(value));
+    else if (QD_PY_INT_CHECK(value)) {
+        // We are now sure that the value is an integer type
+        int64_t ival = QD_PY_INT_2_INT64(value);
+        if (INT32_MIN <= ival && ival <= INT32_MAX) {
+            qd_compose_insert_int(field, (int32_t) ival);
+        } else {
+            qd_compose_insert_long(field, ival);
+        }
     }
-    else if (PyLong_Check(value)) {
-        qd_compose_insert_long(field, (int64_t) PyLong_AsLongLong(value));
+    else if (PyUnicode_Check(value)) {
+        char *data = py_string_2_c(value);
+        if (data) {
+            qd_compose_insert_string(field, data);
+            free(data);
+        } else {
+            qd_log(log_source, QD_LOG_ERROR,
+                   "Unable to convert python unicode object");
+        }
     }
-    else if (PyString_Check(value) || PyUnicode_Check(value)) {
-        qd_compose_insert_string(field, PyString_AsString(value));
+    else if (PyBytes_Check(value)) {
+        // Note: In python 2.X PyBytes is simply an alias for the PyString
+        // type. In python 3.x PyBytes is a distinct type (may contain zeros),
+        // and all strings are PyUnicode types.  Historically
+        // this code has just assumed this data is always a null terminated
+        // UTF8 string. We continue that tradition for Python2, but ending up
+        // here in Python3 means this is actually binary data which may have
+        // embedded zeros.
+        if (PY_MAJOR_VERSION <= 2) {
+            qd_compose_insert_string(field, PyBytes_AsString(value));
+        } else {
+            ssize_t len = 0;
+            char *data = NULL;
+            PyBytes_AsStringAndSize(value, &data, &len);
+            qd_compose_insert_binary(field, (uint8_t *)data, len);
+        }
     }
     else if (PyDict_Check(value)) {
         Py_ssize_t  iter = 0;
@@ -191,10 +246,15 @@ qd_error_t qd_py_to_composed(PyObject *value, qd_composed_field_t *field)
         PyObject *type=0, *typestr=0, *repr=0;
         if ((type = PyObject_Type(value)) &&
             (typestr = PyObject_Str(type)) &&
-            (repr = PyObject_Repr(value)))
+            (repr = PyObject_Repr(value))) {
+            char *t_str = py_string_2_c(typestr);
+            char *r_str = py_string_2_c(repr);
             qd_error(QD_ERROR_TYPE, "Can't compose object of type %s: %s",
-                     PyString_AsString(typestr), PyString_AsString(repr));
-        else
+                     t_str ? t_str : "Unknown",
+                     r_str ? r_str : "Unknown");
+            free(t_str);
+            free(r_str);
+        } else
             qd_error(QD_ERROR_TYPE, "Can't compose python object of unknown type");
 
         Py_XDECREF(type);
@@ -239,7 +299,7 @@ PyObject *qd_field_to_py(qd_parsed_field_t *field)
       case QD_AMQP_UINT:
       case QD_AMQP_SMALLUINT:
       case QD_AMQP_UINT0:
-        result = PyInt_FromLong((long) qd_parse_as_uint(field));
+        result = PyLong_FromLong((long) qd_parse_as_uint(field));
         break;
 
       case QD_AMQP_ULONG:
@@ -253,7 +313,7 @@ PyObject *qd_field_to_py(qd_parsed_field_t *field)
       case QD_AMQP_SHORT:
       case QD_AMQP_INT:
       case QD_AMQP_SMALLINT:
-        result = PyInt_FromLong((long) qd_parse_as_int(field));
+        result = PyLong_FromLong((long) qd_parse_as_int(field));
         break;
 
       case QD_AMQP_LONG:
@@ -337,7 +397,7 @@ static int LogAdapter_init(LogAdapter *self, PyObject *args, PyObject *kwds)
     if (!PyArg_ParseTuple(args, "s", &text))
         return -1;
 
-    self->module_name = PyString_FromString(text);
+    self->module_name = PyUnicode_FromString(text);
     self->log_source  = qd_log_source(text);
     return 0;
 }
@@ -346,7 +406,7 @@ static int LogAdapter_init(LogAdapter *self, PyObject *args, PyObject *kwds)
 static void LogAdapter_dealloc(LogAdapter* self)
 {
     Py_XDECREF(self->module_name);
-    self->ob_type->tp_free((PyObject*)self);
+    Py_TYPE(self)->tp_free((PyObject*)self);
 }
 
 
@@ -376,54 +436,14 @@ static PyMethodDef LogAdapter_methods[] = {
 };
 
 static PyTypeObject LogAdapterType = {
-    PyObject_HEAD_INIT(0)
-    0,                         /* ob_size*/
-    DISPATCH_MODULE ".LogAdapter",  /* tp_name*/
-    sizeof(LogAdapter),        /* tp_basicsize*/
-    0,                         /* tp_itemsize*/
-    (destructor)LogAdapter_dealloc, /* tp_dealloc*/
-    0,                         /* tp_print*/
-    0,                         /* tp_getattr*/
-    0,                         /* tp_setattr*/
-    0,                         /* tp_compare*/
-    0,                         /* tp_repr*/
-    0,                         /* tp_as_number*/
-    0,                         /* tp_as_sequence*/
-    0,                         /* tp_as_mapping*/
-    0,                         /* tp_hash */
-    0,                         /* tp_call*/
-    0,                         /* tp_str*/
-    0,                         /* tp_getattro*/
-    0,                         /* tp_setattro*/
-    0,                         /* tp_as_buffer*/
-    Py_TPFLAGS_DEFAULT,        /* tp_flags*/
-    "Dispatch Log Adapter",    /* tp_doc */
-    0,                         /* tp_traverse */
-    0,                         /* tp_clear */
-    0,                         /* tp_richcompare */
-    0,                         /* tp_weaklistoffset */
-    0,                         /* tp_iter */
-    0,                         /* tp_iternext */
-    LogAdapter_methods,        /* tp_methods */
-    0,                         /* tp_members */
-    0,                         /* tp_getset */
-    0,                         /* tp_base */
-    0,                         /* tp_dict */
-    0,                         /* tp_descr_get */
-    0,                         /* tp_descr_set */
-    0,                         /* tp_dictoffset */
-    (initproc)LogAdapter_init, /* tp_init */
-    0,                         /* tp_alloc */
-    0,                         /* tp_new */
-    0,                         /* tp_free */
-    0,                         /* tp_is_gc */
-    0,                         /* tp_bases */
-    0,                         /* tp_mro */
-    0,                         /* tp_cache */
-    0,                         /* tp_subclasses */
-    0,                         /* tp_weaklist */
-    0,                         /* tp_del */
-    0                          /* tp_version_tag */
+    PyVarObject_HEAD_INIT(NULL, 0)
+    .tp_name      = DISPATCH_MODULE ".LogAdapter",
+    .tp_doc       = "Dispatch Log Adapter",
+    .tp_basicsize = sizeof(LogAdapter),
+    .tp_dealloc   = (destructor)LogAdapter_dealloc,
+    .tp_flags     = Py_TPFLAGS_DEFAULT,
+    .tp_methods   = LogAdapter_methods,
+    .tp_init      = (initproc)LogAdapter_init
 };
 
 
@@ -463,7 +483,7 @@ static PyObject *py_iter_copy(qd_iterator_t *iter)
 {
     unsigned char *bytes = 0;
     PyObject *value = 0;
-    (void)(iter && (bytes = qd_iterator_copy(iter)) && (value = PyString_FromString((char*)bytes)));
+    (void)(iter && (bytes = qd_iterator_copy(iter)) && (value = PyUnicode_FromString((char*)bytes)));
     if (bytes) free(bytes);
     return value;
 }
@@ -529,8 +549,27 @@ static int IoAdapter_init(IoAdapter *self, PyObject *args, PyObject *kwds)
     char aclass    = 'L';
     char phase     = '0';
     int  treatment = QD_TREATMENT_ANYCAST_CLOSEST;
-    if (!PyArg_ParseTuple(args, "OO|cci", &self->handler, &addr, &aclass, &phase, &treatment))
-        return -1;
+    if (PY_MAJOR_VERSION == 2) {
+        if (!PyArg_ParseTuple(args, "OO|cci", &self->handler, &addr, &aclass, &phase, &treatment))
+            return -1;
+    } else {
+        // In Python3 all string text is unicode.  Therefore the ParseTuple format
+        // no longer allows use of a char byte for extracted characters since a
+        // single character may be up to 4 bytes in length.  Since class and
+        // phase can only be ascii we can simply downcast the returned value
+        // (being careful we do not overflow a single character).
+        unsigned int i_aclass = (int) aclass;
+        unsigned int i_phase = (int) phase;
+        if (!PyArg_ParseTuple(args, "OO|CCi", &self->handler, &addr, &i_aclass, &i_phase, &treatment))
+            return -1;
+        if (i_aclass > 0x7F || i_phase > 0x7F) {
+            PyErr_SetString(PyExc_TypeError, "Address class or phase not a single alpha character");
+            return -1;
+        }
+        aclass = (char) i_aclass;
+        phase = (char) i_phase;
+    }
+
     if (!PyCallable_Check(self->handler)) {
         PyErr_SetString(PyExc_TypeError, "IoAdapter.__init__ handler is not callable");
         return -1;
@@ -542,10 +581,11 @@ static int IoAdapter_init(IoAdapter *self, PyObject *args, PyObject *kwds)
     Py_INCREF(self->handler);
     self->qd   = dispatch;
     self->core = qd_router_core(self->qd);
-    const char *address = PyString_AsString(addr);
+    char *address = py_string_2_c(addr);
     if (!address) return -1;
     qd_error_clear();
     self->sub = qdr_core_subscribe(self->core, address, aclass, phase, treatment, qd_io_rx_handler, self);
+    free(address);
     if (qd_error_code()) {
         PyErr_SetString(PyExc_RuntimeError, qd_error_message());
         return -1;
@@ -557,7 +597,7 @@ static void IoAdapter_dealloc(IoAdapter* self)
 {
     qdr_core_unsubscribe(self->sub);
     Py_DECREF(self->handler);
-    self->ob_type->tp_free((PyObject*)self);
+    Py_TYPE(self)->tp_free((PyObject*)self);
 }
 
 static qd_error_t compose_python_message(qd_composed_field_t **field, PyObject *message,
@@ -618,7 +658,14 @@ static PyObject *qd_python_send(PyObject *self, PyObject *args)
 
         PyObject *address = PyObject_GetAttrString(message, "address");
         if (address) {
-            qdr_send_to2(ioa->core, msg, PyString_AsString(address), (bool) no_echo, (bool) control);
+            char *a_str = py_obj_2_c_string(address);
+            if (a_str) {
+                qdr_send_to2(ioa->core, msg, a_str, (bool) no_echo, (bool) control);
+                free(a_str);
+            } else {
+                qd_log(log_source, QD_LOG_ERROR,
+                       "Unable to convert message address to C string");
+            }
             Py_DECREF(address);
         }
         qd_compose_free(field);
@@ -638,54 +685,14 @@ static PyMethodDef IoAdapter_methods[] = {
 
 
 static PyTypeObject IoAdapterType = {
-    PyObject_HEAD_INIT(0)
-    0,                         /* ob_size*/
-    DISPATCH_MODULE ".IoAdapter",  /* tp_name*/
-    sizeof(IoAdapter),         /* tp_basicsize*/
-    0,                         /* tp_itemsize*/
-    (destructor)IoAdapter_dealloc, /* tp_dealloc*/
-    0,                         /* tp_print*/
-    0,                         /* tp_getattr*/
-    0,                         /* tp_setattr*/
-    0,                         /* tp_compare*/
-    0,                         /* tp_repr*/
-    0,                         /* tp_as_number*/
-    0,                         /* tp_as_sequence*/
-    0,                         /* tp_as_mapping*/
-    0,                         /* tp_hash */
-    0,                         /* tp_call*/
-    0,                         /* tp_str*/
-    0,                         /* tp_getattro*/
-    0,                         /* tp_setattro*/
-    0,                         /* tp_as_buffer*/
-    Py_TPFLAGS_DEFAULT,        /* tp_flags*/
-    "Dispatch IO Adapter",     /* tp_doc */
-    0,                         /* tp_traverse */
-    0,                         /* tp_clear */
-    0,                         /* tp_richcompare */
-    0,                         /* tp_weaklistoffset */
-    0,                         /* tp_iter */
-    0,                         /* tp_iternext */
-    IoAdapter_methods,         /* tp_methods */
-    0,                         /* tp_members */
-    0,                         /* tp_getset */
-    0,                         /* tp_base */
-    0,                         /* tp_dict */
-    0,                         /* tp_descr_get */
-    0,                         /* tp_descr_set */
-    0,                         /* tp_dictoffset */
-    (initproc)IoAdapter_init,  /* tp_init */
-    0,                         /* tp_alloc */
-    0,                         /* tp_new */
-    0,                         /* tp_free */
-    0,                         /* tp_is_gc */
-    0,                         /* tp_bases */
-    0,                         /* tp_mro */
-    0,                         /* tp_cache */
-    0,                         /* tp_subclasses */
-    0,                         /* tp_weaklist */
-    0,                         /* tp_del */
-    0                          /* tp_version_tag */
+    PyVarObject_HEAD_INIT(NULL, 0)
+    .tp_name      = DISPATCH_MODULE ".IoAdapter",
+    .tp_doc       = "Dispatch IO Adapter",
+    .tp_basicsize = sizeof(IoAdapter),
+    .tp_dealloc   = (destructor)IoAdapter_dealloc,
+    .tp_flags     = Py_TPFLAGS_DEFAULT,
+    .tp_methods   = IoAdapter_methods,
+    .tp_init      = (initproc)IoAdapter_init,
 };
 
 
@@ -695,7 +702,7 @@ static PyTypeObject IoAdapterType = {
 
 static void qd_register_constant(PyObject *module, const char *name, uint32_t value)
 {
-    PyObject *const_object = PyInt_FromLong((long) value);
+    PyObject *const_object = PyLong_FromLong((long) value);
     Py_INCREF(const_object);
     PyModule_AddObject(module, name, const_object);
 }

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/src/python_private.h
----------------------------------------------------------------------
diff --git a/src/python_private.h b/src/python_private.h
new file mode 100644
index 0000000..ec85505
--- /dev/null
+++ b/src/python_private.h
@@ -0,0 +1,46 @@
+#ifndef __python_internal_h__
+#define __python_internal_h__ 1
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#include <stdint.h>
+#include <Python.h>
+
+#if PY_MAJOR_VERSION <= 2
+// deal with the two integer types in Python2
+#define QD_PY_INT_CHECK(PO) (PyInt_Check(PO) || PyLong_Check(PO))
+#define QD_PY_INT_2_INT64(PO) (PyLong_Check(PO) ? \
+                               (int64_t) PyLong_AsLongLong(PO) : \
+                               (int64_t) PyInt_AS_LONG(PO))
+#else  // Python3
+#define QD_PY_INT_CHECK(PO) (PyLong_Check(PO))
+#define QD_PY_INT_2_INT64(PO) ((int64_t)PyLong_AsLongLong(PO))
+#endif
+
+// Convert a Python string type to a C string.  The resulting string may be
+// UTF-8 encoded.  Caller must free returned string buffer.  Returns NULL on
+// failure
+char *py_string_2_c(PyObject *py_str);
+
+// Convert the string representation of an arbitrary Python type object to a
+// null terminated C string.  Equivalent to calling 'str(o)' in Python.  The
+// resulting string may be UTF-8 encoded. Caller must free the returned string
+// buffer.
+char *py_obj_2_c_string(PyObject *py_obj);
+
+#endif

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/src/python_utils.c
----------------------------------------------------------------------
diff --git a/src/python_utils.c b/src/python_utils.c
new file mode 100644
index 0000000..170e259
--- /dev/null
+++ b/src/python_utils.c
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#include "python_private.h"
+
+
+// Convert a Python string type object to a C null terminated string.  Caller
+// must free the returned string buffer.  Returns NULL if python object is not
+// a string-ish type to start with (i.e. expects string type, error if not)
+char *py_string_2_c(PyObject *py_str)
+{
+    char *str = NULL;
+    if (!py_str) return NULL;
+
+    if (PyUnicode_Check(py_str)) {
+        // python 3 str OR python 2 unicode type
+        PyObject *ref = PyUnicode_AsUTF8String(py_str);
+        if (ref) {
+            // now a bytes object
+            str = strdup(PyBytes_AS_STRING(ref));
+            Py_DECREF(ref);
+        }
+    } else if (PyBytes_Check(py_str)) {
+        // python 2 str
+        str = strdup(PyBytes_AS_STRING(py_str));
+    }
+    return str;
+}
+
+// Convert the string representation of an arbitrary Python type object to a
+// null terminated C string.  Equivalent to calling 'str(o)' in Python.  Caller
+// must free the returned string buffer.
+char *py_obj_2_c_string(PyObject *py_obj)
+{
+    char *str = NULL;
+    PyObject *tmp = NULL;
+
+    if (!py_obj) return NULL;
+
+    // first convert to a python string object
+    if (PyUnicode_Check(py_obj) || PyBytes_Check(py_obj)) {
+        // A python string type - no need to call str(py_obj)
+        tmp = py_obj;
+        Py_INCREF(tmp);  // for decref below
+    } else {
+        // create a new object via str(py_obj);
+        tmp = PyObject_Str(py_obj);
+    }
+    str = py_string_2_c(tmp);
+    Py_XDECREF(tmp);
+    return str;
+}
+

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/src/router_core/agent_config_address.c
----------------------------------------------------------------------
diff --git a/src/router_core/agent_config_address.c b/src/router_core/agent_config_address.c
index 68a2280..b4f0f77 100644
--- a/src/router_core/agent_config_address.c
+++ b/src/router_core/agent_config_address.c
@@ -394,8 +394,8 @@ void qdra_config_address_create_CT(qdr_core_t         *core,
 
 
         bool waypoint  = waypoint_field  ? qd_parse_as_bool(waypoint_field) : false;
-        int  in_phase  = in_phase_field  ? qd_parse_as_int(in_phase_field)  : -1;
-        int  out_phase = out_phase_field ? qd_parse_as_int(out_phase_field) : -1;
+        long in_phase  = in_phase_field  ? qd_parse_as_long(in_phase_field)  : -1;
+        long out_phase = out_phase_field ? qd_parse_as_long(out_phase_field) : -1;
 
         //
         // Handle the address-phasing logic.  If the phases are provided, use them.  Otherwise

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/src/router_core/agent_config_auto_link.c
----------------------------------------------------------------------
diff --git a/src/router_core/agent_config_auto_link.c b/src/router_core/agent_config_auto_link.c
index 20d7bbf..b0f7fec 100644
--- a/src/router_core/agent_config_auto_link.c
+++ b/src/router_core/agent_config_auto_link.c
@@ -413,7 +413,7 @@ void qdra_config_auto_link_create_CT(qdr_core_t        *core,
         // Use the specified phase if present.  Otherwise default based on the direction:
         // Phase 0 for outgoing links and phase 1 for incoming links.
         //
-        int phase = phase_field ? qd_parse_as_int(phase_field) : (dir == QD_OUTGOING ? 0 : 1);
+        long phase = phase_field ? qd_parse_as_long(phase_field) : (dir == QD_OUTGOING ? 0 : 1);
 
         //
         // Validate the phase

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/src/router_core/agent_connection.c
----------------------------------------------------------------------
diff --git a/src/router_core/agent_connection.c b/src/router_core/agent_connection.c
index 810cbae..32da4c6 100644
--- a/src/router_core/agent_connection.c
+++ b/src/router_core/agent_connection.c
@@ -86,6 +86,9 @@ static void qd_get_next_pn_data(pn_data_t **data, const char **d, int *d1)
             case PN_INT:
                 *d1 = pn_data_get_int(*data);
                 break;
+            case PN_LONG:
+                *d1 = pn_data_get_long(*data);
+                break;
             default:
                 break;
         }

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/src/router_core/exchange_bindings.c
----------------------------------------------------------------------
diff --git a/src/router_core/exchange_bindings.c b/src/router_core/exchange_bindings.c
index d03f795..215c68a 100644
--- a/src/router_core/exchange_bindings.c
+++ b/src/router_core/exchange_bindings.c
@@ -469,11 +469,11 @@ void qdra_config_exchange_create_CT(qdr_core_t         *core,
         }
     }
 
-    int phase = 0;
+    long phase = 0;
     qd_parsed_field_t *phase_field = qd_parse_value_by_key(in_body,
                                                            qdr_config_exchange_columns[QDR_CONFIG_EXCHANGE_PHASE]);
     if (phase_field) {
-        phase = qd_parse_as_int(phase_field);
+        phase = qd_parse_as_long(phase_field);
         if (phase < 0 || phase > 9) {
             query->status.description = "phase must be in the range 0-9";
             goto exit;
@@ -481,7 +481,7 @@ void qdra_config_exchange_create_CT(qdr_core_t         *core,
     }
 
     qd_iterator_t *alternate = NULL;
-    int alt_phase = 0;
+    long alt_phase = 0;
     qd_parsed_field_t *alternate_field = qd_parse_value_by_key(in_body,
                                                                qdr_config_exchange_columns[QDR_CONFIG_EXCHANGE_ALTERNATE]);
     if (alternate_field) {
@@ -489,7 +489,7 @@ void qdra_config_exchange_create_CT(qdr_core_t         *core,
         qd_parsed_field_t *alt_phase_field = qd_parse_value_by_key(in_body,
                                                                    qdr_config_exchange_columns[QDR_CONFIG_EXCHANGE_ALT_PHASE]);
         if (alt_phase_field) {
-            alt_phase = qd_parse_as_int(alt_phase_field);
+            alt_phase = qd_parse_as_long(alt_phase_field);
             if (alt_phase < 0 || alt_phase > 9) {
                 query->status.description = "phase must be in the range 0-9";
                 goto exit;
@@ -725,7 +725,7 @@ void qdra_config_binding_create_CT(qdr_core_t         *core,
 
     qd_parsed_field_t *phase_field = qd_parse_value_by_key(in_body,
                                                          qdr_config_binding_columns[QDR_CONFIG_BINDING_NHOP_PHASE]);
-    int phase = (phase_field ? qd_parse_as_int(phase_field) : 0);
+    long phase = (phase_field ? qd_parse_as_long(phase_field) : 0);
     if (phase < 0 || phase > 9) {
         query->status.description = "phase must be in the range 0-9";
         goto exit;

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/src/router_core/management_agent.c
----------------------------------------------------------------------
diff --git a/src/router_core/management_agent.c b/src/router_core/management_agent.c
index 60b6ee1..82e56d0 100644
--- a/src/router_core/management_agent.c
+++ b/src/router_core/management_agent.c
@@ -465,13 +465,13 @@ static bool qd_can_handle_request(qd_parsed_field_t           *properties_fld,
     // Obtain the count and offset.
     parsed_field = qd_parse_value_by_key(properties_fld, COUNT);
     if (parsed_field)
-        (*count) = qd_parse_as_int(parsed_field);
+        (*count) = (int)qd_parse_as_long(parsed_field);
     else
         (*count) = -1;
 
     parsed_field = qd_parse_value_by_key(properties_fld, OFFSET);
     if (parsed_field)
-        (*offset) = qd_parse_as_int(parsed_field);
+        (*offset) = (int)qd_parse_as_long(parsed_field);
     else
         (*offset) = 0;
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/src/router_pynode.c
----------------------------------------------------------------------
diff --git a/src/router_pynode.c b/src/router_pynode.c
index a791973..1d64cfc 100644
--- a/src/router_pynode.c
+++ b/src/router_pynode.c
@@ -26,6 +26,7 @@
 #include "dispatch_private.h"
 #include "router_private.h"
 #include "entity_cache.h"
+#include "python_private.h"
 
 static qd_log_source_t *log_source = 0;
 static PyObject        *pyRouter   = 0;
@@ -188,7 +189,9 @@ static PyObject* qd_set_valid_origins(PyObject *self, PyObject *args)
         int           maskbit;
 
         for (idx = 0; idx < origin_count; idx++) {
-            maskbit = PyInt_AS_LONG(PyList_GetItem(origin_list, idx));
+            PyObject *pi = PyList_GetItem(origin_list, idx);
+            assert(QD_PY_INT_CHECK(pi));
+            maskbit = (int)QD_PY_INT_2_INT64(pi);
             if (maskbit >= qd_bitmask_width() || maskbit < 0) {
                 error = "Origin bit mask out of range";
                 break;
@@ -198,7 +201,9 @@ static PyObject* qd_set_valid_origins(PyObject *self, PyObject *args)
         if (error == 0) {
             qd_bitmask_set_bit(core_bitmask, 0);  // This router is a valid origin for all destinations
             for (idx = 0; idx < origin_count; idx++) {
-                maskbit = PyInt_AS_LONG(PyList_GetItem(origin_list, idx));
+                PyObject *pi = PyList_GetItem(origin_list, idx);
+                assert(QD_PY_INT_CHECK(pi));
+                maskbit = (int)QD_PY_INT_2_INT64(pi);
                 qd_bitmask_set_bit(core_bitmask, maskbit);
             }
         } else {
@@ -302,54 +307,12 @@ static PyMethodDef RouterAdapter_methods[] = {
 };
 
 static PyTypeObject RouterAdapterType = {
-    PyObject_HEAD_INIT(0)
-    0,                         /* ob_size*/
-    "dispatch.RouterAdapter",  /* tp_name*/
-    sizeof(RouterAdapter),     /* tp_basicsize*/
-    0,                         /* tp_itemsize*/
-    0,                         /* tp_dealloc*/
-    0,                         /* tp_print*/
-    0,                         /* tp_getattr*/
-    0,                         /* tp_setattr*/
-    0,                         /* tp_compare*/
-    0,                         /* tp_repr*/
-    0,                         /* tp_as_number*/
-    0,                         /* tp_as_sequence*/
-    0,                         /* tp_as_mapping*/
-    0,                         /* tp_hash */
-    0,                         /* tp_call*/
-    0,                         /* tp_str*/
-    0,                         /* tp_getattro*/
-    0,                         /* tp_setattro*/
-    0,                         /* tp_as_buffer*/
-    Py_TPFLAGS_DEFAULT,        /* tp_flags*/
-    "Dispatch Router Adapter", /* tp_doc */
-    0,                         /* tp_traverse */
-    0,                         /* tp_clear */
-    0,                         /* tp_richcompare */
-    0,                         /* tp_weaklistoffset */
-    0,                         /* tp_iter */
-    0,                         /* tp_iternext */
-    RouterAdapter_methods,     /* tp_methods */
-    0,                         /* tp_members */
-    0,                         /* tp_getset */
-    0,                         /* tp_base */
-    0,                         /* tp_dict */
-    0,                         /* tp_descr_get */
-    0,                         /* tp_descr_set */
-    0,                         /* tp_dictoffset */
-    0,                         /* tp_init */
-    0,                         /* tp_alloc */
-    0,                         /* tp_new */
-    0,                         /* tp_free */
-    0,                         /* tp_is_gc */
-    0,                         /* tp_bases */
-    0,                         /* tp_mro */
-    0,                         /* tp_cache */
-    0,                         /* tp_subclasses */
-    0,                         /* tp_weaklist */
-    0,                         /* tp_del */
-    0                          /* tp_version_tag */
+    PyVarObject_HEAD_INIT(NULL, 0)
+    .tp_name = "dispatch.RouterAdapter",  /* tp_name*/
+    .tp_basicsize = sizeof(RouterAdapter),     /* tp_basicsize*/
+    .tp_flags = Py_TPFLAGS_DEFAULT,        /* tp_flags*/
+    .tp_doc = "Dispatch Router Adapter", /* tp_doc */
+    .tp_methods = RouterAdapter_methods,     /* tp_methods */
 };
 
 
@@ -362,7 +325,7 @@ static void qd_router_mobile_added(void *context, const char *address_hash)
     if (pyAdded && router->router_mode == QD_ROUTER_MODE_INTERIOR) {
         qd_python_lock_state_t lock_state = qd_python_lock();
         pArgs = PyTuple_New(1);
-        PyTuple_SetItem(pArgs, 0, PyString_FromString(address_hash));
+        PyTuple_SetItem(pArgs, 0, PyUnicode_FromString(address_hash));
         pValue = PyObject_CallObject(pyAdded, pArgs);
         qd_error_py();
         Py_DECREF(pArgs);
@@ -381,7 +344,7 @@ static void qd_router_mobile_removed(void *context, const char *address_hash)
     if (pyRemoved && router->router_mode == QD_ROUTER_MODE_INTERIOR) {
         qd_python_lock_state_t lock_state = qd_python_lock();
         pArgs = PyTuple_New(1);
-        PyTuple_SetItem(pArgs, 0, PyString_FromString(address_hash));
+        PyTuple_SetItem(pArgs, 0, PyUnicode_FromString(address_hash));
         pValue = PyObject_CallObject(pyRemoved, pArgs);
         qd_error_py();
         Py_DECREF(pArgs);
@@ -400,7 +363,7 @@ static void qd_router_link_lost(void *context, int link_mask_bit)
     if (pyRemoved && router->router_mode == QD_ROUTER_MODE_INTERIOR) {
         qd_python_lock_state_t lock_state = qd_python_lock();
         pArgs = PyTuple_New(1);
-        PyTuple_SetItem(pArgs, 0, PyInt_FromLong((long) link_mask_bit));
+        PyTuple_SetItem(pArgs, 0, PyLong_FromLong((long) link_mask_bit));
         pValue = PyObject_CallObject(pyLinkLost, pArgs);
         qd_error_py();
         Py_DECREF(pArgs);
@@ -466,21 +429,21 @@ qd_error_t qd_router_python_setup(qd_router_t *router)
     PyTuple_SetItem(pArgs, 0, adapterInstance);
 
     // arg 1: router_id
-    pId = PyString_FromString(router->router_id);
+    pId = PyUnicode_FromString(router->router_id);
     PyTuple_SetItem(pArgs, 1, pId);
 
     // arg 2: area_id
-    pArea = PyString_FromString(router->router_area);
+    pArea = PyUnicode_FromString(router->router_area);
     PyTuple_SetItem(pArgs, 2, pArea);
 
     // arg 3: max_routers
-    pMaxRouters = PyInt_FromLong((long) qd_bitmask_width());
+    pMaxRouters = PyLong_FromLong((long) qd_bitmask_width());
     PyTuple_SetItem(pArgs, 3, pMaxRouters);
 
     //
     // Instantiate the router
     //
-    pyRouter = PyInstance_New(pClass, pArgs, 0);
+    pyRouter = PyObject_CallObject(pClass, pArgs);
     Py_DECREF(pArgs);
     Py_DECREF(adapterType);
     QD_ERROR_PY_RET();

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/src/schema_c.py
----------------------------------------------------------------------
diff --git a/src/schema_c.py b/src/schema_c.py
index 80f6b3c..3c90b4d 100644
--- a/src/schema_c.py
+++ b/src/schema_c.py
@@ -97,8 +97,8 @@ class Generator(object):
 
     def generate_enums(self):
         enums = [self.EnumGenerator(self, entity, attribute)
-                 for entity in self.schema.entity_types.itervalues()
-                 for attribute in entity.attributes.itervalues()
+                 for entity in self.schema.entity_types.values()
+                 for attribute in entity.attributes.values()
                  if isinstance(attribute.atype, EnumType)]
         self.header('schema_enum', '\n'.join(e.decl() for e in enums))
         self.source('schema_enum', '#include "schema_enum.h"\n\n' + '\n'.join(e.defn() for e in enums))

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/src/server.c
----------------------------------------------------------------------
diff --git a/src/server.c b/src/server.c
index cb90510..64819d5 100644
--- a/src/server.c
+++ b/src/server.c
@@ -17,7 +17,6 @@
  * under the License.
  */
 
-#include <Python.h>
 #include <qpid/dispatch/ctools.h>
 #include <qpid/dispatch/threading.h>
 #include <qpid/dispatch/log.h>
@@ -41,6 +40,7 @@
 #include "timer_private.h"
 #include "config.h"
 #include "remote_sasl.h"
+#include "python_private.h"
 #include <stdio.h>
 #include <string.h>
 #include <errno.h>
@@ -302,11 +302,8 @@ static const char *transport_get_user(qd_connection_t *conn, pn_transport_t *tpo
                 qd_python_lock_state_t lock_state = qd_python_lock();
                 PyObject *result = PyObject_CallMethod((PyObject *)conn->server->py_displayname_obj, "query", "(ss)", config->ssl_profile, user_id );
                 if (result) {
-                    const char *res_string = PyString_AsString(result);
                     free(user_id);
-                    user_id = malloc(strlen(res_string) + 1);
-                    user_id[0] = '\0';
-                    strcat(user_id, res_string);
+                    user_id = py_string_2_c(result);
                     Py_XDECREF(result);
                 } else {
                     qd_log(conn->server->log_source, QD_LOG_DEBUG, "Internal: failed to read displaynameservice query result");

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index ee4e080..11bf33c 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -116,6 +116,29 @@ foreach(py_test_module
   list(APPEND SYSTEM_TEST_FILES ${CMAKE_CURRENT_SOURCE_DIR}/${py_test_module}.py)
 endforeach()
 
+# Use tox to run the flake8 python linter tool on all the python
+# sources. Highly recommended if you're hacking the python code
+#
+find_program(TOX_EXE "tox")
+if (TOX_EXE)
+  add_test (NAME python-checker
+            COMMAND ${TOX_EXE}
+            WORKING_DIRECTORY ${CMAKE_SOURCE_DIR})
+  # Once we move to tox >= v1.7.2 we can remove the next
+  # line.  See tox.ini file for details
+  set_tests_properties(python-checker
+                       PROPERTIES
+                       PASS_REGULAR_EXPRESSION "commands succeeded"
+                       FAIL_REGULAR_EXPRESSION "commands failed")
+
+else (TOX_EXE)
+  message(STATUS "Could NOT find 'tox' tool - unable to validate python code")
+endif ()
+
+
+
+
+
 # Additional files to install for running system tests.
 # NOTE: Don't install run.py. A system test of a dispatch installation should pick everything
 # up from standard install locations.

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/management/__init__.py
----------------------------------------------------------------------
diff --git a/tests/management/__init__.py b/tests/management/__init__.py
index 41ecb77..3bfcbce 100644
--- a/tests/management/__init__.py
+++ b/tests/management/__init__.py
@@ -18,7 +18,6 @@
 ##
 
 """Management unit test package"""
-
-from schema import *
-from qdrouter import *
-from entity import *
+from .schema import *
+from .qdrouter import *
+from .entity import *

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/mock/dispatch.py
----------------------------------------------------------------------
diff --git a/tests/mock/dispatch.py b/tests/mock/dispatch.py
index dd08f7d..5a34e43 100644
--- a/tests/mock/dispatch.py
+++ b/tests/mock/dispatch.py
@@ -19,6 +19,7 @@
 """
 Mock implementation of the dispatch C extension module for use in unit tests.
 """
+from __future__ import print_function
 
 LOG_TRACE    = 1
 LOG_DEBUG    = 2
@@ -41,7 +42,7 @@ class LogAdapter:
     self.mod_name = mod_name
 
   def log(self, level, text):
-    print "LOG: mod=%s level=%d text=%s" % (self.mod_name, level, text)
+    print("LOG: mod=%s level=%d text=%s" % (self.mod_name, level, text))
 
 class IoAdapter:
   def __init__(self, handler, address, global_address=False):
@@ -50,4 +51,5 @@ class IoAdapter:
     self.global_address = global_address
 
   def send(self, address, properties, application_properties, body, correlation_id=None):
-    print "IO: send(addr=%s properties=%r application_properties=%r body=%r" % (address, properties, application_properties, body)
+    print("IO: send(addr=%s properties=%r application_properties=%r body=%r"
+          % (address, properties, application_properties, body))

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/router_engine_test.py
----------------------------------------------------------------------
diff --git a/tests/router_engine_test.py b/tests/router_engine_test.py
index 7193443..0442088 100644
--- a/tests/router_engine_test.py
+++ b/tests/router_engine_test.py
@@ -17,6 +17,8 @@
 # under the License.
 #
 
+from __future__ import print_function
+
 import os
 import sys
 import unittest2 as unittest
@@ -34,20 +36,20 @@ class Adapter(object):
         self._domain = domain
 
     def log(self, level, text):
-        print "Adapter.log(%d): domain=%s, text=%s" % (level, self._domain, text)
+        print("Adapter.log(%d): domain=%s, text=%s" % (level, self._domain, text))
 
     def send(self, dest, opcode, body):
-        print "Adapter.send: domain=%s, dest=%s, opcode=%s, body=%s" % (self._domain, dest, opcode, body)
+        print("Adapter.send: domain=%s, dest=%s, opcode=%s, body=%s" % (self._domain, dest, opcode, body))
 
     def remote_bind(self, subject, peer):
-        print "Adapter.remote_bind: subject=%s, peer=%s" % (subject, peer)
+        print("Adapter.remote_bind: subject=%s, peer=%s" % (subject, peer))
 
     def remote_unbind(self, subject, peer):
-        print "Adapter.remote_unbind: subject=%s, peer=%s" % (subject, peer)
+        print("Adapter.remote_unbind: subject=%s, peer=%s" % (subject, peer))
 
     def node_updated(self, address, reachable, neighbor, link_bit, router_bit):
-        print "Adapter.node_updated: address=%s, reachable=%r, neighbor=%r, link_bit=%d, router_bit=%d" % \
-            (address, reachable, neighbor, link_bit, router_bit)
+        print("Adapter.node_updated: address=%s, reachable=%r, neighbor=%r, link_bit=%d, router_bit=%d" % \
+              (address, reachable, neighbor, link_bit, router_bit))
 
 
 class DataTest(unittest.TestCase):
@@ -189,7 +191,7 @@ class NeighborTest(unittest.TestCase):
         self.engine.tick(2.0)
         self.engine.tick(3.0)
         self.assertEqual(len(self.neighbors), 1)
-        self.assertEqual(self.neighbors.keys(), ['R2'])
+        self.assertEqual(list(self.neighbors.keys()), ['R2'])
 
     def test_establish_multiple_peers(self):
         self.sent = []
@@ -203,7 +205,7 @@ class NeighborTest(unittest.TestCase):
         self.engine.handle_hello(MessageHELLO(None, 'R5', ['R2']), 2.5, 0, 1)
         self.engine.handle_hello(MessageHELLO(None, 'R6', ['R1']), 2.5, 0, 1)
         self.engine.tick(3.0)
-        keys = self.neighbors.keys()
+        keys = [k for k in self.neighbors.keys()]
         keys.sort()
         self.assertEqual(keys, ['R2', 'R3', 'R4', 'R6'])
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/router_policy_test.py
----------------------------------------------------------------------
diff --git a/tests/router_policy_test.py b/tests/router_policy_test.py
index 42b78ab..3421250 100644
--- a/tests/router_policy_test.py
+++ b/tests/router_policy_test.py
@@ -17,6 +17,8 @@
 # under the License.
 #
 
+from __future__ import print_function
+
 import unittest2 as unittest
 
 from qpid_dispatch_internal.policy.policy_util import HostAddr, is_ipv6_enabled

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_test.py
----------------------------------------------------------------------
diff --git a/tests/system_test.py b/tests/system_test.py
index d8baed7..0ff97da 100755
--- a/tests/system_test.py
+++ b/tests/system_test.py
@@ -27,6 +27,7 @@ Features:
 - Tools to manipulate qdrouter configuration files.
 - Sundry other tools.
 """
+from __future__ import print_function
 
 import errno, os, time, socket, random, subprocess, shutil, unittest, __main__, re, sys
 from copy import copy
@@ -40,19 +41,20 @@ import proton
 from proton import Message, Timeout
 from proton.utils import BlockingConnection
 from qpid_dispatch.management.client import Node
+from qpid_dispatch_internal.compat import dict_iteritems
 
 # Optional modules
 MISSING_MODULES = []
 
 try:
     import qpidtoollibs
-except ImportError, err:
+except ImportError as err:
     qpidtoollibs = None         # pylint: disable=invalid-name
     MISSING_MODULES.append(str(err))
 
 try:
     import qpid_messaging as qm
-except ImportError, err:
+except ImportError as err:
     qm = None                   # pylint: disable=invalid-name
     MISSING_MODULES.append(str(err))
 
@@ -126,7 +128,7 @@ def retry_exception(function, timeout=TIMEOUT, delay=.001, max_delay=1, exceptio
     while True:
         try:
             return function()
-        except Exception, e:    # pylint: disable=broad-except
+        except Exception as e:    # pylint: disable=broad-except
             if exception_test:
                 exception_test(e)
             delay = retry_delay(deadline, delay, max_delay)
@@ -150,7 +152,7 @@ def port_available(port, protocol_family='IPv4'):
     try:
         s.connect((host, port))
         s.close()
-    except socket.error, e:
+    except socket.error as e:
         return e.errno == errno.ECONNREFUSED
     except:
         pass
@@ -167,7 +169,7 @@ def wait_port(port, protocol_family='IPv4', **retry_kwargs):
     try:
         retry_exception(lambda: s.connect((host, port)), exception_test=check,
                         **retry_kwargs)
-    except Exception, e:
+    except Exception as e:
         raise Exception("wait_port timeout on host %s port %s: %s"%(host, port, e))
 
     finally: s.close()
@@ -175,13 +177,13 @@ def wait_port(port, protocol_family='IPv4', **retry_kwargs):
 def wait_ports(ports, **retry_kwargs):
     """Wait up to timeout for all ports (on host) to be connectable.
     Takes same keyword arguments as retry to control the timeout"""
-    for port, protocol_family in ports.iteritems():
+    for port, protocol_family in dict_iteritems(ports):
         wait_port(port=port, protocol_family=protocol_family, **retry_kwargs)
 
 def message(**properties):
     """Convenience to create a proton.Message with properties set"""
     m = Message()
-    for name, value in properties.iteritems():
+    for name, value in dict_iteritems(properties):
         getattr(m, name)        # Raise exception if not a valid message attribute.
         setattr(m, name, value)
     return m
@@ -227,7 +229,7 @@ class Process(subprocess.Popen):
                 super(Process, self).__init__(args, **kwargs)
                 with open(self.outfile + '.cmd', 'w') as f:
                     f.write("%s\npid=%s\n" % (' '.join(args), self.pid))
-            except Exception, e:
+            except Exception as e:
                 raise Exception("subprocess.Popen(%s, %s) failed: %s: %s" %
                                 (args, kwargs, type(e).__name__, e))
 
@@ -297,13 +299,13 @@ class Qdrouterd(Process):
             """Fill in default values in gconfiguration"""
             for name, props in self:
                 if name in Qdrouterd.Config.DEFAULTS:
-                    for n,p in Qdrouterd.Config.DEFAULTS[name].iteritems():
+                    for n,p in dict_iteritems(Qdrouterd.Config.DEFAULTS[name]):
                         props.setdefault(n,p)
 
         def __str__(self):
             """Generate config file content. Calls default() first."""
             def props(p):
-                return "".join(["    %s: %s\n"%(k, v) for k, v in p.iteritems()])
+                return "".join(["    %s: %s\n"%(k, v) for k, v in dict_iteritems(p)])
             self.defaults()
             return "".join(["%s {\n%s}\n"%(n, props(p)) for n, p in self])
 
@@ -523,8 +525,8 @@ class Tester(object):
                     if cleanup:
                         cleanup()
                         break
-            except Exception, e:
-                errors.append(e)
+            except Exception as exc:
+                errors.append(exc)
         if errors:
             raise RuntimeError("Errors during teardown: \n\n%s" % "\n\n".join([str(e) for e in errors]))
 
@@ -543,14 +545,6 @@ class Tester(object):
         """Return a Qdrouterd that will be cleaned up on teardown"""
         return self.cleanup(Qdrouterd(*args, **kwargs))
 
-    def messenger(self, name=None, cleanup=True, **kwargs):
-        """Return a started Messenger that will be cleaned up on teardown."""
-        m = Messenger(name or os.path.basename(self.directory), **kwargs)
-        m.start()
-        if cleanup:
-            self.cleanup(m)
-        return m
-
     port_range = (20000, 30000)
     next_port = random.randint(port_range[0], port_range[1])
 
@@ -621,7 +615,7 @@ class TestCase(unittest.TestCase, Tester): # pylint: disable=too-many-public-met
         if hasattr(unittest.TestCase, 'skipTest'):
             unittest.TestCase.skipTest(self, reason)
         else:
-            print "Skipping test", self.id(), reason
+            print("Skipping test %s: %s" % (self.id(), reason))
 
     # Hack to support tearDownClass on older versions of python.
     # The default TestLoader sorts tests alphabetically so we insert
@@ -678,7 +672,7 @@ class SkipIfNeeded(object):
             instance = args[0]
             if isinstance(instance, TestCase) and hasattr(instance, "skip") and instance.skip[self.test_name]:
                 if sys.version_info < (2, 7):
-                    print "%s -> skipping (python<2.7) ..." % self.test_name
+                    print("%s -> skipping (python<2.7) ..." % self.test_name)
                     return
                 else:
                     instance.skipTest(self.reason)

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_auth_service_plugin.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_auth_service_plugin.py b/tests/system_tests_auth_service_plugin.py
index f005766..013c87e 100644
--- a/tests/system_tests_auth_service_plugin.py
+++ b/tests/system_tests_auth_service_plugin.py
@@ -17,6 +17,8 @@
 # under the License.
 #
 
+from __future__ import print_function
+
 import unittest2 as unittest
 import os
 from subprocess import PIPE, Popen
@@ -31,7 +33,7 @@ class AuthServicePluginTest(TestCase):
     def createSaslFiles(cls):
         # Create a sasl database.
         p = Popen(['saslpasswd2', '-c', '-p', '-f', 'qdrouterd.sasldb', '-u', 'domain.com', 'test'],
-                  stdin=PIPE, stdout=PIPE, stderr=PIPE)
+                  stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True)
         result = p.communicate('password')
         assert p.returncode == 0, \
             "saslpasswd2 exit status %s, output:\n%s" % (p.returncode, result)

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_authz_service_plugin.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_authz_service_plugin.py b/tests/system_tests_authz_service_plugin.py
index 0dc839f..994079d 100644
--- a/tests/system_tests_authz_service_plugin.py
+++ b/tests/system_tests_authz_service_plugin.py
@@ -17,7 +17,7 @@
 # under the License.
 #
 
-import unittest2 as unitest
+import unittest2 as unittest
 import os, json
 from subprocess import PIPE, Popen, STDOUT
 from system_test import TestCase, Qdrouterd, main_module, DIR, TIMEOUT, Process
@@ -30,7 +30,7 @@ class AuthServicePluginAuthzTest(TestCase):
     def addUser(cls, user, password):
         # Create a sasl database.
         p = Popen(['saslpasswd2', '-c', '-p', '-f', 'users.sasldb', user],
-                  stdin=PIPE, stdout=PIPE, stderr=PIPE)
+                  stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True)
         result = p.communicate(password)
         assert p.returncode == 0, "saslpasswd2 exit status %s, output:\n%s" % (p.returncode, result)
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_autolinks.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_autolinks.py b/tests/system_tests_autolinks.py
index 16aeca4..952644b 100644
--- a/tests/system_tests_autolinks.py
+++ b/tests/system_tests_autolinks.py
@@ -97,7 +97,8 @@ class AutolinkTest(TestCase):
         cmd = ['qdstat', '--bus', str(AutolinkTest.normal_address), '--timeout', str(TIMEOUT)] + ['-g']
         p = self.popen(
             cmd,
-            name='qdstat-'+self.id(), stdout=PIPE, expect=None)
+            name='qdstat-'+self.id(), stdout=PIPE, expect=None,
+            universal_newlines=True)
 
         out = p.communicate()[0]
         assert p.returncode == 0, "qdstat exit status %s, output:\n%s" % (p.returncode, out)
@@ -106,11 +107,12 @@ class AutolinkTest(TestCase):
     def run_qdmanage(self, cmd, input=None, expect=Process.EXIT_OK):
         p = self.popen(
             ['qdmanage'] + cmd.split(' ') + ['--bus', AutolinkTest.normal_address, '--indent=-1', '--timeout', str(TIMEOUT)],
-            stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=expect)
+            stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=expect,
+            universal_newlines=True)
         out = p.communicate(input)[0]
         try:
             p.teardown()
-        except Exception, e:
+        except Exception as e:
             raise Exception("%s\n%s" % (e, out))
         return out
 
@@ -766,7 +768,7 @@ class ManageAutolinksTest(MessagingHandler):
             self.send_ops()
 
     def on_message(self, event):
-        if event.message.properties['statusCode'] / 100 != 2:
+        if event.message.properties['statusCode'] // 100 != 2:
             self.error = 'Op Error: %d %s' % (event.message.properties['statusCode'],
                                               event.message.properties['statusDescription'])
             self.timer.cancel()

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_bad_configuration.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_bad_configuration.py b/tests/system_tests_bad_configuration.py
index 1b9ecf0..8dd379d 100644
--- a/tests/system_tests_bad_configuration.py
+++ b/tests/system_tests_bad_configuration.py
@@ -141,10 +141,11 @@ class RouterTestBadConfiguration(TestCase):
         """
         p = self.popen(
             ['qdmanage', '-b', self.address(), 'query', '--type=router', '--timeout', str(TIMEOUT)],
-            stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=Process.EXIT_OK)
+            stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=Process.EXIT_OK,
+            universal_newlines=True)
         out = p.communicate()[0]
         try:
             p.teardown()
-        except Exception, e:
+        except Exception as e:
             raise Exception("%s\n%s" % (e, out))
         return out

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_broker.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_broker.py b/tests/system_tests_broker.py
index 3832bf0..bef3008 100644
--- a/tests/system_tests_broker.py
+++ b/tests/system_tests_broker.py
@@ -39,7 +39,7 @@ class DistributedQueueTest(system_test.TestCase): # pylint: disable=too-many-pub
             """Start 3 qpidd brokers, wait for them to be ready."""
             super(DistributedQueueTest, cls).setUpClass()
             cls.qpidds = [cls.tester.qpidd('qpidd%s'%i, port=cls.get_port(), wait=False)
-                        for i in xrange(3)]
+                        for i in range(3)]
             for q in cls.qpidds:
                 q.wait_ready()
 
@@ -98,7 +98,7 @@ class DistributedQueueTest(system_test.TestCase): # pylint: disable=too-many-pub
                     rconf += [
                         ('connector', {'name':q.name, 'port':q.port})]
                 return self.qdrouterd(name, rconf, wait=False)
-            routers = [router(i) for i in xrange(len(self.qpidds))]
+            routers = [router(i) for i in range(len(self.qpidds))]
             for r in routers: r.wait_ready()
             addrs = [r.addresses[0]+"/"+self.testq for r in routers]
             self.verify_equal_spread(addrs, addrs)

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_cmdline_parsing.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_cmdline_parsing.py b/tests/system_tests_cmdline_parsing.py
index e68e6be..75526fb 100644
--- a/tests/system_tests_cmdline_parsing.py
+++ b/tests/system_tests_cmdline_parsing.py
@@ -65,7 +65,8 @@ class CommandLineTest(TestCase):
             [os.path.join(os.environ.get('BUILD_DIR'), 'router', 'qdrouterd'), '-d',
              '-I', os.path.join(os.environ.get('SOURCE_DIR'), 'python'),
              '-c', self.config.write(config_file_name), '-P', pid_file_name],
-            stdout=PIPE, stderr=STDOUT, expect=Process.EXIT_OK)
+            stdout=PIPE, stderr=STDOUT, expect=Process.EXIT_OK,
+            universal_newlines=True)
         out = pipe.communicate()[0]
         wait_port(CommandLineTest.testport)
 
@@ -127,7 +128,8 @@ class CommandLineTest2(TestCase):
             [os.path.join(os.environ.get('BUILD_DIR'), 'router', 'qdrouterd'), '-d',
              '-I', os.path.join(os.environ.get('SOURCE_DIR'), 'python'),
              '-c', self.config.write(config_file_name), '-P', pid_file_name],
-            stdout=PIPE, stderr=STDOUT, expect=Process.EXIT_OK)
+            stdout=PIPE, stderr=STDOUT, expect=Process.EXIT_OK,
+            universal_newlines=True)
         out = pipe.communicate()[0]
         wait_port(CommandLineTest2.testport)
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_default_distribution.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_default_distribution.py b/tests/system_tests_default_distribution.py
index 8d318e4..2bb9b4d 100644
--- a/tests/system_tests_default_distribution.py
+++ b/tests/system_tests_default_distribution.py
@@ -48,7 +48,8 @@ class DefaultDistributionTest(TestCase):
     def run_qdstat(self, args, regexp=None, address=None):
         p = self.popen(
             ['qdstat', '--bus', str(address or self.address), '--timeout', str(TIMEOUT) ] + args,
-            name='qdstat-'+self.id(), stdout=PIPE, expect=None)
+            name='qdstat-'+self.id(), stdout=PIPE, expect=None,
+            universal_newlines=True)
 
         out = p.communicate()[0]
         assert p.returncode == 0, \

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_delivery_abort.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_delivery_abort.py b/tests/system_tests_delivery_abort.py
index fc60002..6051ebf 100644
--- a/tests/system_tests_delivery_abort.py
+++ b/tests/system_tests_delivery_abort.py
@@ -22,6 +22,7 @@ from proton import Message, Timeout
 from system_test import TestCase, Qdrouterd, main_module
 from proton.handlers import MessagingHandler
 from proton.reactor import Container
+from qpid_dispatch_internal.compat import BINARY
 
 # PROTON-828:
 try:
@@ -211,7 +212,7 @@ class MessageRouteTruncateTest(MessagingHandler):
         self.receiver      = event.container.create_receiver(self.receiver_conn, self.address)
 
     def stream(self):
-        self.sender1.stream(self.long_data)
+        self.sender1.stream(BINARY(self.long_data))
         self.sent_stream += len(self.long_data)
         if self.sent_stream >= 1000000:
             self.streaming = False
@@ -316,7 +317,7 @@ class LinkRouteTruncateTest(MessagingHandler):
         self.sender1 = event.container.create_sender(self.sender_conn, self.address, name="S1")
 
     def stream(self):
-        self.sender1.stream(self.long_data)
+        self.sender1.stream(BINARY(self.long_data))
         self.sent_stream += len(self.long_data)
         if self.sent_stream >= 1000000:
             self.streaming = False
@@ -434,7 +435,7 @@ class MessageRouteAbortTest(MessagingHandler):
         if op == 'F':
             body = "FINISH"
         else:
-            for i in range(size / 10):
+            for i in range(size // 10):
                 body += "0123456789"
         msg = Message(body=body)
         
@@ -522,7 +523,7 @@ class MulticastTruncateTest(MessagingHandler):
         self.receiver2      = event.container.create_receiver(self.receiver2_conn, self.address)
 
     def stream(self):
-        self.sender1.stream(self.long_data)
+        self.sender1.stream(BINARY(self.long_data))
         self.sent_stream += len(self.long_data)
         if self.sent_stream >= 1000000:
             self.streaming = False

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_deprecated.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_deprecated.py b/tests/system_tests_deprecated.py
index 818d12d..6809e94 100644
--- a/tests/system_tests_deprecated.py
+++ b/tests/system_tests_deprecated.py
@@ -53,7 +53,7 @@ class RouterTestDeprecatedLinkRoute(TestCase):
         with open('../setUpClass/test-router-2.out', 'r') as router_log:
             log_lines = router_log.read().split("\n")
             search_lines = [s for s in log_lines if "org.apache.qpid.dispatch.router.config.linkRoute: Both 'dir' and 'direction' cannot be specified for entity 'linkRoute'" in s]
-            self.assertEqual(len(search_lines), 4)
+            self.assertTrue(len(search_lines) > 0)
 
 
 class RouterTestDeprecatedLAutoLink(TestCase):
@@ -86,7 +86,7 @@ class RouterTestDeprecatedLAutoLink(TestCase):
             log_lines = router_log.read().split("\n")
             search_lines = [s for s in log_lines if
                             "org.apache.qpid.dispatch.router.config.autoLink: Both 'dir' and 'direction' cannot be specified for entity 'autoLink'" in s]
-            self.assertEqual(len(search_lines), 4)
+            self.assertTrue(len(search_lines) > 0)
 
 
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_disallow_link_resumable_link_route.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_disallow_link_resumable_link_route.py b/tests/system_tests_disallow_link_resumable_link_route.py
index bac12ff..05d2ae8 100644
--- a/tests/system_tests_disallow_link_resumable_link_route.py
+++ b/tests/system_tests_disallow_link_resumable_link_route.py
@@ -92,7 +92,8 @@ class LinkRouteTest(TestCase):
         try:
             receiver = connection.create_receiver(address="org.apache", options=[DurableSubscription()])
             self.fail("link should have been detached")
-        except LinkDetached, e: None
+        except LinkDetached:
+            pass
         connection.close()
 
     def test_normal_sender_allowed(self):
@@ -109,7 +110,8 @@ class LinkRouteTest(TestCase):
         try:
             sender = connection.create_sender(address="org.apache", options=[SenderExpiry(Terminus.EXPIRE_NEVER)])
             self.fail("link should have been detached")
-        except LinkDetached, e: None
+        except LinkDetached:
+            pass
         connection.close()
 
     def test_non_zero_timeout_sender_disallowed(self):
@@ -119,7 +121,8 @@ class LinkRouteTest(TestCase):
         try:
             sender = connection.create_sender(address="org.apache", options=[SenderTimeout(10)])
             self.fail("link should have been detached")
-        except LinkDetached, e: None
+        except LinkDetached:
+            pass
         connection.close()
 
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_distribution.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_distribution.py b/tests/system_tests_distribution.py
index d6ef781..b3484fd 100644
--- a/tests/system_tests_distribution.py
+++ b/tests/system_tests_distribution.py
@@ -17,6 +17,8 @@
 # under the License.
 #
 
+from __future__ import print_function
+
 import unittest2 as unittest
 from proton          import Message, Timeout
 from system_test     import TestCase, Qdrouterd, main_module, TIMEOUT, SkipIfNeeded
@@ -1978,7 +1980,7 @@ class LinkAttachRoutingCheckOnly ( MessagingHandler ):
 
     def debug_print ( self, message ) :
         if self.debug :
-            print message
+            print(message)
 
 
     def timeout ( self ):
@@ -2886,7 +2888,7 @@ class RoutingTest ( MessagingHandler ):
 
     def debug_print ( self, message ) :
         if self.debug :
-            print message
+            print(message)
 
 
     # If this happens, the test is hanging.
@@ -2950,13 +2952,13 @@ class RoutingTest ( MessagingHandler ):
         for router in range(len(self.where_to_make_connections)) :
             how_many_for_this_router = self.where_to_make_connections[router]
             for j in range(how_many_for_this_router) :
-              route_container_addr = self.route_container_addrs[router]
-              cnx = event.container.connect ( route_container_addr )
-              # In the dict of connections and actual receiver
-              # counts, store this cnx, and 0.
-              self.router_cnx_counts[router][cnx] = 0
-              self.cnx_status[cnx] = 1
-              self.debug_print ( "on_start: made cnx %s on router %d" % ( str(cnx), router ) )
+                route_container_addr = self.route_container_addrs[router]
+                cnx = event.container.connect ( route_container_addr )
+                # In the dict of connections and actual receiver
+                # counts, store this cnx, and 0.
+                self.router_cnx_counts[router][cnx] = 0
+                self.cnx_status[cnx] = 1
+                self.debug_print ( "on_start: made cnx %s on router %d" % ( str(cnx), router ) )
 
         # STEP 2 : Make a sender and receiver that we will use to tell when the router
         #          network is ready to handle our reoutable address. This sender will
@@ -3092,12 +3094,14 @@ class RoutingTest ( MessagingHandler ):
 
 
     def print_receiver_distribution ( self ) :
-        print "receiver distribution:"
+        print("receiver distribution:")
         for router in range(len(self.router_cnx_counts)) :
-            print "    router", router
+            print("    router %s" % router)
             cnx_dict = self.router_cnx_counts[router]
             for cnx in cnx_dict :
-                print "        cnx:", cnx, "receivers: " , cnx_dict[cnx]
+                print("        cnx: %s receivers: %s"
+                      % (cnx, cnx_dict[cnx]))
+
 
     def get_receiver_distribution ( self ) :
         threeple = ()
@@ -3232,7 +3236,7 @@ class RoutingTest ( MessagingHandler ):
     #=================================================
     def make_senders ( self, n ):
         self.debug_print ( "making %d senders" % n )
-        for i in xrange(n):
+        for i in range(n):
             sender = self.sender_container.create_sender ( self.sender_cnx,
                                                            self.link_routable_address,
                                                            name=link_name()
@@ -3400,7 +3404,7 @@ class WaypointTest ( MessagingHandler ):
 
     def debug_print ( self, message ) :
         if self.debug :
-            print message
+            print(message)
 
 
 
@@ -3644,7 +3648,7 @@ class SerialWaypointTest ( MessagingHandler ):
 
     def debug_print ( self, message ) :
         if self.debug :
-            print message
+            print(message)
 
 
     def send_from_client ( self, sender, n_messages, sender_index ):
@@ -3828,23 +3832,23 @@ class SerialWaypointTest ( MessagingHandler ):
 
 
     def report ( self ) :
-        print "\n\n==========================================================\nreport\n"
+        print("\n\n==========================================================\nreport\n")
 
         for i in range(len(self.senders)) :
-            print "    client sender %d sent %d messages." % ( i, self.senders[i]['n_sent'] )
+            print("    client sender %d sent %d messages." % ( i, self.senders[i]['n_sent']))
 
-        print "\n"
+        print("\n")
 
         for i in range(len(self.waypoints)) :
-            print "    waypoint %d received %d messages." % ( i, self.waypoints[i]['n_received'] )
-            print "    waypoint %d sent     %d messages." % ( i, self.waypoints[i]['n_sent'] )
+            print("    waypoint %d received %d messages." % ( i, self.waypoints[i]['n_received']))
+            print("    waypoint %d sent     %d messages." % ( i, self.waypoints[i]['n_sent']))
 
-        print "\n"
+        print("\n")
 
         for i in range(len(self.receivers)) :
-            print "    client receiver %d received %d messages." % ( i, self.receivers[i]['n_received'] )
+            print("    client receiver %d received %d messages." % ( i, self.receivers[i]['n_received'] ))
 
-        print "\nend report\n=========================================================\n\n"
+        print("\nend report\n=========================================================\n\n")
 
 
 
@@ -3959,7 +3963,7 @@ class ParallelWaypointTest ( MessagingHandler ):
 
     def debug_print ( self, message ) :
         if self.debug :
-            print message
+            print(message)
 
 
     def send_from_client ( self, sender, n_messages, sender_index ):
@@ -4148,23 +4152,23 @@ class ParallelWaypointTest ( MessagingHandler ):
 
 
     def report ( self ) :
-        print "\n\n==========================================================\nreport\n"
+        print("\n\n==========================================================\nreport\n")
 
         for i in range(len(self.senders)) :
-            print "    client sender %d sent %d messages." % ( i, self.senders[i]['n_sent'] )
+            print("    client sender %d sent %d messages." % ( i, self.senders[i]['n_sent'] ))
 
-        print "\n"
+        print("\n")
 
         for i in range(len(self.waypoints)) :
-            print "    waypoint %d received %d messages." % ( i, self.waypoints[i]['n_received'] )
-            print "    waypoint %d sent     %d messages." % ( i, self.waypoints[i]['n_sent'] )
+            print("    waypoint %d received %d messages." % ( i, self.waypoints[i]['n_received'] ))
+            print("    waypoint %d sent     %d messages." % ( i, self.waypoints[i]['n_sent'] ))
 
-        print "\n"
+        print("\n")
 
         for i in range(len(self.receivers)) :
-            print "    client receiver %d received %d messages." % ( i, self.receivers[i]['n_received'] )
+            print( "    client receiver %d received %d messages." % ( i, self.receivers[i]['n_received'] ))
 
-        print "\nend report\n=========================================================\n\n"
+        print("\nend report\n=========================================================\n\n")
 
 
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_exchange_bindings.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_exchange_bindings.py b/tests/system_tests_exchange_bindings.py
index e03f36a..1449f77 100644
--- a/tests/system_tests_exchange_bindings.py
+++ b/tests/system_tests_exchange_bindings.py
@@ -51,11 +51,12 @@ class ExchangeBindingsTest(TestCase):
         p = self.popen(
             ['qdmanage'] + cmd.split(' ')
             + ['--bus', router.addresses[0], '--indent=-1', '--timeout', str(TIMEOUT)],
-            stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=expect)
+            stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=expect,
+            universal_newlines=True)
         out = p.communicate(input)[0]
         try:
             p.teardown()
-        except Exception, e:
+        except Exception as e:
             raise Exception("%s\n%s" % (e, out))
         return out
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/tests/system_tests_handle_failover.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_handle_failover.py b/tests/system_tests_handle_failover.py
index f8c70e9..dcd9893 100644
--- a/tests/system_tests_handle_failover.py
+++ b/tests/system_tests_handle_failover.py
@@ -94,18 +94,20 @@ class FailoverTest(TestCase):
     def run_qdmanage(self, cmd, input=None, expect=Process.EXIT_OK, address=None):
         p = self.popen(
             ['qdmanage'] + cmd.split(' ') + ['--bus', address or self.address(), '--indent=-1', '--timeout', str(TIMEOUT)],
-            stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=expect)
+            stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=expect,
+            universal_newlines=True)
         out = p.communicate(input)[0]
         try:
             p.teardown()
-        except Exception, e:
+        except Exception as e:
             raise Exception("%s\n%s" % (e, out))
         return out
 
     def run_qdstat(self, args, regexp=None, address=None):
         p = self.popen(
             ['qdstat', '--bus', str(address or self.router.addresses[0]), '--timeout', str(TIMEOUT) ] + args,
-            name='qdstat-'+self.id(), stdout=PIPE, expect=None)
+            name='qdstat-'+self.id(), stdout=PIPE, expect=None,
+            universal_newlines=True)
 
         out = p.communicate()[0]
         assert p.returncode == 0, \
@@ -175,4 +177,4 @@ class FailoverTest(TestCase):
 
 
 if __name__ == '__main__':
-    unittest.main(main_module())
\ No newline at end of file
+    unittest.main(main_module())


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org


[08/11] qpid-dispatch git commit: DISPATCH-965: fix relative import (thanks ernie)

Posted by kg...@apache.org.
DISPATCH-965: fix relative import (thanks ernie)


Project: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/repo
Commit: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/commit/72939380
Tree: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/tree/72939380
Diff: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/diff/72939380

Branch: refs/heads/master
Commit: 729393808835dd6cc087b9878eda1be93d834320
Parents: 9d3cecf
Author: Kenneth Giusti <kg...@apache.org>
Authored: Wed May 16 17:11:58 2018 -0400
Committer: Kenneth Giusti <kg...@apache.org>
Committed: Wed May 16 17:11:58 2018 -0400

----------------------------------------------------------------------
 console/config/mock/section.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/72939380/console/config/mock/section.py
----------------------------------------------------------------------
diff --git a/console/config/mock/section.py b/console/config/mock/section.py
index 1e563be..eabc2b4 100644
--- a/console/config/mock/section.py
+++ b/console/config/mock/section.py
@@ -24,7 +24,7 @@ from __future__ import absolute_import
 
 import json
 import re
-from schema import Schema
+from .schema import Schema
 import pdb
 
 class ConfigSection(object):


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org


[03/11] qpid-dispatch git commit: DISPATCH-965: port python code to Python 3. Stay compatible with 2.6-7

Posted by kg...@apache.org.
DISPATCH-965: port python code to Python 3. Stay compatible with 2.6-7


Project: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/repo
Commit: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/commit/878534ec
Tree: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/tree/878534ec
Diff: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/diff/878534ec

Branch: refs/heads/master
Commit: 878534ec682b13cc731197318c8e6f32f06d6216
Parents: 4bd79a3
Author: Kenneth Giusti <kg...@redhat.com>
Authored: Wed Apr 11 17:24:23 2018 -0400
Committer: Kenneth Giusti <kg...@redhat.com>
Committed: Thu May 10 02:39:02 2018 -0400

----------------------------------------------------------------------
 .gitignore                                      |   1 +
 console/config/config.py                        |  34 +--
 console/config/mock/section.py                  |  10 +-
 doc/man/help2txt.py                             |  12 +-
 doc/man/qdrouterd.conf.5.py                     |   6 +-
 python/qpid_dispatch/management/entity.py       |  40 ++-
 .../qpid_dispatch_internal/compat/__init__.py   | 102 +++++++-
 .../compat/ordereddict.py                       |   6 +-
 python/qpid_dispatch_internal/dispatch.py       |  15 +-
 .../qpid_dispatch_internal/management/agent.py  |  69 +++--
 .../qpid_dispatch_internal/management/config.py |  15 +-
 .../management/qdrouter.py                      |   4 +-
 .../qpid_dispatch_internal/management/schema.py |  73 +++---
 .../management/schema_doc.py                    |  11 +-
 .../policy/policy_local.py                      |  50 ++--
 .../policy/policy_manager.py                    |   3 +-
 .../policy/policy_util.py                       |   6 +-
 .../qpid_dispatch_internal/router/__init__.py   |   2 +-
 python/qpid_dispatch_internal/router/data.py    |  53 ++--
 python/qpid_dispatch_internal/router/engine.py  |  24 +-
 python/qpid_dispatch_internal/router/hello.py   |  11 +-
 python/qpid_dispatch_internal/router/link.py    |   2 +-
 python/qpid_dispatch_internal/router/mobile.py  |   2 +-
 python/qpid_dispatch_internal/router/node.py    |  30 ++-
 python/qpid_dispatch_internal/router/path.py    |  14 +-
 python/qpid_dispatch_internal/tools/command.py  |  11 +-
 python/qpid_dispatch_internal/tools/display.py  |  32 +--
 run.py.in                                       |  13 +-
 src/CMakeLists.txt                              |   1 +
 src/entity.c                                    |  29 +--
 src/error.c                                     |  46 ++--
 src/log.c                                       |  11 +-
 src/parse.c                                     | 141 +++++++----
 src/policy.c                                    |  62 +++--
 src/python_embedded.c                           | 251 ++++++++++---------
 src/python_private.h                            |  46 ++++
 src/python_utils.c                              |  68 +++++
 src/router_core/agent_config_address.c          |   4 +-
 src/router_core/agent_config_auto_link.c        |   2 +-
 src/router_core/agent_connection.c              |   3 +
 src/router_core/exchange_bindings.c             |  10 +-
 src/router_core/management_agent.c              |   4 +-
 src/router_pynode.c                             |  77 ++----
 src/schema_c.py                                 |   4 +-
 src/server.c                                    |   7 +-
 tests/CMakeLists.txt                            |  23 ++
 tests/management/__init__.py                    |   7 +-
 tests/mock/dispatch.py                          |   6 +-
 tests/router_engine_test.py                     |  18 +-
 tests/router_policy_test.py                     |   2 +
 tests/system_test.py                            |  38 ++-
 tests/system_tests_auth_service_plugin.py       |   4 +-
 tests/system_tests_authz_service_plugin.py      |   4 +-
 tests/system_tests_autolinks.py                 |  10 +-
 tests/system_tests_bad_configuration.py         |   5 +-
 tests/system_tests_broker.py                    |   4 +-
 tests/system_tests_cmdline_parsing.py           |   6 +-
 tests/system_tests_default_distribution.py      |   3 +-
 tests/system_tests_delivery_abort.py            |   9 +-
 tests/system_tests_deprecated.py                |   4 +-
 ..._tests_disallow_link_resumable_link_route.py |   9 +-
 tests/system_tests_distribution.py              |  68 ++---
 tests/system_tests_exchange_bindings.py         |   5 +-
 tests/system_tests_handle_failover.py           |  10 +-
 tests/system_tests_http.py                      |   2 +-
 tests/system_tests_link_routes.py               |  16 +-
 tests/system_tests_log_message_components.py    |  10 +-
 tests/system_tests_management.py                |  12 +-
 tests/system_tests_multi_tenancy.py             |   4 +-
 tests/system_tests_one_router.py                |  26 +-
 tests/system_tests_policy.py                    |  40 +--
 tests/system_tests_protocol_settings.py         |   3 +-
 tests/system_tests_qdmanage.py                  |  15 +-
 tests/system_tests_qdstat.py                    |  22 +-
 tests/system_tests_sasl_plain.py                |  14 +-
 tests/system_tests_topology.py                  |   3 +-
 tests/system_tests_topology_addition.py         |  12 +-
 tests/system_tests_topology_disposition.py      |  49 ++--
 tests/system_tests_user_id_proxy.py             |   5 +-
 tools/qdmanage                                  |  18 +-
 tools/qdstat                                    |  11 +-
 tox.ini                                         |  33 +++
 82 files changed, 1178 insertions(+), 769 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/.gitignore
----------------------------------------------------------------------
diff --git a/.gitignore b/.gitignore
index b4164bb..52d844c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -13,3 +13,4 @@ tests/policy-1/policy-*.json
 .settings
 console/test/topolgies/config-*
 .history
+.tox

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/console/config/config.py
----------------------------------------------------------------------
diff --git a/console/config/config.py b/console/config/config.py
index f83057e..ae51bd7 100755
--- a/console/config/config.py
+++ b/console/config/config.py
@@ -34,6 +34,11 @@ import threading
 import subprocess
 from distutils.spawn import find_executable
 
+# Python 3 does not have a unicode() builtin method
+if sys.version_info[0] > 2:
+    def unicode(x, encoding='utf-8', errors=None):
+        return str(x, encoding, errors)
+
 get_class = lambda x: globals()[x]
 sectionKeys = {"log": "module", "sslProfile": "name", "connector": "port", "listener": "port", "address": "prefix|pattern"}
 
@@ -87,7 +92,7 @@ class DirectoryConfigs(object):
         try:
             c = get_class(cname)
             return c(**s[1])
-        except KeyError, e:
+        except KeyError:
             return None
 
 class Manager(object):
@@ -104,15 +109,15 @@ class Manager(object):
         try:
             method = getattr(self, m)
         except AttributeError:
-            print op + " is not implemented yet"
+            print(op + " is not implemented yet")
             return None
         if self.verbose:
-            print "Got request " + op
+            print("Got request " + op)
         return method(request)
 
     def ANSIBLE_INSTALLED(self, request):
         if self.verbose:
-            print "Ansible is", "installed" if find_executable("ansible") else "not installed"
+            print("Ansible is %s" % "installed" if find_executable("ansible") else "not installed")
         return "installed" if find_executable("ansible") else ""
 
     # if the node has listeners, and one of them has an http:'true'
@@ -176,7 +181,7 @@ class Manager(object):
         def ansible_done(returncode):
             os.remove(inventory_file)
             if self.verbose:
-                print "-------------- DEPLOYMENT DONE with return code", returncode, "------------"
+                print("-------------- DEPLOYMENT DONE with return code", returncode, "------------")
             if returncode:
                 self.state = returncode
             else:
@@ -261,7 +266,7 @@ class Manager(object):
 
     def GET_TOPOLOGY(self, request):
         if self.verbose:
-            pprint (self.topology)
+            pprint(self.topology)
         return unicode(self.topology)
 
     def GET_TOPOLOGY_LIST(self, request):
@@ -327,7 +332,7 @@ class Manager(object):
             # remove all .conf files from the output dir. they will be recreated below possibly under new names
             for f in glob(self.topo_base + topology + "/*.conf"):
                 if self.verbose:
-                    print "Removing", f
+                    print("Removing %s" % f)
                 os.remove(f)
 
         # establish connections and listeners for each node based on links
@@ -337,7 +342,8 @@ class Manager(object):
         for node in nodes:
             if node['nodeType'] == 'inter-router':
                 if self.verbose:
-                    print "------------- processing node", node["name"], "---------------"
+                    print("------------- processing node %s "
+                          "---------------" % node["name"])
 
                 nname = node["name"]
                 if nodeIndex is not None:
@@ -360,14 +366,14 @@ class Manager(object):
                 for sectionKey in sectionKeys:
                     if sectionKey+'s' in node:
                         if self.verbose:
-                            print "found", sectionKey+'s'
+                            print("found %s" % sectionKey+'s')
                         for k in node[sectionKey+'s']:
                             if self.verbose:
-                                print "processing", k
+                                print("processing %s" % k)
                             o = node[sectionKey+'s'][k]
                             cname = sectionKey[0].upper() + sectionKey[1:] + "Section"
                             if self.verbose:
-                                print "class name is", cname
+                                print("class name is %s" % cname)
                             c = get_class(cname)
                             if sectionKey == "listener" and o['port'] != 'amqp' and int(o['port']) == http_port:
                                 config_fp.write("\n# Listener for a console\n")
@@ -376,7 +382,7 @@ class Manager(object):
                             if node.get('host') == o.get('host'):
                                 o['host'] = '0.0.0.0'
                             if self.verbose:
-                                print "attributes", o, "is written as", str(c(**o))
+                                print("attributes %s is written as %s" % (o, str(c(**o))))
                             config_fp.write(str(c(**o)) + "\n")
 
                 if 'listener' in node:
@@ -450,7 +456,7 @@ args = parser.parse_args()
 
 try:
     httpd = ConfigTCPServer(args.port, Manager(args.topology, args.verbose), args.verbose)
-    print "serving at port", args.port
+    print("serving at port %s" % args.port)
     httpd.serve_forever()
 except KeyboardInterrupt:
-    pass
\ No newline at end of file
+    pass

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/console/config/mock/section.py
----------------------------------------------------------------------
diff --git a/console/config/mock/section.py b/console/config/mock/section.py
index ce71d7c..ac5b154 100644
--- a/console/config/mock/section.py
+++ b/console/config/mock/section.py
@@ -103,9 +103,9 @@ if __name__ == '__main__':
     c = ConnectorSection(20001)
     s = SslProfileSection()
     g = LogSection(module="ROUTER", enable="trace+")
-    print r
-    print l
-    print c
-    print s
-    print g
+    print(r)
+    print(l)
+    print(c)
+    print(s)
+    print(g)
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/doc/man/help2txt.py
----------------------------------------------------------------------
diff --git a/doc/man/help2txt.py b/doc/man/help2txt.py
index a1eca2c..0fb2f7f 100644
--- a/doc/man/help2txt.py
+++ b/doc/man/help2txt.py
@@ -22,8 +22,9 @@ Convert --help output of a program into asciidoc text format.
 """
 from __future__ import print_function
 import re, sys
-from qpid_dispatch_internal.compat.subproc import check_output, STDOUT, CalledProcessError
-from os import path
+from qpid_dispatch_internal.compat import PY_STRING_TYPE
+from qpid_dispatch_internal.compat.subproc import check_output
+
 
 def help2txt(help_out):
     VALUE = r"(?:[\w-]+|<[^>]+>)"
@@ -34,6 +35,10 @@ def help2txt(help_out):
     OPT_HELP = r"^\s+(%s)(%s)" % (OPTIONS, HELP)
     SUBHEAD = r"^((?: +\w+)*):$"
 
+    # check_output returns binary in py3
+    if not isinstance(help_out, PY_STRING_TYPE):
+        help_out = help_out.decode()
+
     options = re.search("^Options:$", help_out, re.IGNORECASE | re.MULTILINE)
     if (options): help_out = help_out[options.end():]
     result = ""
@@ -49,7 +54,8 @@ def help2txt(help_out):
     return result
 
 def main(argv):
-    if len(argv) < 2: raise ValueError("Wrong number of arguments: "+usage)
+    if len(argv) < 2: raise ValueError("Wrong number of arguments\nUsage %s"
+                                       " <program> [args,...]" % argv[0])
     program = argv[1:]
     print(help2txt(check_output(program)))
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/doc/man/qdrouterd.conf.5.py
----------------------------------------------------------------------
diff --git a/doc/man/qdrouterd.conf.5.py b/doc/man/qdrouterd.conf.5.py
index 9c467b3..efdb554 100644
--- a/doc/man/qdrouterd.conf.5.py
+++ b/doc/man/qdrouterd.conf.5.py
@@ -24,9 +24,7 @@ Generate the qdrouterd.conf. man page from the qdrouterd management schema.
 import sys
 from qpid_dispatch_internal.management.qdrouter import QdSchema
 from qpid_dispatch_internal.management.schema_doc import SchemaWriter
-from qpid_dispatch_internal.management.schema import AttributeType
-
-from qpid_dispatch_internal.compat import OrderedDict
+from qpid_dispatch_internal.compat import dict_itervalues
 
 CONNECTOR = 'org.apache.qpid.dispatch.connector'
 LISTENER = 'org.apache.qpid.dispatch.listener'
@@ -132,7 +130,7 @@ listener {
         with self.section("Configuration Sections"):
 
             config = self.schema.entity_type("configurationEntity")
-            for entity_type in self.schema.entity_types.itervalues():
+            for entity_type in dict_itervalues(self.schema.entity_types):
                 if config in entity_type.all_bases:
                     with self.section(entity_type.short_name):
                         if entity_type.description:

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/python/qpid_dispatch/management/entity.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch/management/entity.py b/python/qpid_dispatch/management/entity.py
index 4e5466a..19df0e8 100644
--- a/python/qpid_dispatch/management/entity.py
+++ b/python/qpid_dispatch/management/entity.py
@@ -22,14 +22,30 @@ AMQP Managment Entity
 """
 
 import itertools, re
+import sys
+
+
+if sys.version_info[0] > 2:
+    # Python 3 does not have a unicode() builtin method,
+    # luckily all strings are unicode to start with
+    def unicode(s):
+        return s
+    def dict_iteritems(d):
+        return iter(d.items())
+else:
+    def dict_iteritems(d):
+        return d.iteritems()
+
+
 
 def clean_dict(items, **kwargs):
     """
     @param items: A mapping or iterable of pairs.
     @return: dict containing items + kwargs without any None values. All keys are unicode.
     """
-    if hasattr(items, 'iteritems'): items = items.iteritems()
-    return dict((unicode(k), v) for k, v in itertools.chain(items, kwargs.iteritems())
+    if isinstance(items, dict): items = dict_iteritems(items)
+    return dict((unicode(k), v) for k, v in itertools.chain(items,
+                                                            dict_iteritems(kwargs))
                 if v is not None)
 
 class EntityBase(object):
@@ -50,10 +66,10 @@ class EntityBase(object):
     def __init__(self, attributes=None, **kwargs):
         self.__dict__['attributes'] = {}
         if attributes:
-            for k, v in attributes.iteritems():
+            for k, v in dict_iteritems(attributes):
                 self.attributes[k] = v
                 self.__dict__[self._pyname(k)] = v
-        for k, v in kwargs.iteritems():
+        for k, v in dict_iteritems(kwargs):
             self._set(k, v)
 
     def __getitem__(self, name):
@@ -88,22 +104,24 @@ class EntityBase(object):
 
     def __repr__(self): return "EntityBase(%r)" % self.attributes
 
-    SPECIAL = [u"name", u"identity", u"type"]
-    N_SPECIAL = len(SPECIAL)
-    PRIORITY = dict([(SPECIAL[i], i) for i in xrange(N_SPECIAL)])
+    # attributes name, identity and type are special snowflake
+    # attributes that we print before all the not so special
+    # attributes.  Assign each a priority for the sort
+    _SPECIAL = {u"name": 0, u"identity": 1, u"type": 2}
 
     def __str__(self):
-        # Print the name and identity first.
-        keys = sorted(self.attributes.keys(), key=lambda k: self.PRIORITY.get(k, self.N_SPECIAL))
+        # Sort so the _SPECIAL attributes are printed first, 3 ==
+        # lower priority than special
+        keys = sorted(self.attributes.keys(),
+                      key=lambda k: self._SPECIAL.get(k, 3))
         return "Entity(%s)" % ", ".join("%s=%s" % (k, self.attributes[k]) for k in keys)
 
-
 def update(entity, values):
     """Update entity from values
     @param entity: an Entity
     @param values: a map of values
     """
-    for k, v in values.iteritems(): entity[k] = v
+    for k, v in dict_iteritems(values): entity[k] = v
 
 SEPARATOR_RE = re.compile(r' |_|-|\.')
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/python/qpid_dispatch_internal/compat/__init__.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/compat/__init__.py b/python/qpid_dispatch_internal/compat/__init__.py
index 2a0988b..8af2d21 100644
--- a/python/qpid_dispatch_internal/compat/__init__.py
+++ b/python/qpid_dispatch_internal/compat/__init__.py
@@ -19,12 +19,28 @@
 
 """Compatibility hacks for older versions of python"""
 
-import sys
+__all__ = [
+    "OrderedDict",
+    "JSON_LOAD_KWARGS",
+    "dictify",
+    "IS_PY2",
+    "PY_STRING_TYPE",
+    "PY_TEXT_TYPE",
+    "PY_BINARY_TYPE",
+    "PY_INTEGER_TYPES",
+    "dict_iterkeys",
+    "dict_itervalues",
+    "dict_iteritems",
+    "UNICODE",
+    "BINARY"
+]
 
-__all__ = ["OrderedDict"]
+import sys
 
-try: from collections import OrderedDict
-except: from ordereddict import OrderedDict
+try:
+    from collections import OrderedDict
+except Exception:
+    from ordereddict import OrderedDict
 
 if sys.version_info >= (2, 7):
     JSON_LOAD_KWARGS = {'object_pairs_hook':OrderedDict}
@@ -34,6 +50,82 @@ else:
 def dictify(od):
     """Recursively replace OrderedDict with dict"""
     if isinstance(od, OrderedDict):
-        return dict((k, dictify(v)) for k, v in od.iteritems())
+        return dict((k, dictify(v)) for k, v in dict_iteritems(od))
     else:
         return od
+
+IS_PY2 = sys.version_info[0] == 2
+
+if IS_PY2:
+    PY_STRING_TYPE = basestring  # noqa: F821
+    PY_TEXT_TYPE = unicode  # noqa: F821
+    PY_BINARY_TYPE = str
+    PY_INTEGER_TYPES = (int, long)  # noqa: F821
+    PY_LONG_TYPE = long  # noqa: F821
+    def dict_iterkeys(d):
+        return d.iterkeys()
+    def dict_itervalues(d):
+        return d.itervalues()
+    def dict_iteritems(d):
+        return d.iteritems()
+    def dict_keys(d):
+        return d.keys()
+    def dict_values(d):
+        return d.values()
+    def dict_items(d):
+        return d.items()
+    def BINARY(s):
+        ts = type(s)
+        if ts is str:
+            return s
+        elif ts is unicode:  # noqa: F821
+            return s.encode("utf-8")
+        else:
+            raise TypeError("%s cannot be converted to binary" % ts)
+    def UNICODE(s):
+        if type(s) is str:
+            return s.decode("utf-8")
+        elif type(s) is unicode:  # noqa: F821
+            return s
+        else:
+            return unicode(str(s), "utf-8")  # noqa: F821
+    def LONG(i):
+        return long(i)  # noqa: F821
+else:
+    PY_STRING_TYPE = str
+    PY_TEXT_TYPE = str
+    PY_BINARY_TYPE = bytes
+    PY_INTEGER_TYPES = (int,)
+    PY_LONG_TYPE = int
+    def dict_iterkeys(d):
+        return iter(d.keys())
+    def dict_itervalues(d):
+        return iter(d.values())
+    def dict_iteritems(d):
+        return iter(d.items())
+    # .keys(), .items(), .values()
+    # now return a dict_view not a list. Should be ok unless dict is modified
+    # when iterating over it. Use these if that's the case:
+    def dict_keys(d):
+        return list(d.keys())
+    def dict_values(d):
+        return list(d.values())
+    def dict_items(d):
+        return list(d.items())
+    def BINARY(s):
+        st = type(s)
+        if st is str:
+            return s.encode("utf-8")
+        elif st is bytes:
+            return s
+        else:
+            raise TypeError("%s cannot be converted to binary" % st)
+    def UNICODE(s):
+        if type(s) is bytes:
+            return s.decode("utf-8")
+        elif type(s) is str:
+            return s
+        else:
+            return str(s)
+    def LONG(i):
+        return int(i)

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/python/qpid_dispatch_internal/compat/ordereddict.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/compat/ordereddict.py b/python/qpid_dispatch_internal/compat/ordereddict.py
index a312cfa..2fa007d 100644
--- a/python/qpid_dispatch_internal/compat/ordereddict.py
+++ b/python/qpid_dispatch_internal/compat/ordereddict.py
@@ -31,7 +31,11 @@ try:
 except ImportError:
     pass
 
-
+# Note well: this class is only used for versions of python < 2.7
+# Since 2.7 OrderDict is part of the collections module of the standard
+# library. It does not need to be python3 compatible and can
+# eventually removed when python versions <= 2.6 are no longer supported.
+#
 class OrderedDict(dict):
     'Dictionary that remembers insertion order'
     # An inherited dict maps keys to values.

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/python/qpid_dispatch_internal/dispatch.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/dispatch.py b/python/qpid_dispatch_internal/dispatch.py
index 4c9123b..a8cd05b 100644
--- a/python/qpid_dispatch_internal/dispatch.py
+++ b/python/qpid_dispatch_internal/dispatch.py
@@ -33,6 +33,7 @@ This module also prevents the proton python module from being accidentally loade
 import sys, ctypes
 from ctypes import c_char_p, c_long, py_object
 import qpid_dispatch_site
+from .compat import UNICODE
 
 class CError(Exception):
     """Exception raised if there is an error in a C call"""
@@ -54,7 +55,9 @@ class QdDll(ctypes.PyDLL):
         # No check on qd_error_* functions, it would be recursive
         self._prototype(self.qd_error_code, c_long, [], check=False)
         self._prototype(self.qd_error_message, c_char_p, [], check=False)
-
+        # in python3 c_char_p returns a byte type for the error message.  We
+        # need to convert that to a unicode string:
+        self.qd_error_message.errcheck = lambda x,y,z : UNICODE(x)
         self._prototype(self.qd_log_entity, c_long, [py_object])
         self._prototype(self.qd_dispatch_configure_router, None, [self.qd_dispatch_p, py_object])
         self._prototype(self.qd_dispatch_prepare, None, [self.qd_dispatch_p])
@@ -129,6 +132,10 @@ def import_check(name, *args, **kw):
     return builtin_import(name, *args, **kw)
 
 check_forbidden()
-import __builtin__
-builtin_import = __builtin__.__import__
-__builtin__.__import__ = import_check
+try:
+    import builtins
+except:  # py2
+    import __builtin__ as builtins
+
+builtin_import = builtins.__import__
+builtins.__import__ = import_check

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/python/qpid_dispatch_internal/management/agent.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/management/agent.py b/python/qpid_dispatch_internal/management/agent.py
index 88e828b..6d737bb 100644
--- a/python/qpid_dispatch_internal/management/agent.py
+++ b/python/qpid_dispatch_internal/management/agent.py
@@ -64,13 +64,24 @@ data that may be updated in other threads.
 
 import traceback, json, pstats
 import socket
-from itertools import ifilter, chain
 from traceback import format_exc
 from threading import Lock
 from cProfile import Profile
-from cStringIO import StringIO
+try:
+    # py2
+    from cStringIO import StringIO
+except ImportError:
+    from io import StringIO
+
 from ctypes import c_void_p, py_object, c_long
 from subprocess import Popen
+try:
+    # Python 2
+    from future_builtins import filter
+except ImportError:
+    # Python 3
+    pass
+
 from ..dispatch import IoAdapter, LogAdapter, LOG_INFO, LOG_WARNING, LOG_DEBUG, LOG_ERROR, TREATMENT_ANYCAST_CLOSEST
 from qpid_dispatch.management.error import ManagementError, OK, CREATED, NO_CONTENT, STATUS_TEXT, \
     BadRequestStatus, InternalServerErrorStatus, NotImplementedStatus, NotFoundStatus, ForbiddenStatus
@@ -80,11 +91,12 @@ from .qdrouter import QdSchema
 from ..router.message import Message
 from ..router.address import Address
 from ..policy.policy_manager import PolicyManager
+from qpid_dispatch_internal.compat import dict_iteritems
 
 
 def dictstr(d):
     """Stringify a dict in the form 'k=v, k=v ...' instead of '{k:v, ...}'"""
-    return ", ".join("%s=%r" % (k, v) for k, v in d.iteritems())
+    return ", ".join("%s=%r" % (k, v) for k, v in dict_iteritems(d))
 
 def required_property(prop, request):
     """Raise exception if required property is missing"""
@@ -436,7 +448,7 @@ class ConsoleEntity(EntityAdapter):
                                 dargs['$wsport'] = wsport
                             if home:
                                 dargs['$home'] = home
-                            for k,v in dargs.iteritems():
+                            for k,v in dict_iteritems(dargs):
                                 args = args.replace(k,str(v))
                             pargs += args.split()
 
@@ -517,15 +529,22 @@ class EntityCache(object):
 
     def map_filter(self, function, test):
         """Filter with test then apply function."""
-        return map(function, ifilter(test, self.entities))
+        if function is None:
+            function = lambda x: x  # return results of filter
+        return list(map(function, filter(test, self.entities)))
 
     def map_type(self, function, type):
-        """Apply function to all entities of type, if type is None do all entities"""
+        """Apply function to all entities of type, if type is None do all
+        entities"""
+        if function is None:
+            function = lambda x: x
         if type is None:
-            return map(function, self.entities)
+            return list(map(function, self.entities))
         else:
-            if not isinstance(type, EntityType): type = self.schema.entity_type(type)
-            return map(function, ifilter(lambda e: e.entity_type.is_a(type), self.entities))
+            if not isinstance(type, EntityType):
+                type = self.schema.entity_type(type)
+            return list(map(function, filter(lambda e: e.entity_type.is_a(type),
+                                             self.entities)))
 
     def add(self, entity):
         """Add an entity to the agent"""
@@ -575,7 +594,7 @@ class EntityCache(object):
             """Remove redundant add/remove pairs of events."""
             add = {}            # add[pointer] = index of add event.
             redundant = []      # List of redundant event indexes.
-            for i in xrange(len(events)):
+            for i in range(len(events)):
                 action, type, pointer = events[i]
                 if action == ADD:
                     add[pointer] = i
@@ -620,13 +639,13 @@ class ManagementEntity(EntityAdapter):
         """Management node query operation"""
         entity_type = self.requested_type(request)
         if entity_type:
-            all_attrs = set(entity_type.attributes.keys())
+            all_attrs = list(entity_type.attributes.keys())
         else:
-            all_attrs = self._schema.all_attributes
+            all_attrs = list(self._schema.all_attributes)
 
-        names = set(request.body.get('attributeNames'))
+        names = request.body.get('attributeNames')
         if names:
-            unknown = names - all_attrs
+            unknown = set(names) - set(all_attrs)
             if unknown:
                 if entity_type:
                     for_type = " for type %s" % entity_type.name
@@ -646,7 +665,7 @@ class ManagementEntity(EntityAdapter):
             if non_empty: results.append(result)
 
         self._agent.entities.map_type(add_result, entity_type)
-        return (OK, {'attributeNames': list(names), 'results': results})
+        return (OK, {'attributeNames': names, 'results': results})
 
     def get_types(self, request):
         type = self.requested_type(request)
@@ -662,13 +681,13 @@ class ManagementEntity(EntityAdapter):
     def get_operations(self, request):
         type = self.requested_type(request)
         return (OK, dict((t, et.operations)
-                         for t, et in self._schema.entity_types.iteritems()
+                         for t, et in dict_iteritems(self._schema.entity_types)
                          if not type or type.name == t))
 
     def get_attributes(self, request):
         type = self.requested_type(request)
         return (OK, dict((t, [a for a in et.attributes])
-                         for t, et in self._schema.entity_types.iteritems()
+                         for t, et in dict_iteritems(self._schema.entity_types)
                          if not type or type.name == t))
 
     def get_mgmt_nodes(self, request):
@@ -786,7 +805,7 @@ class Agent(object):
         """Called when a management request is received."""
         def error(e, trace):
             """Raise an error"""
-            self.log(LOG_ERROR, "Error performing %s: %s"%(request.properties.get('operation'), e.message))
+            self.log(LOG_ERROR, "Error performing %s: %s"%(request.properties.get('operation'), e.description))
             self.respond(request, e.status, e.description)
 
         # If there's no reply_to, don't bother to process the request.
@@ -800,16 +819,16 @@ class Agent(object):
                 self.log(LOG_DEBUG, "Agent request %s"% request)
                 status, body = self.handle(request)
                 self.respond(request, status=status, body=body)
-            except ManagementError, e:
+            except ManagementError as e:
                 error(e, format_exc())
-            except ValidationError, e:
+            except ValidationError as e:
                 error(BadRequestStatus(str(e)), format_exc())
-            except Exception, e:
+            except Exception as e:
                 error(InternalServerErrorStatus("%s: %s"%(type(e).__name__, e)), format_exc())
 
     def entity_type(self, type):
         try: return self.schema.entity_type(type)
-        except ValidationError, e: raise NotFoundStatus(str(e))
+        except ValidationError as e: raise NotFoundStatus(str(e))
 
     def handle(self, request):
         """
@@ -904,9 +923,9 @@ class Agent(object):
 
         def attrvals():
             """String form of the id attribute values for error messages"""
-            return " ".join(["%s=%r" % (k, v) for k, v in ids.iteritems()])
+            return " ".join(["%s=%r" % (k, v) for k, v in dict_iteritems(ids)])
 
-        k, v = ids.iteritems().next() # Get the first id attribute
+        k, v = next(dict_iteritems(ids)) # Get the first id attribute
         found = self.entities.map_filter(None, lambda e: e.attributes.get(k) == v)
         if len(found) == 1:
             entity = found[0]
@@ -916,7 +935,7 @@ class Agent(object):
         else:
             raise NotFoundStatus("No entity with %s" % attrvals())
 
-        for k, v in ids.iteritems():
+        for k, v in dict_iteritems(ids):
             if entity[k] != v: raise BadRequestStatus("Conflicting %s" % attrvals())
 
         if requested_type:

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/python/qpid_dispatch_internal/management/config.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/management/config.py b/python/qpid_dispatch_internal/management/config.py
index 303609e..24a6f04 100644
--- a/python/qpid_dispatch_internal/management/config.py
+++ b/python/qpid_dispatch_internal/management/config.py
@@ -28,19 +28,24 @@ from qpid_dispatch.management.entity import camelcase
 
 from ..dispatch import QdDll
 from .qdrouter import QdSchema
+from qpid_dispatch_internal.compat import dict_itervalues
+from qpid_dispatch_internal.compat import dict_iteritems
+from qpid_dispatch_internal.compat import PY_STRING_TYPE
+from qpid_dispatch_internal.compat import PY_TEXT_TYPE
 
 class Config(object):
     """Load config entities from qdrouterd.conf and validated against L{QdSchema}."""
 
     def __init__(self, filename=None, schema=QdSchema(), raw_json=False):
         self.schema = schema
-        self.config_types = [et for et in schema.entity_types.itervalues()
+        self.config_types = [et for et in dict_itervalues(schema.entity_types)
                              if schema.is_configuration(et)]
         if filename:
             try:
                 self.load(filename, raw_json)
-            except Exception, e:
-                raise Exception, "Cannot load configuration file %s: %s" % (filename, e), sys.exc_info()[2]
+            except Exception as e:
+                raise Exception("Cannot load configuration file %s: %s"
+                                % (filename, e))
         else:
             self.entities = []
 
@@ -48,7 +53,7 @@ class Config(object):
     def transform_sections(sections):
         for s in sections:
             s[0] = camelcase(s[0])
-            s[1] = dict((camelcase(k), v) for k, v in s[1].iteritems())
+            s[1] = dict((camelcase(k), v) for k, v in dict_iteritems(s[1]))
             if s[0] == "address":   s[0] = "router.config.address"
             if s[0] == "linkRoute": s[0] = "router.config.linkRoute"
             if s[0] == "autoLink":  s[0] = "router.config.autoLink"
@@ -111,7 +116,7 @@ class Config(object):
         @param source: A file name, open file object or iterable list of lines
         @param raw_json: Source is pure json not needing conf-style substitutions
         """
-        if isinstance(source, basestring):
+        if isinstance(source, (PY_STRING_TYPE, PY_TEXT_TYPE)):
             raw_json |= source.endswith(".json")
             with open(source) as f:
                 self.load(f, raw_json)

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/python/qpid_dispatch_internal/management/qdrouter.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/management/qdrouter.py b/python/qpid_dispatch_internal/management/qdrouter.py
index efb9965..e26b96b 100644
--- a/python/qpid_dispatch_internal/management/qdrouter.py
+++ b/python/qpid_dispatch_internal/management/qdrouter.py
@@ -24,7 +24,7 @@ Qpid Dispatch Router management schema and config file parsing.
 import json
 from pkgutil import get_data
 from . import schema
-from ..compat import JSON_LOAD_KWARGS
+from qpid_dispatch_internal.compat import JSON_LOAD_KWARGS
 
 class QdSchema(schema.Schema):
     """
@@ -39,7 +39,7 @@ class QdSchema(schema.Schema):
         qd_schema = get_data('qpid_dispatch.management', 'qdrouter.json')
         try:
             super(QdSchema, self).__init__(**json.loads(qd_schema, **JSON_LOAD_KWARGS))
-        except Exception,e:
+        except Exception as e:
             raise ValueError("Invalid schema qdrouter.json: %s" % e)
         self.configuration_entity = self.entity_type(self.CONFIGURATION_ENTITY)
         self.operational_entity = self.entity_type(self.OPERATIONAL_ENTITY)

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/python/qpid_dispatch_internal/management/schema.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/management/schema.py b/python/qpid_dispatch_internal/management/schema.py
index 7427851..6e619e7 100644
--- a/python/qpid_dispatch_internal/management/schema.py
+++ b/python/qpid_dispatch_internal/management/schema.py
@@ -31,6 +31,10 @@ import traceback
 from qpid_dispatch.management.entity import EntityBase
 from qpid_dispatch.management.error import NotImplementedStatus
 from ..compat import OrderedDict
+from ..compat import PY_STRING_TYPE
+from ..compat import PY_TEXT_TYPE
+from ..compat import dict_keys
+from ..compat import dict_items
 try:
     from ..dispatch import LogAdapter, LOG_WARNING
     logger_available = True
@@ -89,7 +93,7 @@ class BooleanType(Type):
         @return A python bool.
         """
         try:
-            if isinstance(value, basestring):
+            if isinstance(value, (PY_STRING_TYPE, PY_TEXT_TYPE)):
                 return self.VALUES[value.lower()]
             return bool(value)
         except:
@@ -104,6 +108,7 @@ class EnumValue(str):
         setattr(s, 'value', value)
         return s
 
+    def __hash__(self): return super(EnumValue, self).__hash__()
     def __int__(self): return self.value
     def __eq__(self, x): return str(self) == x or int(self) == x
     def __ne__(self, x): return not self == x
@@ -217,9 +222,11 @@ class AttributeType(object):
             self.create=create
             self.update=update
             self.graph=graph
-        except:
-            ex, msg, trace = sys.exc_info()
-            raise ValidationError, "Attribute '%s': %s" % (name, msg), trace
+        except Exception:
+            raise ValidationError("Attribute '%s': %s\n%s"
+                                  % (name,
+                                     sys.exc_info()[1],
+                                     sys.exc_info()[2]))
 
     def missing_value(self):
         """
@@ -243,8 +250,8 @@ class AttributeType(object):
                 self.name, self.value, value))
         try:
             return self.atype.validate(value)
-        except (TypeError, ValueError), e:
-            raise ValidationError, str(e), sys.exc_info()[2]
+        except (TypeError, ValueError) as e:
+            raise ValidationError("%s:%s" % (str(e), sys.exc_info()[2]))
 
     def dump(self):
         """
@@ -270,7 +277,7 @@ class MessageDef(object):
         self.body = None
         if body: self.body = AttributeType("body", **body)
         self.properties = dict((name, AttributeType(name, **value))
-                               for name, value in (properties or {}).iteritems())
+                               for name, value in (properties or {}).items())
 
 
 class OperationDef(object):
@@ -282,9 +289,9 @@ class OperationDef(object):
             self.request = self.response = None
             if request: self.request = MessageDef(**request)
             if response: self.response = MessageDef(**response)
-        except:
-            ex, msg, trace = sys.exc_info()
-            raise ValidationError, "Operation '%s': %s" % (name, msg), trace
+        except Exception as exc:
+            raise ValidationError("Operation '%s': %s\n%s"
+                                  % (name, str(exc), sys.exc_info()[2]))
 
 
 class EntityType(object):
@@ -320,7 +327,7 @@ class EntityType(object):
             else:
                 self.name = self.short_name = name
             self.attributes = OrderedDict((k, AttributeType(k, defined_in=self, **v))
-                                              for k, v in (attributes or {}).iteritems())
+                                              for k, v in (attributes or {}).items())
 
             self.deprecated_attributes = OrderedDict()
             for key, value in self.attributes.items():
@@ -357,10 +364,12 @@ class EntityType(object):
             self._init = False      # Have not yet initialized from base and attributes.
             # Operation definitions
             self.operation_defs = dict((name, OperationDef(name, **op))
-                                  for name, op in (operationDefs or {}).iteritems())
-        except:
-            ex, msg, trace = sys.exc_info()
-            raise ValidationError, "%s '%s': %s" % (type(self).__name__, name, msg), trace
+                                  for name, op in (operationDefs or {}).items())
+        except Exception as exc:
+            raise ValidationError("%s '%s': %s\n%s" % (type(self).__name__,
+                                                       name,
+                                                       exc,
+                                                       sys.exc_info()[2]))
 
     def init(self):
         """Find bases after all types are loaded."""
@@ -381,7 +390,7 @@ class EntityType(object):
                                       % (self.name, how, other.short_name, what, ",".join(overlap)))
         check(self.operations, other.operations, "operations")
         self.operations += other.operations
-        check(self.attributes.iterkeys(), other.attributes.itervalues(), "attributes")
+        check(dict_keys(self.attributes), other.attributes.values(), "attributes")
         self.attributes.update(other.attributes)
         if other.name == 'entity':
             # Fill in entity "type" attribute automatically.
@@ -393,7 +402,7 @@ class EntityType(object):
 
     def attribute(self, name):
         """Get the AttributeType for name"""
-        if not name in self.attributes and not name in self.deprecated_attributes.keys():
+        if not name in self.attributes and not name in dict_keys(self.deprecated_attributes):
             raise ValidationError("Unknown attribute '%s' for '%s'" % (name, self))
         if self.attributes.get(name):
             return self.attributes[name]
@@ -407,7 +416,7 @@ class EntityType(object):
     @property
     def my_attributes(self):
         """Return only attribute types defined in this entity type"""
-        return [a for a in self.attributes.itervalues() if a.defined_in == self]
+        return [a for a in self.attributes.values() if a.defined_in == self]
 
     def validate(self, attributes):
         """
@@ -419,7 +428,7 @@ class EntityType(object):
 
         try:
             # Add missing values
-            for attr in self.attributes.itervalues():
+            for attr in self.attributes.values():
                 if attributes.get(attr.name) is None:
                     value = None
                     deprecation_name = attr.deprecation_name
@@ -449,12 +458,12 @@ class EntityType(object):
                                                   (deprecation_name, attr.name, self.short_name))
 
             # Validate attributes.
-            for name, value in attributes.iteritems():
+            for name, value in dict_items(attributes):
                 if name == 'type':
                     value = self.schema.long_name(value)
                 attributes[name] = self.attribute(name).validate(value)
-        except ValidationError, e:
-            raise ValidationError, "%s: %s"%(self, e), sys.exc_info()[2]
+        except ValidationError as e:
+            raise ValidationError("%s: %s" % (self, e))
 
         return attributes
 
@@ -471,7 +480,7 @@ class EntityType(object):
                 raise ValidationError("Cannot set attribute '%s' in CREATE" % a)
 
     def update_check(self, new_attributes, old_attributes):
-        for a, v in new_attributes.iteritems():
+        for a, v in new_attributes.items():
             # Its not an error to include an attribute in UPDATE if the value is not changed.
             if not self.attribute(a).update and \
                not (a in old_attributes and old_attributes[a] == v):
@@ -481,7 +490,7 @@ class EntityType(object):
         """Json friendly representation"""
         return _dump_dict([
             ('attributes', OrderedDict(
-                (k, v.dump()) for k, v in self.attributes.iteritems()
+                (k, v.dump()) for k, v in self.attributes.items()
                 if k != 'type')), # Don't dump 'type' attribute, dumped separately.
             ('operations', self.operations),
             ('description', self.description or None),
@@ -529,15 +538,15 @@ class Schema(object):
 
         def parsedefs(cls, defs):
             return OrderedDict((self.long_name(k), cls(k, self, **v))
-                               for k, v in (defs or {}).iteritems())
+                               for k, v in (defs or {}).items())
 
         self.entity_types = parsedefs(EntityType, entityTypes)
 
         self.all_attributes = set()
 
-        for e in self.entity_types.itervalues():
+        for e in self.entity_types.values():
             e.init()
-            self.all_attributes.update(e.attributes.keys())
+            self.all_attributes.update(dict_keys(e.attributes))
 
     def log(self, level, text):
         if not self.log_adapter:
@@ -564,7 +573,7 @@ class Schema(object):
         return OrderedDict([
             ('prefix', self.prefix),
             ('entityTypes',
-             OrderedDict((e.short_name, e.dump()) for e in self.entity_types.itervalues()))
+             OrderedDict((e.short_name, e.dump()) for e in self.entity_types.values()))
         ])
 
     def _lookup(self, map, name, message, error):
@@ -622,7 +631,7 @@ class Schema(object):
 
     def entity(self, attributes):
         """Convert an attribute map into an L{SchemaEntity}"""
-        attributes = dict((k, v) for k, v in attributes.iteritems() if v is not None)
+        attributes = dict((k, v) for k, v in attributes.items() if v is not None)
         return SchemaEntity(self.entity_type(attributes['type']), attributes)
 
     def entities(self, attribute_maps):
@@ -631,14 +640,14 @@ class Schema(object):
 
     def filter(self, predicate):
         """Return an iterator over entity types that satisfy predicate."""
-        if predicate is None: return self.entity_types.itervalues()
-        return (t for t in self.entity_types.itervalues() if predicate(t))
+        if predicate is None: return self.entity_types.values()
+        return (t for t in self.entity_types.values() if predicate(t))
 
     def by_type(self, type):
         """Return an iterator over entity types that extend or are type.
         If type is None return all entities."""
         if not type:
-            return self.entity_types.itervalues()
+            return self.entity_types.values()
         else:
             return self.filter(lambda t: t.is_a(type))
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/python/qpid_dispatch_internal/management/schema_doc.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/management/schema_doc.py b/python/qpid_dispatch_internal/management/schema_doc.py
index 676fe50..d5bbf50 100644
--- a/python/qpid_dispatch_internal/management/schema_doc.py
+++ b/python/qpid_dispatch_internal/management/schema_doc.py
@@ -19,9 +19,12 @@
 
 """Library for generating asciidoc documentation from a L{schema.Schema}"""
 
+from __future__ import print_function
+
 from collections import namedtuple
 import sys
 from .schema import AttributeType
+from qpid_dispatch_internal.compat import PY_STRING_TYPE, dict_itervalues
 
 class SchemaWriter(object):
     """Write the schema as an asciidoc document"""
@@ -32,7 +35,7 @@ class SchemaWriter(object):
         # Options affecting how output is written
 
     def warn(self, message):
-        if not self.quiet: print >>sys.stderr, message
+        if not self.quiet: print(message, file=sys.stderr)
 
     def write(self, text): self.output.write(text)
 
@@ -52,7 +55,7 @@ class SchemaWriter(object):
 
     def attribute_qualifiers(self, attr, show_create=True, show_update=True):
         default = attr.default
-        if isinstance(default, basestring) and default.startswith('$'):
+        if isinstance(default, PY_STRING_TYPE) and default.startswith('$'):
             default = None  # Don't show defaults that are references, confusing.
         return ' (%s)' % (', '.join(
             filter(None, [str(attr.atype),
@@ -100,7 +103,7 @@ class SchemaWriter(object):
                         message.body.description))
                 if message.properties:
                     self.para(".%s properties" % (what.capitalize()))
-                    for prop in message.properties.itervalues():
+                    for prop in dict_itervalues(message.properties):
                         self.attribute_type(prop)
 
         with self.section("Operation %s" % op.name):
@@ -109,7 +112,7 @@ class SchemaWriter(object):
             request_response("response")
 
     def operation_defs(self, entity_type):
-        for op in entity_type.operation_defs.itervalues():
+        for op in dict_itervalues(entity_type.operation_defs):
             self.operation_def(op, entity_type)
 
     def entity_type(self, entity_type, operation_defs=True):

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/python/qpid_dispatch_internal/policy/policy_local.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/policy/policy_local.py b/python/qpid_dispatch_internal/policy/policy_local.py
index b482b7f..9218a56 100644
--- a/python/qpid_dispatch_internal/policy/policy_local.py
+++ b/python/qpid_dispatch_internal/policy/policy_local.py
@@ -23,7 +23,12 @@
 
 import json
 import pdb
-from policy_util import PolicyError, HostStruct, HostAddr, PolicyAppConnectionMgr, is_ipv6_enabled
+from .policy_util import PolicyError, HostStruct, HostAddr, PolicyAppConnectionMgr, is_ipv6_enabled
+from ..compat import PY_STRING_TYPE
+from ..compat import PY_TEXT_TYPE
+from ..compat import dict_iteritems
+from ..compat import dict_keys
+
 
 """
 Entity implementing the business logic of user connection/access policy.
@@ -148,7 +153,7 @@ class PolicyCompiler(object):
         """
         try:
             v_int = int(val)
-        except Exception, e:
+        except Exception as e:
             errors.append("Value '%s' does not resolve to an integer." % val)
             return False
         if v_int < v_min:
@@ -178,15 +183,11 @@ class PolicyCompiler(object):
         """
         key = PolicyKeys.KW_REMOTE_HOSTS
         # convert val string to list of host specs
-        if type(val) is str:
-            # 'abc, def, mytarget'
-            val = [x.strip(' ') for x in val.split(PolicyKeys.KC_CONFIG_LIST_SEP)]
-        elif type(val) is list:
+        if isinstance(val, list):
             # ['abc', 'def', 'mytarget']
             pass
-        elif type(val) is unicode:
-            # u'abc, def, mytarget'
-            val = [x.strip(' ') for x in str(val).split(PolicyKeys.KC_CONFIG_LIST_SEP)]
+        elif isinstance(val, (PY_STRING_TYPE, PY_TEXT_TYPE)):
+            val = [x.strip(' ') for x in val.split(PolicyKeys.KC_CONFIG_LIST_SEP)]
         else:
             errors.append(
                 "Policy vhost '%s' user group '%s' option '%s' has illegal value '%s'. Type must be 'str' or 'list' but is '%s;" %
@@ -196,7 +197,7 @@ class PolicyCompiler(object):
             try:
                 coha = HostAddr(coname, PolicyKeys.KC_CONFIG_IP_SEP)
                 list_out.append(coha)
-            except Exception, e:
+            except Exception as e:
                 errors.append("Policy vhost '%s' user group '%s' option '%s' connectionOption '%s' failed to translate: '%s'." %
                                 (vhostname, groupname, key, coname, e))
                 return False
@@ -238,7 +239,7 @@ class PolicyCompiler(object):
         user_targets = False
         user_src_pattern = False
         user_tgt_pattern = False
-        for key, val in policy_in.iteritems():
+        for key, val in dict_iteritems(policy_in):
             if key not in self.allowed_settings_options:
                 warnings.append("Policy vhost '%s' user group '%s' option '%s' is ignored." %
                                 (vhostname, usergroup, key))
@@ -277,15 +278,12 @@ class PolicyCompiler(object):
                          PolicyKeys.KW_TARGET_PATTERN
                          ]:
                 # accept a string or list
-                if type(val) is str:
-                    # 'abc, def, mytarget'
-                    val = [x.strip(' ') for x in val.split(PolicyKeys.KC_CONFIG_LIST_SEP)]
-                elif type(val) is list:
+                if isinstance(val, list):
                     # ['abc', 'def', 'mytarget']
                     pass
-                elif type(val) is unicode:
-                    # u'abc, def, mytarget'
-                    val = [x.strip(' ') for x in str(val).split(PolicyKeys.KC_CONFIG_LIST_SEP)]
+                elif isinstance(val, (PY_STRING_TYPE, PY_TEXT_TYPE)):
+                    # 'abc, def, mytarget'
+                    val = [x.strip(' ') for x in val.split(PolicyKeys.KC_CONFIG_LIST_SEP)]
                 else:
                     errors.append("Policy vhost '%s' user group '%s' option '%s' has illegal value '%s'. Type must be 'str' or 'list' but is '%s;" %
                                   (vhostname, usergroup, key, val, type(val)))
@@ -335,7 +333,7 @@ class PolicyCompiler(object):
         policy_out[PolicyKeys.KW_GROUPS] = {}
 
         # validate the options
-        for key, val in policy_in.iteritems():
+        for key, val in dict_iteritems(policy_in):
             if key not in self.allowed_ruleset_options:
                 warnings.append("Policy vhost '%s' option '%s' is ignored." %
                                 (name, key))
@@ -360,7 +358,7 @@ class PolicyCompiler(object):
                     errors.append("Policy vhost '%s' option '%s' must be of type 'dict' but is '%s'" %
                                   (name, key, type(val)))
                     return False
-                for skey, sval in val.iteritems():
+                for skey, sval in dict_iteritems(val):
                     newsettings = {}
                     if not self.compile_app_settings(name, skey, sval, newsettings, warnings, errors):
                         return False
@@ -371,7 +369,7 @@ class PolicyCompiler(object):
         # Create user-to-group map for looking up user's group
         policy_out[PolicyKeys.RULESET_U2G_MAP] = {}
         if PolicyKeys.KW_GROUPS in policy_out:
-            for group, groupsettings in policy_out[PolicyKeys.KW_GROUPS].iteritems():
+            for group, groupsettings in dict_iteritems(policy_out[PolicyKeys.KW_GROUPS]):
                 if PolicyKeys.KW_USERS in groupsettings:
                     users = [x.strip(' ') for x in groupsettings[PolicyKeys.KW_USERS].split(PolicyKeys.KC_CONFIG_LIST_SEP)]
                     for user in users:
@@ -449,7 +447,7 @@ class AppStats(object):
 
 #
 #
-class ConnectionFacts:
+class ConnectionFacts(object):
     def __init__(self, user, host, app, conn_name):
         self.user = user
         self.host = host
@@ -554,7 +552,7 @@ class PolicyLocal(object):
         """
         Return a list of vhost names in this policy
         """
-        return self.rulesetdb.keys()
+        return dict_keys(self.rulesetdb)
 
     def set_default_vhost(self, name):
         """
@@ -662,7 +660,7 @@ class PolicyLocal(object):
             # Return success
             return usergroup
 
-        except Exception, e:
+        except Exception as e:
             self._manager.log_info(
                 "DENY AMQP Open lookup_user failed for user '%s', rhost '%s', vhost '%s': "
                 "Internal error: %s" % (user, rhost, vhost, e))
@@ -702,7 +700,7 @@ class PolicyLocal(object):
             upolicy.update(ruleset[PolicyKeys.KW_GROUPS][groupname])
             upolicy[PolicyKeys.KW_CSTATS] = self.statsdb[vhost].get_cstats()
             return True
-        except Exception, e:
+        except Exception as e:
             return False
 
     def close_connection(self, conn_id):
@@ -717,7 +715,7 @@ class PolicyLocal(object):
                 stats = self.statsdb[facts.app]
                 stats.disconnect(facts.conn_name, facts.user, facts.host)
                 del self._connections[conn_id]
-        except Exception, e:
+        except Exception as e:
             self._manager.log_trace(
                 "Policy internal error closing connection id %s. %s" % (conn_id, str(e)))
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/python/qpid_dispatch_internal/policy/policy_manager.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/policy/policy_manager.py b/python/qpid_dispatch_internal/policy/policy_manager.py
index 34deabb..0445386 100644
--- a/python/qpid_dispatch_internal/policy/policy_manager.py
+++ b/python/qpid_dispatch_internal/policy/policy_manager.py
@@ -23,7 +23,8 @@
 
 import json
 import traceback
-from policy_local import PolicyLocal
+
+from .policy_local import PolicyLocal
 from ..dispatch import LogAdapter, LOG_INFO, LOG_TRACE, LOG_DEBUG, LOG_ERROR, LOG_WARNING
 
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/python/qpid_dispatch_internal/policy/policy_util.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/policy/policy_util.py b/python/qpid_dispatch_internal/policy/policy_util.py
index eaf8993..b74f7b5 100644
--- a/python/qpid_dispatch_internal/policy/policy_util.py
+++ b/python/qpid_dispatch_internal/policy/policy_util.py
@@ -88,7 +88,7 @@ class HostStruct(object):
             self.family = sfamily
             self.binary = socket.inet_pton(family, saddr)
             return
-        except Exception, e:
+        except Exception as e:
             raise PolicyError("HostStruct: '%s' failed to resolve: '%s'" %
                               (hostname, e))
 
@@ -201,7 +201,7 @@ class HostAddr(object):
             return c0 >= 0 and c1 <= 0
         except PolicyError:
             return False
-        except Exception, e:
+        except Exception as e:
             assert isinstance(candidate, HostStruct), \
                 ("Wrong type. Expected HostStruct but received %s" % candidate.__class__.__name__)
             return False
@@ -341,4 +341,4 @@ class PolicyAppConnectionMgr(object):
         Record the statistic for a connection denied by some other process
         @return:
         """
-        self.connections_denied += 1
\ No newline at end of file
+        self.connections_denied += 1

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/python/qpid_dispatch_internal/router/__init__.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/router/__init__.py b/python/qpid_dispatch_internal/router/__init__.py
index 27bcf09..0c1682d 100644
--- a/python/qpid_dispatch_internal/router/__init__.py
+++ b/python/qpid_dispatch_internal/router/__init__.py
@@ -18,6 +18,6 @@
 #
 
 from .engine import RouterEngine
-from address import Address
+from .address import Address
 
 __all__ = ["RouterEngine", "Address"]

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/python/qpid_dispatch_internal/router/data.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/router/data.py b/python/qpid_dispatch_internal/router/data.py
index a2b669b..827f621 100644
--- a/python/qpid_dispatch_internal/router/data.py
+++ b/python/qpid_dispatch_internal/router/data.py
@@ -21,7 +21,10 @@
 ## Define the current protocol version.  Any messages that do not contain version
 ## information shall be considered to be coming from routers using version 0.
 ##
-ProtocolVersion = 1L
+from ..compat import PY_LONG_TYPE
+from ..compat import LONG
+
+ProtocolVersion = LONG(1)
 
 def getMandatory(data, key, cls=None):
     """
@@ -57,12 +60,12 @@ class LinkState(object):
         if body:
             self.id = getMandatory(body, 'id', str)
             self.area = '0'
-            self.ls_seq = getMandatory(body, 'ls_seq', long)
+            self.ls_seq = getMandatory(body, 'ls_seq', PY_LONG_TYPE)
             self.peers = getMandatory(body, 'peers', dict)
         else:
             self.id = _id
             self.area = '0'
-            self.ls_seq = long(_ls_seq)
+            self.ls_seq = LONG(_ls_seq)
             self.peers = _peers
 
     def __repr__(self):
@@ -107,13 +110,13 @@ class MessageHELLO(object):
     This message is used by directly connected routers to determine with whom they have
     bidirectional connectivity.
     """
-    def __init__(self, body, _id=None, _seen_peers=None, _instance=long(0)):
+    def __init__(self, body, _id=None, _seen_peers=None, _instance=LONG(0)):
         if body:
             self.id = getMandatory(body, 'id', str)
             self.area = '0'
             self.seen_peers = getMandatory(body, 'seen', list)
-            self.instance = getOptional(body, 'instance', 0, long)
-            self.version  = getOptional(body, 'pv', 0, long)
+            self.instance = getOptional(body, 'instance', 0, PY_LONG_TYPE)
+            self.version  = getOptional(body, 'pv', 0, PY_LONG_TYPE)
         else:
             self.id   = _id
             self.area = '0'
@@ -145,19 +148,19 @@ class MessageRA(object):
     This message is sent periodically to indicate the originating router's sequence numbers
     for link-state and mobile-address-state.
     """
-    def __init__(self, body, _id=None, _ls_seq=None, _mobile_seq=None, _instance=long(0)):
+    def __init__(self, body, _id=None, _ls_seq=None, _mobile_seq=None, _instance=LONG(0)):
         if body:
             self.id = getMandatory(body, 'id', str)
             self.area = '0'
-            self.ls_seq = getMandatory(body, 'ls_seq', long)
-            self.mobile_seq = getMandatory(body, 'mobile_seq', long)
-            self.instance = getOptional(body, 'instance', 0, long)
-            self.version  = getOptional(body, 'pv', 0, long)
+            self.ls_seq = getMandatory(body, 'ls_seq', PY_LONG_TYPE)
+            self.mobile_seq = getMandatory(body, 'mobile_seq', PY_LONG_TYPE)
+            self.instance = getOptional(body, 'instance', 0, PY_LONG_TYPE)
+            self.version  = getOptional(body, 'pv', 0, PY_LONG_TYPE)
         else:
             self.id = _id
             self.area = '0'
-            self.ls_seq = long(_ls_seq)
-            self.mobile_seq = long(_mobile_seq)
+            self.ls_seq = LONG(_ls_seq)
+            self.mobile_seq = LONG(_mobile_seq)
             self.instance = _instance
             self.version  = ProtocolVersion
 
@@ -180,18 +183,18 @@ class MessageRA(object):
 class MessageLSU(object):
     """
     """
-    def __init__(self, body, _id=None, _ls_seq=None, _ls=None, _instance=long(0)):
+    def __init__(self, body, _id=None, _ls_seq=None, _ls=None, _instance=LONG(0)):
         if body:
             self.id = getMandatory(body, 'id', str)
             self.area = '0'
-            self.ls_seq = getMandatory(body, 'ls_seq', long)
+            self.ls_seq = getMandatory(body, 'ls_seq', PY_LONG_TYPE)
             self.ls = LinkState(getMandatory(body, 'ls', dict))
-            self.instance = getOptional(body, 'instance', 0, long)
-            self.version  = getOptional(body, 'pv', 0, long)
+            self.instance = getOptional(body, 'instance', 0, PY_LONG_TYPE)
+            self.version  = getOptional(body, 'pv', 0, PY_LONG_TYPE)
         else:
             self.id = _id
             self.area = '0'
-            self.ls_seq = long(_ls_seq)
+            self.ls_seq = LONG(_ls_seq)
             self.ls = _ls
             self.instance = _instance
             self.version  = ProtocolVersion
@@ -218,7 +221,7 @@ class MessageLSR(object):
     def __init__(self, body, _id=None):
         if body:
             self.id = getMandatory(body, 'id', str)
-            self.version = getOptional(body, 'pv', 0, long)
+            self.version = getOptional(body, 'pv', 0, PY_LONG_TYPE)
             self.area = '0'
         else:
             self.id = _id
@@ -243,9 +246,9 @@ class MessageMAU(object):
     def __init__(self, body, _id=None, _seq=None, _add_list=None, _del_list=None, _exist_list=None):
         if body:
             self.id = getMandatory(body, 'id', str)
-            self.version = getOptional(body, 'pv', 0, long)
+            self.version = getOptional(body, 'pv', 0, PY_LONG_TYPE)
             self.area = '0'
-            self.mobile_seq = getMandatory(body, 'mobile_seq', long)
+            self.mobile_seq = getMandatory(body, 'mobile_seq', PY_LONG_TYPE)
             self.add_list = getOptional(body, 'add', None, list)
             self.del_list = getOptional(body, 'del', None, list)
             self.exist_list = getOptional(body, 'exist', None, list)
@@ -253,7 +256,7 @@ class MessageMAU(object):
             self.id = _id
             self.version = ProtocolVersion
             self.area = '0'
-            self.mobile_seq = long(_seq)
+            self.mobile_seq = LONG(_seq)
             self.add_list = _add_list
             self.del_list = _del_list
             self.exist_list = _exist_list
@@ -288,14 +291,14 @@ class MessageMAR(object):
     def __init__(self, body, _id=None, _have_seq=None):
         if body:
             self.id = getMandatory(body, 'id', str)
-            self.version = getOptional(body, 'pv', 0, long)
+            self.version = getOptional(body, 'pv', 0, PY_LONG_TYPE)
             self.area = '0'
-            self.have_seq = getMandatory(body, 'have_seq', long)
+            self.have_seq = getMandatory(body, 'have_seq', PY_LONG_TYPE)
         else:
             self.id = _id
             self.version = ProtocolVersion
             self.area = '0'
-            self.have_seq = long(_have_seq)
+            self.have_seq = LONG(_have_seq)
 
     def get_opcode(self):
         return 'MAR'

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/python/qpid_dispatch_internal/router/engine.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/router/engine.py b/python/qpid_dispatch_internal/router/engine.py
index aefaa5c..ef099be 100644
--- a/python/qpid_dispatch_internal/router/engine.py
+++ b/python/qpid_dispatch_internal/router/engine.py
@@ -17,13 +17,13 @@
 # under the License.
 #
 
-from data import MessageHELLO, MessageRA, MessageLSU, MessageMAU, MessageMAR, MessageLSR
-from hello import HelloProtocol
-from link import LinkStateEngine
-from path import PathEngine
-from mobile import MobileAddressEngine
-from node import NodeTracker
-from message import Message
+from .data import MessageHELLO, MessageRA, MessageLSU, MessageMAU, MessageMAR, MessageLSR
+from .hello import HelloProtocol
+from .link import LinkStateEngine
+from .path import PathEngine
+from .mobile import MobileAddressEngine
+from .node import NodeTracker
+from .message import Message
 
 from traceback import format_exc, extract_stack
 import time
@@ -35,7 +35,7 @@ import time
 from ..dispatch import IoAdapter, LogAdapter, LOG_TRACE, LOG_INFO, LOG_ERROR, LOG_STACK_LIMIT
 from ..dispatch import TREATMENT_MULTICAST_FLOOD, TREATMENT_MULTICAST_ONCE
 
-class RouterEngine:
+class RouterEngine(object):
     """
     """
 
@@ -60,7 +60,7 @@ class RouterEngine:
                                IoAdapter(self.receive, "qdhello",     'L', '0', TREATMENT_MULTICAST_FLOOD)]
         self.max_routers    = max_routers
         self.id             = router_id
-        self.instance       = long(time.time())
+        self.instance       = int(time.time())
         self.area           = area
         self.log(LOG_INFO, "Router Engine Instantiated: id=%s instance=%d max_routers=%d" %
                  (self.id, self.instance, self.max_routers))
@@ -87,8 +87,10 @@ class RouterEngine:
     @property
     def config(self):
         if not self._config:
-            try: self._config = self.router_adapter.get_agent().find_entity_by_type('router')[0]
-            except IndexError: raise ValueError("No router configuration found")
+            try:
+                self._config = self.router_adapter.get_agent().find_entity_by_type('router')[0]
+            except IndexError:
+                raise ValueError("No router configuration found")
         return self._config
 
     def addressAdded(self, addr):

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/python/qpid_dispatch_internal/router/hello.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/router/hello.py b/python/qpid_dispatch_internal/router/hello.py
index 177e578..6b21bc8 100644
--- a/python/qpid_dispatch_internal/router/hello.py
+++ b/python/qpid_dispatch_internal/router/hello.py
@@ -17,8 +17,11 @@
 # under the License.
 #
 
-from data import MessageHELLO
-from qpid_dispatch_internal.dispatch import LOG_INFO, LOG_TRACE, LOG_CRITICAL
+from .data import MessageHELLO
+from ..dispatch import LOG_INFO, LOG_TRACE, LOG_CRITICAL
+from ..compat import dict_keys
+from ..compat import dict_items
+
 
 class HelloProtocol(object):
     """
@@ -41,7 +44,7 @@ class HelloProtocol(object):
         self.ticks += 1.0
         if self.ticks - self.last_hello_ticks >= self.hello_interval:
             self.last_hello_ticks = self.ticks
-            msg = MessageHELLO(None, self.id, self.hellos.keys(), self.container.instance)
+            msg = MessageHELLO(None, self.id, dict_keys(self.hellos), self.container.instance)
             self.container.send('amqp:/_local/qdhello', msg)
             self.container.log_hello(LOG_TRACE, "SENT: %r" % msg)
 
@@ -62,7 +65,7 @@ class HelloProtocol(object):
         Expire local records of received hellos.  This is not involved in the
         expiration of neighbor status for routers.
         """
-        for key, last_seen in self.hellos.items():
+        for key, last_seen in dict_items(self.hellos):
             if now - last_seen > self.hello_max_age:
                 self.hellos.pop(key)
                 self.container.log_hello(LOG_TRACE, "HELLO peer expired: %s" % key)

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/python/qpid_dispatch_internal/router/link.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/router/link.py b/python/qpid_dispatch_internal/router/link.py
index ee051a0..09c4dfd 100644
--- a/python/qpid_dispatch_internal/router/link.py
+++ b/python/qpid_dispatch_internal/router/link.py
@@ -17,7 +17,7 @@
 # under the License.
 #
 
-from data import MessageRA, MessageLSU, MessageLSR
+from .data import MessageRA, MessageLSU, MessageLSR
 from ..dispatch import LOG_TRACE
 
 class LinkStateEngine(object):

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/python/qpid_dispatch_internal/router/mobile.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/router/mobile.py b/python/qpid_dispatch_internal/router/mobile.py
index 2592fe2..c29d038 100644
--- a/python/qpid_dispatch_internal/router/mobile.py
+++ b/python/qpid_dispatch_internal/router/mobile.py
@@ -17,7 +17,7 @@
 # under the License.
 #
 
-from data import MessageMAR, MessageMAU
+from .data import MessageMAR, MessageMAU
 from ..dispatch import LOG_TRACE
 
 MAX_KEPT_DELTAS = 10

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/python/qpid_dispatch_internal/router/node.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/router/node.py b/python/qpid_dispatch_internal/router/node.py
index 619d88a..68d40ef 100644
--- a/python/qpid_dispatch_internal/router/node.py
+++ b/python/qpid_dispatch_internal/router/node.py
@@ -18,8 +18,10 @@
 #
 
 from ..dispatch import LOG_INFO, LOG_TRACE, LOG_DEBUG
-from data import LinkState, ProtocolVersion
+from .data import LinkState, ProtocolVersion
 from .address import Address
+from ..compat import dict_items
+
 
 class NodeTracker(object):
     """
@@ -70,7 +72,7 @@ class NodeTracker(object):
         """
         Run through the list of routers and check for expired conditions
         """
-        for node_id, node in self.nodes.items():
+        for node_id, node in dict_items(self.nodes):
             ##
             ## If the node is a neighbor, check the neighbor refresh time to see
             ## if we've waited too long for a refresh.  If so, disconnect the link
@@ -275,7 +277,7 @@ class NodeTracker(object):
         ##
         ## Add the version if we haven't already done so.
         ##
-        if node.version == None:
+        if node.version is None:
             node.version = version
 
         ##
@@ -328,7 +330,7 @@ class NodeTracker(object):
         ##
         ## Add the version if we haven't already done so.
         ##
-        if node.version == None:
+        if node.version is None:
             node.version = version
 
         ##
@@ -361,13 +363,13 @@ class NodeTracker(object):
 
 
     def _allocate_maskbit(self):
-        if self.next_maskbit == None:
+        if self.next_maskbit is None:
             raise Exception("Exceeded Maximum Router Count")
         result = self.next_maskbit
         self.next_maskbit = None
         self.maskbits[result] = True
         for n in range(result + 1, self.max_routers):
-            if self.maskbits[n] == None:
+            if self.maskbits[n] is None:
                 self.next_maskbit = n
                 break
         return result
@@ -375,7 +377,7 @@ class NodeTracker(object):
 
     def _free_maskbit(self, i):
         self.maskbits[i] = None
-        if self.next_maskbit == None or i < self.next_maskbit:
+        if self.next_maskbit is None or i < self.next_maskbit:
             self.next_maskbit = i
 
 
@@ -444,7 +446,7 @@ class RouterNode(object):
 
 
     def remove_link(self):
-        if self.peer_link_id != None:
+        if self.peer_link_id is not None:
             self.peer_link_id = None
             self.adapter.remove_link(self.maskbit)
             self.log(LOG_TRACE, "Node %s link removed" % self.id)
@@ -498,7 +500,7 @@ class RouterNode(object):
 
 
     def is_neighbor(self):
-        return self.peer_link_id != None
+        return self.peer_link_id is not None
 
 
     def request_link_state(self):
@@ -515,7 +517,8 @@ class RouterNode(object):
         reachable.  There's no point in sending it a request if we don't know how to
         reach it.
         """
-        if self.need_ls_request and (self.peer_link_id != None or self.next_hop_router != None):
+        if self.need_ls_request and (self.peer_link_id is not None or
+                                     self.next_hop_router is not None):
             self.need_ls_request = False
             return True
         return False
@@ -526,7 +529,8 @@ class RouterNode(object):
 
 
     def mobile_address_requested(self):
-        if self.need_mobile_request and (self.peer_link_id != None or self.next_hop_router != None):
+        if self.need_mobile_request and (self.peer_link_id is not None or
+                                         self.next_hop_router is not None):
             self.need_mobile_request = False
             return True
         return False
@@ -566,9 +570,9 @@ class RouterNode(object):
 
 
     def update_instance(self, instance, version):
-        if instance == None:
+        if instance is None:
             return False
-        if self.instance == None:
+        if self.instance is None:
             self.instance = instance
             return False
         if self.instance == instance:

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/python/qpid_dispatch_internal/router/path.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/router/path.py b/python/qpid_dispatch_internal/router/path.py
index 4e215e2..548f4e8 100644
--- a/python/qpid_dispatch_internal/router/path.py
+++ b/python/qpid_dispatch_internal/router/path.py
@@ -17,6 +17,8 @@
 # under the License.
 #
 
+from ..compat import dict_items
+from ..compat import dict_keys
 
 class PathEngine(object):
     """
@@ -40,7 +42,7 @@ class PathEngine(object):
             link_states[_id] = ls.peers
             for p in ls.peers:
                 if p not in link_states:
-                    link_states[p] = {_id:1L}
+                    link_states[p] = {_id:1}
 
         ##
         ## Setup Dijkstra's Algorithm
@@ -77,7 +79,7 @@ class PathEngine(object):
         ## Remove unreachable nodes from the maps.  Note that this will also remove the
         ## root node (has no previous node) from the map.
         ##
-        for u, val in prev.items():
+        for u, val in dict_items(prev):
             if not val:
                 prev.pop(u)
                 hops.pop(u)
@@ -101,9 +103,9 @@ class PathEngine(object):
             if node != self.id:
                 valid_origin[node] = []
 
-        for root in valid_origin.keys():
+        for root in dict_keys(valid_origin):
             prev, cost, hops = self._calculate_tree_from_root(root, collection)
-            nodes = prev.keys()
+            nodes = dict_keys(prev)
             while len(nodes) > 0:
                 u = nodes[0]
                 path = [u]
@@ -127,7 +129,7 @@ class PathEngine(object):
         ## Generate the shortest-path tree with the local node as root
         ##
         prev, cost, hops = self._calculate_tree_from_root(self.id, collection)
-        nodes = prev.keys()
+        nodes = dict_keys(prev)
 
         ##
         ## We will also compute the radius of the topology.  This is the number of
@@ -156,7 +158,7 @@ class PathEngine(object):
         ##
         ## Calculate the valid origins for remote routers
         ##
-        valid_origins = self._calculate_valid_origins(prev.keys(), collection)
+        valid_origins = self._calculate_valid_origins(dict_keys(prev), collection)
 
         return (next_hops, cost, valid_origins, radius)
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/python/qpid_dispatch_internal/tools/command.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/tools/command.py b/python/qpid_dispatch_internal/tools/command.py
index 22415ee..6153c9e 100644
--- a/python/qpid_dispatch_internal/tools/command.py
+++ b/python/qpid_dispatch_internal/tools/command.py
@@ -20,6 +20,7 @@
 """
 Utilities for command-line programs.
 """
+from __future__ import print_function
 
 import sys, json, optparse, os
 from collections import Sequence, Mapping
@@ -44,13 +45,13 @@ def main(run, argv=sys.argv, op=None):
         run(argv)
         return 0
     except KeyboardInterrupt:
-        print
-    except UsageError, e:
+        print()
+    except UsageError as e:
         op.error(e)
-    except Exception, e:
+    except Exception as e:
         if "_QPID_DISPATCH_TOOLS_DEBUG_" in os.environ:
             raise
-        print "%s: %s" % (type(e).__name__, e)
+        print("%s: %s" % (type(e).__name__, e))
     return 1
 
 def check_args(args, maxargs=0, minargs=0):
@@ -194,7 +195,7 @@ class OptionParser(optparse.OptionParser):
     def __init__(self, *args, **kwargs):
         optparse.OptionParser.__init__(self, *args, **kwargs)
         def version_cb(*args):
-            print VERSION
+            print("%s" % VERSION)
             exit(0)
 
         self.add_option("--version", help="Print version and exit.",

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/python/qpid_dispatch_internal/tools/display.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/tools/display.py b/python/qpid_dispatch_internal/tools/display.py
index b9d38bc..86d67ac 100644
--- a/python/qpid_dispatch_internal/tools/display.py
+++ b/python/qpid_dispatch_internal/tools/display.py
@@ -17,7 +17,11 @@
 # under the License.
 #
 
+from __future__ import print_function
+
 from time import strftime, gmtime
+from qpid_dispatch_internal.compat import UNICODE
+
 
 def YN(val):
   if val:
@@ -156,7 +160,7 @@ class Display:
       for idx in range(diff):
         row.append("")
 
-    print title
+    print("%s" % title)
     if len (rows) == 0:
       return
     colWidth = []
@@ -165,10 +169,8 @@ class Display:
     for head in heads:
       width = len (head)
       for row in rows:
-        text = row[col]
-        if text.__class__ == str:
-          text = text.decode('utf-8')
-        cellWidth = len(unicode(text))
+        text = UNICODE(row[col])
+        cellWidth = len(text)
         if cellWidth > width:
           width = cellWidth
       colWidth.append (width + self.tableSpacing)
@@ -177,26 +179,24 @@ class Display:
         for i in range (colWidth[col] - len (head)):
           line = line + " "
       col = col + 1
-    print line
+    print(line)
     line = self.tablePrefix
     for width in colWidth:
       for i in range (width):
         line = line + "="
-    print line
+    print(line)
 
     for row in rows:
       line = self.tablePrefix
       col  = 0
       for width in colWidth:
-        text = row[col]
-        if text.__class__ == str:
-          text = text.decode('utf-8')
-        line = line + unicode(text)
+        text = UNICODE(row[col])
+        line = line + text
         if col < len (heads) - 1:
-          for i in range (width - len(unicode(text))):
+          for i in range (width - len(text)):
             line = line + " "
         col = col + 1
-      print line
+      print(line)
 
   def do_setTimeFormat (self, fmt):
     """ Select timestamp format """
@@ -225,7 +225,7 @@ class Display:
     result += "%ds" % (sec % 60)
     return result
 
-class Sortable:
+class Sortable(object):
   """ """
   def __init__(self, row, sortIndex):
     self.row = row
@@ -233,8 +233,8 @@ class Sortable:
     if sortIndex >= len(row):
       raise Exception("sort index exceeds row boundary")
 
-  def __cmp__(self, other):
-    return cmp(self.row[self.sortIndex], other.row[self.sortIndex])
+  def __lt__(self, other):
+    return self.row[self.sortIndex] < other.row[self.sortIndex]
 
   def getRow(self):
     return self.row

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/run.py.in
----------------------------------------------------------------------
diff --git a/run.py.in b/run.py.in
index 292e57c..5f050e2 100755
--- a/run.py.in
+++ b/run.py.in
@@ -18,6 +18,7 @@
 ## under the License
 ##
 
+from __future__ import print_function
 
 """
 Run a tool or test in a build tree with the correct PATH, PYTHONPATH, etc.
@@ -108,7 +109,7 @@ if __name__ == "__main__":
     error_prefix = ""
     try:
         if len(sys.argv) == 1:
-            print usage
+            print("%s" % usage)
         elif sys.argv[1] == '-m':
             sys.argv = sys.argv[2:]
             error_prefix = "Run python module '%s': "%(sys.argv[0])
@@ -118,19 +119,19 @@ if __name__ == "__main__":
             error_prefix = "Run python script '%s':"%(sys.argv[0])
             run_path(sys.argv[0], run_name="__main__")
         elif sys.argv[1] == '--sh':
-            for name, value in env_vars.iteritems(): print '%s="%s"'%(name, value)
-            print "export %s"%' '.join(env_vars.keys())
+            for name, value in env_vars.items(): print('%s="%s"'%(name, value))
+            print("export %s"%' '.join(env_vars.keys()))
         elif sys.argv[1] == '-x':
             args = test_runner.split() + sys.argv[2:]
             error_prefix = "Running '%s': "%(args)
             os.execvp(args[0], args)
         elif sys.argv[1].startswith('-'):
-            print usage
+            print(usage)
         else:
             args = sys.argv[1:]
             error_prefix = "Running '%s': "%(args)
             os.execvp(args[0], args)
-    except Exception, e:
-        print "%s%s: %s"%(error_prefix, type(e).__name__, e)
+    except Exception as e:
+        print("%s%s: %s"%(error_prefix, type(e).__name__, e))
         raise
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/src/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index ac85bca..bc132dd 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -101,6 +101,7 @@ set(qpid_dispatch_SOURCES
   server.c
   timer.c
   trace_mask.c
+  python_utils.c
   )
 
 # USE_LIBWEBSOCKETS is true only if LIBWEBSOCKETS_FOUND

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/878534ec/src/entity.c
----------------------------------------------------------------------
diff --git a/src/entity.c b/src/entity.c
index d461fc5..9128752 100644
--- a/src/entity.c
+++ b/src/entity.c
@@ -18,17 +18,17 @@
  */
 
 
-#include <Python.h>
 #include <qpid/dispatch/error.h>
 #include "dispatch_private.h"
 #include "entity.h"
+#include "python_private.h"
 
 struct qd_entity_t {
     PyObject py_object;      /* Any object supporting __set/get_item__, e.g. dict. */
 };
 
 static PyObject* qd_entity_get_py(qd_entity_t* entity, const char* attribute) {
-    PyObject *py_key = PyString_FromString(attribute);
+    PyObject *py_key = PyUnicode_FromString(attribute);
     if (!py_key) return NULL;   /* Don't set qd_error, caller will set if needed. */
     PyObject *value = PyObject_GetItem((PyObject*)entity, py_key);
     Py_DECREF(py_key);
@@ -45,11 +45,8 @@ bool qd_entity_has(qd_entity_t* entity, const char *attribute) {
 char *qd_entity_get_string(qd_entity_t *entity, const char* attribute) {
     qd_error_clear();
     PyObject *py_obj = qd_entity_get_py(entity, attribute);
-    PyObject *py_str = py_obj ? PyObject_Str(py_obj) : NULL;
-    const char *cstr = py_str ? PyString_AsString(py_str) : NULL;
-    char* str = cstr ? strdup(cstr) : NULL;
+    char *str = py_string_2_c(py_obj);
     Py_XDECREF(py_obj);
-    Py_XDECREF(py_str);
     if (!str) qd_error_py();
     return str;
 }
@@ -57,7 +54,7 @@ char *qd_entity_get_string(qd_entity_t *entity, const char* attribute) {
 long qd_entity_get_long(qd_entity_t *entity, const char* attribute) {
     qd_error_clear();
     PyObject *py_obj = qd_entity_get_py(entity, attribute);
-    long result = py_obj ? PyInt_AsLong(py_obj) : -1;
+    long result = py_obj ? PyLong_AsLong(py_obj) : -1;
     Py_XDECREF(py_obj);
     qd_error_py();
     return result;
@@ -110,7 +107,7 @@ qd_error_t qd_entity_set_py(qd_entity_t* entity, const char* attribute, PyObject
     qd_error_clear();
 
     int result = 0;
-    PyObject *py_key = PyString_FromString(attribute);
+    PyObject *py_key = PyUnicode_FromString(attribute);
     if (py_key) {
         if (py_value == NULL) {     /* Delete the attribute */
             result = PyObject_DelItem((PyObject*)entity, py_key);
@@ -132,11 +129,11 @@ qd_error_t qd_entity_set_py(qd_entity_t* entity, const char* attribute, PyObject
 }
 
 qd_error_t qd_entity_set_string(qd_entity_t *entity, const char* attribute, const char *value) {
-    return qd_entity_set_py(entity, attribute, value ? PyString_FromString(value) : 0);
+    return qd_entity_set_py(entity, attribute, value ? PyUnicode_FromString(value) : 0);
 }
 
 qd_error_t qd_entity_set_longp(qd_entity_t *entity, const char* attribute, const long *value) {
-    return qd_entity_set_py(entity, attribute, value ? PyInt_FromLong(*value) : 0);
+    return qd_entity_set_py(entity, attribute, value ? PyLong_FromLong(*value) : 0);
 }
 
 qd_error_t qd_entity_set_boolp(qd_entity_t *entity, const char *attribute, const bool *value) {
@@ -173,9 +170,9 @@ qd_error_t qd_entity_set_map_key_value_int(qd_entity_t *entity, const char *attr
     if (!key)
         return  QD_ERROR_VALUE;
 
-    PyObject *py_key = PyString_FromString(key);
-    PyObject *py_value = PyInt_FromLong(value);
-    PyObject *py_attribute = PyString_FromString(attribute);
+    PyObject *py_key = PyUnicode_FromString(key);
+    PyObject *py_value = PyLong_FromLong(value);
+    PyObject *py_attribute = PyUnicode_FromString(attribute);
 
     qd_error_t ret = QD_ERROR_NONE;
 
@@ -199,9 +196,9 @@ qd_error_t qd_entity_set_map_key_value_string(qd_entity_t *entity, const char *a
     if (!key)
         return  QD_ERROR_VALUE;
 
-    PyObject *py_key = PyString_FromString(key);
-    PyObject *py_value = PyString_FromString(value);
-    PyObject *py_attribute = PyString_FromString(attribute);
+    PyObject *py_key = PyUnicode_FromString(key);
+    PyObject *py_value = PyUnicode_FromString(value);
+    PyObject *py_attribute = PyUnicode_FromString(attribute);
 
     qd_error_t ret = QD_ERROR_NONE;
 


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org


[04/11] qpid-dispatch git commit: DISPATCH-965: fixups for Python 2.7 compatibility

Posted by kg...@apache.org.
DISPATCH-965: fixups for Python 2.7 compatibility


Project: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/repo
Commit: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/commit/7bdd55c7
Tree: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/tree/7bdd55c7
Diff: http://git-wip-us.apache.org/repos/asf/qpid-dispatch/diff/7bdd55c7

Branch: refs/heads/master
Commit: 7bdd55c7db7b010f204750c0e39fbc067180d26a
Parents: 878534e
Author: Kenneth Giusti <kg...@apache.org>
Authored: Sun May 13 21:11:31 2018 -0400
Committer: Kenneth Giusti <kg...@apache.org>
Committed: Sun May 13 21:11:31 2018 -0400

----------------------------------------------------------------------
 console/config/config.py                        |  5 +++
 console/config/mock/schema.py                   |  5 +++
 console/config/mock/section.py                  |  5 +++
 .../dispatch-dashboard/dispatch/dashboard.py    |  5 +++
 .../dispatch-dashboard/dispatch/overv/panel.py  |  5 +++
 .../dispatch-dashboard/dispatch/overv/tests.py  |  5 +++
 .../dispatch-dashboard/dispatch/overv/urls.py   |  5 +++
 .../dispatch-dashboard/dispatch/overv/views.py  |  5 +++
 .../dispatch/topology/panel.py                  |  5 +++
 .../dispatch/topology/tests.py                  |  5 +++
 .../dispatch/topology/urls.py                   |  5 +++
 .../dispatch/topology/views.py                  |  5 +++
 .../enabled/_4000_dispatch.py                   |  5 +++
 .../enabled/_4030_dispatch_overv_panel.py       |  5 +++
 .../enabled/_4050_dispatch_topology_panel.py    |  4 ++
 doc/book/schema_txt.py                          |  4 ++
 doc/man/help2txt.py                             |  5 +++
 doc/man/qdrouterd.conf.5.py                     |  5 +++
 python/qpid_dispatch/management/client.py       |  5 +++
 python/qpid_dispatch/management/entity.py       |  5 +++
 python/qpid_dispatch/management/error.py        |  5 +++
 .../qpid_dispatch_internal/compat/__init__.py   |  5 +++
 .../compat/ordereddict.py                       |  6 +++
 python/qpid_dispatch_internal/compat/subproc.py |  4 ++
 python/qpid_dispatch_internal/dispatch.py       |  5 +++
 .../display_name/display_name.py                |  7 ++++
 .../qpid_dispatch_internal/management/agent.py  | 10 +++--
 .../qpid_dispatch_internal/management/config.py |  5 +++
 .../management/qdrouter.py                      |  4 ++
 .../qpid_dispatch_internal/management/schema.py |  6 +++
 .../management/schema_doc.py                    |  3 ++
 .../policy/policy_local.py                      |  4 ++
 .../policy/policy_manager.py                    |  5 +++
 .../policy/policy_util.py                       |  7 +++-
 .../qpid_dispatch_internal/router/__init__.py   |  5 +++
 python/qpid_dispatch_internal/router/address.py |  5 ++-
 python/qpid_dispatch_internal/router/data.py    | 21 ++++++----
 python/qpid_dispatch_internal/router/engine.py  |  5 +++
 python/qpid_dispatch_internal/router/hello.py   |  5 +++
 python/qpid_dispatch_internal/router/link.py    |  5 +++
 python/qpid_dispatch_internal/router/message.py |  5 +++
 python/qpid_dispatch_internal/router/mobile.py  |  5 +++
 python/qpid_dispatch_internal/router/node.py    |  5 +++
 python/qpid_dispatch_internal/router/path.py    |  5 +++
 python/qpid_dispatch_internal/tools/__init__.py |  5 +++
 python/qpid_dispatch_internal/tools/command.py  |  3 ++
 python/qpid_dispatch_internal/tools/display.py  |  3 ++
 python/qpid_dispatch_site.py.in                 |  4 ++
 run.py.in                                       |  3 ++
 src/entity.c                                    |  2 +-
 src/error.c                                     |  8 +---
 src/log.c                                       |  3 +-
 src/python_embedded.c                           | 41 ++++++++++----------
 src/python_private.h                            |  2 +-
 src/schema_c.py                                 |  4 ++
 src/server.c                                    |  6 ++-
 tests/authservice.py                            |  6 ++-
 tests/management/entity.py                      |  5 +++
 tests/management/qdrouter.py                    |  5 +++
 tests/management/schema.py                      |  5 +++
 tests/mock/__init__.py                          |  4 ++
 tests/mock/dispatch.py                          |  5 +++
 tests/router_engine_test.py                     |  3 ++
 tests/router_policy_test.py                     |  3 ++
 tests/run_system_tests.py                       |  4 ++
 tests/system_test.py                            |  4 ++
 tests/system_tests_auth_service_plugin.py       |  4 ++
 tests/system_tests_authz_service_plugin.py      |  5 +++
 tests/system_tests_autolinks.py                 |  6 +++
 tests/system_tests_bad_configuration.py         |  6 +++
 tests/system_tests_broker.py                    |  7 ++++
 tests/system_tests_cmdline_parsing.py           |  5 +++
 tests/system_tests_default_distribution.py      |  5 +++
 tests/system_tests_delivery_abort.py            |  5 +++
 tests/system_tests_deprecated.py                |  5 +++
 ..._tests_disallow_link_resumable_link_route.py |  5 +++
 tests/system_tests_distribution.py              |  3 ++
 tests/system_tests_drain.py                     |  5 +++
 tests/system_tests_drain_support.py             |  7 +++-
 tests/system_tests_dynamic_terminus.py          |  5 +++
 tests/system_tests_exchange_bindings.py         |  5 +++
 tests/system_tests_failover_list.py             |  5 +++
 tests/system_tests_handle_failover.py           |  5 +++
 tests/system_tests_http.py                      |  4 ++
 tests/system_tests_link_routes.py               |  7 +++-
 tests/system_tests_log_message_components.py    |  5 +++
 tests/system_tests_management.py                |  5 +++
 tests/system_tests_multi_tenancy.py             |  5 +++
 tests/system_tests_one_router.py                |  9 ++++-
 tests/system_tests_policy.py                    |  9 ++++-
 tests/system_tests_protocol_family.py           |  7 +++-
 tests/system_tests_protocol_settings.py         |  5 +++
 tests/system_tests_qdmanage.py                  |  7 +++-
 tests/system_tests_qdstat.py                    |  5 +++
 tests/system_tests_sasl_plain.py                |  5 +++
 tests/system_tests_topology.py                  |  3 ++
 tests/system_tests_topology_addition.py         |  5 +++
 tests/system_tests_topology_disposition.py      |  3 ++
 tests/system_tests_two_routers.py               |  5 +++
 tests/system_tests_user_id.py                   |  4 ++
 tests/system_tests_user_id_proxy.py             |  4 ++
 tools/qdmanage                                  |  3 ++
 tools/qdstat                                    |  3 ++
 tox.ini                                         |  7 ++--
 104 files changed, 512 insertions(+), 54 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/console/config/config.py
----------------------------------------------------------------------
diff --git a/console/config/config.py b/console/config/config.py
index ae51bd7..1f768f5 100755
--- a/console/config/config.py
+++ b/console/config/config.py
@@ -18,6 +18,11 @@
 # under the License.
 #
 
+from __future__ import print_function
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+
 import argparse
 from pprint import pprint
 import os, sys, inspect

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/console/config/mock/schema.py
----------------------------------------------------------------------
diff --git a/console/config/mock/schema.py b/console/config/mock/schema.py
index 524164b..880f225 100644
--- a/console/config/mock/schema.py
+++ b/console/config/mock/schema.py
@@ -18,6 +18,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import json
 
 class Schema(object):

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/console/config/mock/section.py
----------------------------------------------------------------------
diff --git a/console/config/mock/section.py b/console/config/mock/section.py
index ac5b154..1e563be 100644
--- a/console/config/mock/section.py
+++ b/console/config/mock/section.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import print_function
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+
 import json
 import re
 from schema import Schema

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/console/dispatch-dashboard/dispatch/dashboard.py
----------------------------------------------------------------------
diff --git a/console/dispatch-dashboard/dispatch/dashboard.py b/console/dispatch-dashboard/dispatch/dashboard.py
index 9fad953..f3212e1 100644
--- a/console/dispatch-dashboard/dispatch/dashboard.py
+++ b/console/dispatch-dashboard/dispatch/dashboard.py
@@ -10,6 +10,11 @@
 # License for the specific language governing permissions and limitations
 # under the License.
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 from django.utils.translation import ugettext_lazy as _
 
 import horizon

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/console/dispatch-dashboard/dispatch/overv/panel.py
----------------------------------------------------------------------
diff --git a/console/dispatch-dashboard/dispatch/overv/panel.py b/console/dispatch-dashboard/dispatch/overv/panel.py
index 315c7e0..0032c76 100644
--- a/console/dispatch-dashboard/dispatch/overv/panel.py
+++ b/console/dispatch-dashboard/dispatch/overv/panel.py
@@ -10,6 +10,11 @@
 # License for the specific language governing permissions and limitations
 # under the License.
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 from django.utils.translation import ugettext_lazy as _
 
 import horizon

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/console/dispatch-dashboard/dispatch/overv/tests.py
----------------------------------------------------------------------
diff --git a/console/dispatch-dashboard/dispatch/overv/tests.py b/console/dispatch-dashboard/dispatch/overv/tests.py
index 47816a3..119b5a4 100644
--- a/console/dispatch-dashboard/dispatch/overv/tests.py
+++ b/console/dispatch-dashboard/dispatch/overv/tests.py
@@ -10,6 +10,11 @@
 # License for the specific language governing permissions and limitations
 # under the License.
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 from horizon.test import helpers as test
 
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/console/dispatch-dashboard/dispatch/overv/urls.py
----------------------------------------------------------------------
diff --git a/console/dispatch-dashboard/dispatch/overv/urls.py b/console/dispatch-dashboard/dispatch/overv/urls.py
index 6debf00..0dab119 100644
--- a/console/dispatch-dashboard/dispatch/overv/urls.py
+++ b/console/dispatch-dashboard/dispatch/overv/urls.py
@@ -10,6 +10,11 @@
 # License for the specific language governing permissions and limitations
 # under the License.
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 from django.conf.urls import url
 
 from dispatch.overv import views

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/console/dispatch-dashboard/dispatch/overv/views.py
----------------------------------------------------------------------
diff --git a/console/dispatch-dashboard/dispatch/overv/views.py b/console/dispatch-dashboard/dispatch/overv/views.py
index 235a0d5..28a7202 100644
--- a/console/dispatch-dashboard/dispatch/overv/views.py
+++ b/console/dispatch-dashboard/dispatch/overv/views.py
@@ -10,6 +10,11 @@
 # License for the specific language governing permissions and limitations
 # under the License.
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 from horizon import views
 
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/console/dispatch-dashboard/dispatch/topology/panel.py
----------------------------------------------------------------------
diff --git a/console/dispatch-dashboard/dispatch/topology/panel.py b/console/dispatch-dashboard/dispatch/topology/panel.py
index 6efbeda..db4eb11 100644
--- a/console/dispatch-dashboard/dispatch/topology/panel.py
+++ b/console/dispatch-dashboard/dispatch/topology/panel.py
@@ -10,6 +10,11 @@
 # License for the specific language governing permissions and limitations
 # under the License.
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 from django.utils.translation import ugettext_lazy as _
 
 import horizon

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/console/dispatch-dashboard/dispatch/topology/tests.py
----------------------------------------------------------------------
diff --git a/console/dispatch-dashboard/dispatch/topology/tests.py b/console/dispatch-dashboard/dispatch/topology/tests.py
index b321fc1..96a64c3 100644
--- a/console/dispatch-dashboard/dispatch/topology/tests.py
+++ b/console/dispatch-dashboard/dispatch/topology/tests.py
@@ -10,6 +10,11 @@
 # License for the specific language governing permissions and limitations
 # under the License.
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 from horizon.test import helpers as test
 
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/console/dispatch-dashboard/dispatch/topology/urls.py
----------------------------------------------------------------------
diff --git a/console/dispatch-dashboard/dispatch/topology/urls.py b/console/dispatch-dashboard/dispatch/topology/urls.py
index d8629f9..bdb499b 100644
--- a/console/dispatch-dashboard/dispatch/topology/urls.py
+++ b/console/dispatch-dashboard/dispatch/topology/urls.py
@@ -10,6 +10,11 @@
 # License for the specific language governing permissions and limitations
 # under the License.
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 from django.conf.urls import url
 
 from dispatch.topology import views

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/console/dispatch-dashboard/dispatch/topology/views.py
----------------------------------------------------------------------
diff --git a/console/dispatch-dashboard/dispatch/topology/views.py b/console/dispatch-dashboard/dispatch/topology/views.py
index 03b6012..cf1699c 100644
--- a/console/dispatch-dashboard/dispatch/topology/views.py
+++ b/console/dispatch-dashboard/dispatch/topology/views.py
@@ -10,6 +10,11 @@
 # License for the specific language governing permissions and limitations
 # under the License.
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 from horizon import views
 
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/console/dispatch-dashboard/enabled/_4000_dispatch.py
----------------------------------------------------------------------
diff --git a/console/dispatch-dashboard/enabled/_4000_dispatch.py b/console/dispatch-dashboard/enabled/_4000_dispatch.py
index 16d3215..f45e228 100644
--- a/console/dispatch-dashboard/enabled/_4000_dispatch.py
+++ b/console/dispatch-dashboard/enabled/_4000_dispatch.py
@@ -10,6 +10,11 @@
 #    License for the specific language governing permissions and limitations
 #    under the License.
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 # The name of the dashboard to be added to HORIZON['dashboards']. Required.
 DASHBOARD = 'dispatch'
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/console/dispatch-dashboard/enabled/_4030_dispatch_overv_panel.py
----------------------------------------------------------------------
diff --git a/console/dispatch-dashboard/enabled/_4030_dispatch_overv_panel.py b/console/dispatch-dashboard/enabled/_4030_dispatch_overv_panel.py
index b5d0446..1594fed 100644
--- a/console/dispatch-dashboard/enabled/_4030_dispatch_overv_panel.py
+++ b/console/dispatch-dashboard/enabled/_4030_dispatch_overv_panel.py
@@ -17,6 +17,11 @@
 # under the License
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 # The slug of the panel to be added to HORIZON_CONFIG. Required.
 PANEL = 'overv'
 # The slug of the dashboard the PANEL associated with. Required.

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/console/dispatch-dashboard/enabled/_4050_dispatch_topology_panel.py
----------------------------------------------------------------------
diff --git a/console/dispatch-dashboard/enabled/_4050_dispatch_topology_panel.py b/console/dispatch-dashboard/enabled/_4050_dispatch_topology_panel.py
index 37d408f..87e4549 100644
--- a/console/dispatch-dashboard/enabled/_4050_dispatch_topology_panel.py
+++ b/console/dispatch-dashboard/enabled/_4050_dispatch_topology_panel.py
@@ -17,6 +17,10 @@
 # under the License
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
 
 # The slug of the panel to be added to HORIZON_CONFIG. Required.
 PANEL = 'topology'

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/doc/book/schema_txt.py
----------------------------------------------------------------------
diff --git a/doc/book/schema_txt.py b/doc/book/schema_txt.py
index c9d5b1b..9f340f3 100644
--- a/doc/book/schema_txt.py
+++ b/doc/book/schema_txt.py
@@ -20,6 +20,10 @@
 """
 Generate the schema.md chapter for the dispatch book from the qdrouter.json schema.
 """
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
 
 import sys, re
 from qpid_dispatch_internal.management.qdrouter import QdSchema

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/doc/man/help2txt.py
----------------------------------------------------------------------
diff --git a/doc/man/help2txt.py b/doc/man/help2txt.py
index 0fb2f7f..24aeb53 100644
--- a/doc/man/help2txt.py
+++ b/doc/man/help2txt.py
@@ -21,6 +21,11 @@
 Convert --help output of a program into asciidoc text format.
 """
 from __future__ import print_function
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+
+
 import re, sys
 from qpid_dispatch_internal.compat import PY_STRING_TYPE
 from qpid_dispatch_internal.compat.subproc import check_output

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/doc/man/qdrouterd.conf.5.py
----------------------------------------------------------------------
diff --git a/doc/man/qdrouterd.conf.5.py b/doc/man/qdrouterd.conf.5.py
index efdb554..e2bdd8e 100644
--- a/doc/man/qdrouterd.conf.5.py
+++ b/doc/man/qdrouterd.conf.5.py
@@ -21,6 +21,11 @@
 Generate the qdrouterd.conf. man page from the qdrouterd management schema.
 """
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import sys
 from qpid_dispatch_internal.management.qdrouter import QdSchema
 from qpid_dispatch_internal.management.schema_doc import SchemaWriter

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch/management/client.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch/management/client.py b/python/qpid_dispatch/management/client.py
index a449e33..22ed58e 100644
--- a/python/qpid_dispatch/management/client.py
+++ b/python/qpid_dispatch/management/client.py
@@ -21,6 +21,11 @@
 AMQP management client for Qpid dispatch.
 """
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import qpid_dispatch_site
 import proton
 from proton import Url

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch/management/entity.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch/management/entity.py b/python/qpid_dispatch/management/entity.py
index 19df0e8..58ba836 100644
--- a/python/qpid_dispatch/management/entity.py
+++ b/python/qpid_dispatch/management/entity.py
@@ -21,6 +21,11 @@
 AMQP Managment Entity
 """
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import itertools, re
 import sys
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch/management/error.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch/management/error.py b/python/qpid_dispatch/management/error.py
index 0d73e92..9c2aa4b 100644
--- a/python/qpid_dispatch/management/error.py
+++ b/python/qpid_dispatch/management/error.py
@@ -21,6 +21,11 @@
 ManagementError exception class and subclasses, with status codes used by AMQP.
 """
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 #from httplib import responses as STATUS_TEXT
 #from httplib import OK, NO_CONTENT, CREATED, \
 #    BAD_REQUEST, UNAUTHORIZED, FORBIDDEN, NOT_FOUND, INTERNAL_SERVER_ERROR, NOT_IMPLEMENTED

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_internal/compat/__init__.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/compat/__init__.py b/python/qpid_dispatch_internal/compat/__init__.py
index 8af2d21..b37d5db 100644
--- a/python/qpid_dispatch_internal/compat/__init__.py
+++ b/python/qpid_dispatch_internal/compat/__init__.py
@@ -19,6 +19,11 @@
 
 """Compatibility hacks for older versions of python"""
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 __all__ = [
     "OrderedDict",
     "JSON_LOAD_KWARGS",

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_internal/compat/ordereddict.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/compat/ordereddict.py b/python/qpid_dispatch_internal/compat/ordereddict.py
index 2fa007d..3d67612 100644
--- a/python/qpid_dispatch_internal/compat/ordereddict.py
+++ b/python/qpid_dispatch_internal/compat/ordereddict.py
@@ -21,6 +21,12 @@
 # Passes Python2.7's test suite and incorporates all the latest updates.
 # From http://code.activestate.com/recipes/576693/
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
+
 try:
     from thread import get_ident as _get_ident
 except ImportError:

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_internal/compat/subproc.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/compat/subproc.py b/python/qpid_dispatch_internal/compat/subproc.py
index 7927961..8596297 100644
--- a/python/qpid_dispatch_internal/compat/subproc.py
+++ b/python/qpid_dispatch_internal/compat/subproc.py
@@ -20,6 +20,10 @@
 """
 Implementations of some handy subprocess functions missing in python 2.6
 """
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
 
 from subprocess import *
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_internal/dispatch.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/dispatch.py b/python/qpid_dispatch_internal/dispatch.py
index a8cd05b..9adc2f4 100644
--- a/python/qpid_dispatch_internal/dispatch.py
+++ b/python/qpid_dispatch_internal/dispatch.py
@@ -29,6 +29,11 @@ The C library also adds the following C extension types to this module:
 
 This module also prevents the proton python module from being accidentally loaded.
 """
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 
 import sys, ctypes
 from ctypes import c_char_p, c_long, py_object

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_internal/display_name/display_name.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/display_name/display_name.py b/python/qpid_dispatch_internal/display_name/display_name.py
index ba92e76..2f3c5dc 100644
--- a/python/qpid_dispatch_internal/display_name/display_name.py
+++ b/python/qpid_dispatch_internal/display_name/display_name.py
@@ -23,6 +23,13 @@ user nick name.
 Maintains a dict (profile_dict) of ssl profile names to SSLProfile objects. The SSLProfile objects are built using
 the file name which contains a mapping of user identifiers to user names.
 """
+
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
+
 import traceback
 from traceback import format_exc
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_internal/management/agent.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/management/agent.py b/python/qpid_dispatch_internal/management/agent.py
index 6d737bb..da9cded 100644
--- a/python/qpid_dispatch_internal/management/agent.py
+++ b/python/qpid_dispatch_internal/management/agent.py
@@ -61,6 +61,10 @@ When refreshing attributes, the agent must also read C implementation object
 data that may be updated in other threads.
 
 """
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
 
 import traceback, json, pstats
 import socket
@@ -96,7 +100,7 @@ from qpid_dispatch_internal.compat import dict_iteritems
 
 def dictstr(d):
     """Stringify a dict in the form 'k=v, k=v ...' instead of '{k:v, ...}'"""
-    return ", ".join("%s=%r" % (k, v) for k, v in dict_iteritems(d))
+    return ", ".join("%s=%s" % (k, v) for k, v in dict_iteritems(d))
 
 def required_property(prop, request):
     """Raise exception if required property is missing"""
@@ -923,7 +927,7 @@ class Agent(object):
 
         def attrvals():
             """String form of the id attribute values for error messages"""
-            return " ".join(["%s=%r" % (k, v) for k, v in dict_iteritems(ids)])
+            return " ".join(["%s=%s" % (k, v) for k, v in dict_iteritems(ids)])
 
         k, v = next(dict_iteritems(ids)) # Get the first id attribute
         found = self.entities.map_filter(None, lambda e: e.attributes.get(k) == v)
@@ -931,7 +935,7 @@ class Agent(object):
             entity = found[0]
         elif len(found) > 1:
             raise InternalServerErrorStatus(
-                "Duplicate (%s) entities with %s=%r" % (len(found), k, v))
+                "Duplicate (%s) entities with %s=%s" % (len(found), k, v))
         else:
             raise NotFoundStatus("No entity with %s" % attrvals())
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_internal/management/config.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/management/config.py b/python/qpid_dispatch_internal/management/config.py
index 24a6f04..cd7fdfa 100644
--- a/python/qpid_dispatch_internal/management/config.py
+++ b/python/qpid_dispatch_internal/management/config.py
@@ -20,6 +20,11 @@
 """
 Configuration file parsing
 """
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 
 import json, re, sys
 import os

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_internal/management/qdrouter.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/management/qdrouter.py b/python/qpid_dispatch_internal/management/qdrouter.py
index e26b96b..616d903 100644
--- a/python/qpid_dispatch_internal/management/qdrouter.py
+++ b/python/qpid_dispatch_internal/management/qdrouter.py
@@ -20,6 +20,10 @@
 """
 Qpid Dispatch Router management schema and config file parsing.
 """
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
 
 import json
 from pkgutil import get_data

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_internal/management/schema.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/management/schema.py b/python/qpid_dispatch_internal/management/schema.py
index 6e619e7..227f96a 100644
--- a/python/qpid_dispatch_internal/management/schema.py
+++ b/python/qpid_dispatch_internal/management/schema.py
@@ -26,6 +26,12 @@ check for uniqueness of enties/attributes that are specified to be unique.
 A Schema can be loaded/dumped to a json file.
 """
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
+
 import sys
 import traceback
 from qpid_dispatch.management.entity import EntityBase

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_internal/management/schema_doc.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/management/schema_doc.py b/python/qpid_dispatch_internal/management/schema_doc.py
index d5bbf50..56cb929 100644
--- a/python/qpid_dispatch_internal/management/schema_doc.py
+++ b/python/qpid_dispatch_internal/management/schema_doc.py
@@ -19,6 +19,9 @@
 
 """Library for generating asciidoc documentation from a L{schema.Schema}"""
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
 from __future__ import print_function
 
 from collections import namedtuple

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_internal/policy/policy_local.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/policy/policy_local.py b/python/qpid_dispatch_internal/policy/policy_local.py
index 9218a56..0fda54c 100644
--- a/python/qpid_dispatch_internal/policy/policy_local.py
+++ b/python/qpid_dispatch_internal/policy/policy_local.py
@@ -20,6 +20,10 @@
 """
 
 """
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
 
 import json
 import pdb

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_internal/policy/policy_manager.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/policy/policy_manager.py b/python/qpid_dispatch_internal/policy/policy_manager.py
index 0445386..a5b352e 100644
--- a/python/qpid_dispatch_internal/policy/policy_manager.py
+++ b/python/qpid_dispatch_internal/policy/policy_manager.py
@@ -21,6 +21,11 @@
 
 """
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import json
 import traceback
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_internal/policy/policy_util.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/policy/policy_util.py b/python/qpid_dispatch_internal/policy/policy_util.py
index b74f7b5..b7a52cc 100644
--- a/python/qpid_dispatch_internal/policy/policy_util.py
+++ b/python/qpid_dispatch_internal/policy/policy_util.py
@@ -17,6 +17,11 @@
 # under the License
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import socket
 import binascii
 
@@ -26,7 +31,7 @@ class PolicyError(Exception):
     def __init__(self, value):
         self.value = value
     def __str__(self):
-        return repr(self.value)
+        return str(self.value)
 
 def is_ipv6_enabled():
     """

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_internal/router/__init__.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/router/__init__.py b/python/qpid_dispatch_internal/router/__init__.py
index 0c1682d..4acf3b2 100644
--- a/python/qpid_dispatch_internal/router/__init__.py
+++ b/python/qpid_dispatch_internal/router/__init__.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 from .engine import RouterEngine
 from .address import Address
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_internal/router/address.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/router/address.py b/python/qpid_dispatch_internal/router/address.py
index 0cff578..24cb6a4 100644
--- a/python/qpid_dispatch_internal/router/address.py
+++ b/python/qpid_dispatch_internal/router/address.py
@@ -19,7 +19,10 @@
 
 """Parse & decompose router addresses"""
 
-
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
 
 class Address(str):
     """A router address. Immutable, hashable.

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_internal/router/data.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/router/data.py b/python/qpid_dispatch_internal/router/data.py
index 827f621..6c1db7f 100644
--- a/python/qpid_dispatch_internal/router/data.py
+++ b/python/qpid_dispatch_internal/router/data.py
@@ -21,8 +21,15 @@
 ## Define the current protocol version.  Any messages that do not contain version
 ## information shall be considered to be coming from routers using version 0.
 ##
+
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 from ..compat import PY_LONG_TYPE
 from ..compat import LONG
+from ..compat import PY_TEXT_TYPE
 
 ProtocolVersion = LONG(1)
 
@@ -58,7 +65,7 @@ class LinkState(object):
     def __init__(self, body, _id=None, _ls_seq=None, _peers=None):
         self.last_seen = 0
         if body:
-            self.id = getMandatory(body, 'id', str)
+            self.id = getMandatory(body, 'id', PY_TEXT_TYPE)
             self.area = '0'
             self.ls_seq = getMandatory(body, 'ls_seq', PY_LONG_TYPE)
             self.peers = getMandatory(body, 'peers', dict)
@@ -112,7 +119,7 @@ class MessageHELLO(object):
     """
     def __init__(self, body, _id=None, _seen_peers=None, _instance=LONG(0)):
         if body:
-            self.id = getMandatory(body, 'id', str)
+            self.id = getMandatory(body, 'id', PY_TEXT_TYPE)
             self.area = '0'
             self.seen_peers = getMandatory(body, 'seen', list)
             self.instance = getOptional(body, 'instance', 0, PY_LONG_TYPE)
@@ -150,7 +157,7 @@ class MessageRA(object):
     """
     def __init__(self, body, _id=None, _ls_seq=None, _mobile_seq=None, _instance=LONG(0)):
         if body:
-            self.id = getMandatory(body, 'id', str)
+            self.id = getMandatory(body, 'id', PY_TEXT_TYPE)
             self.area = '0'
             self.ls_seq = getMandatory(body, 'ls_seq', PY_LONG_TYPE)
             self.mobile_seq = getMandatory(body, 'mobile_seq', PY_LONG_TYPE)
@@ -185,7 +192,7 @@ class MessageLSU(object):
     """
     def __init__(self, body, _id=None, _ls_seq=None, _ls=None, _instance=LONG(0)):
         if body:
-            self.id = getMandatory(body, 'id', str)
+            self.id = getMandatory(body, 'id', PY_TEXT_TYPE)
             self.area = '0'
             self.ls_seq = getMandatory(body, 'ls_seq', PY_LONG_TYPE)
             self.ls = LinkState(getMandatory(body, 'ls', dict))
@@ -220,7 +227,7 @@ class MessageLSR(object):
     """
     def __init__(self, body, _id=None):
         if body:
-            self.id = getMandatory(body, 'id', str)
+            self.id = getMandatory(body, 'id', PY_TEXT_TYPE)
             self.version = getOptional(body, 'pv', 0, PY_LONG_TYPE)
             self.area = '0'
         else:
@@ -245,7 +252,7 @@ class MessageMAU(object):
     """
     def __init__(self, body, _id=None, _seq=None, _add_list=None, _del_list=None, _exist_list=None):
         if body:
-            self.id = getMandatory(body, 'id', str)
+            self.id = getMandatory(body, 'id', PY_TEXT_TYPE)
             self.version = getOptional(body, 'pv', 0, PY_LONG_TYPE)
             self.area = '0'
             self.mobile_seq = getMandatory(body, 'mobile_seq', PY_LONG_TYPE)
@@ -290,7 +297,7 @@ class MessageMAR(object):
     """
     def __init__(self, body, _id=None, _have_seq=None):
         if body:
-            self.id = getMandatory(body, 'id', str)
+            self.id = getMandatory(body, 'id', PY_TEXT_TYPE)
             self.version = getOptional(body, 'pv', 0, PY_LONG_TYPE)
             self.area = '0'
             self.have_seq = getMandatory(body, 'have_seq', PY_LONG_TYPE)

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_internal/router/engine.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/router/engine.py b/python/qpid_dispatch_internal/router/engine.py
index ef099be..31fad2c 100644
--- a/python/qpid_dispatch_internal/router/engine.py
+++ b/python/qpid_dispatch_internal/router/engine.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 from .data import MessageHELLO, MessageRA, MessageLSU, MessageMAU, MessageMAR, MessageLSR
 from .hello import HelloProtocol
 from .link import LinkStateEngine

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_internal/router/hello.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/router/hello.py b/python/qpid_dispatch_internal/router/hello.py
index 6b21bc8..9bbc900 100644
--- a/python/qpid_dispatch_internal/router/hello.py
+++ b/python/qpid_dispatch_internal/router/hello.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 from .data import MessageHELLO
 from ..dispatch import LOG_INFO, LOG_TRACE, LOG_CRITICAL
 from ..compat import dict_keys

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_internal/router/link.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/router/link.py b/python/qpid_dispatch_internal/router/link.py
index 09c4dfd..3b46722 100644
--- a/python/qpid_dispatch_internal/router/link.py
+++ b/python/qpid_dispatch_internal/router/link.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 from .data import MessageRA, MessageLSU, MessageLSR
 from ..dispatch import LOG_TRACE
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_internal/router/message.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/router/message.py b/python/qpid_dispatch_internal/router/message.py
index 4f5df69..ed73288 100644
--- a/python/qpid_dispatch_internal/router/message.py
+++ b/python/qpid_dispatch_internal/router/message.py
@@ -17,6 +17,11 @@
 # under the License
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 """Python class to hold message data"""
 
 class Message(object):

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_internal/router/mobile.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/router/mobile.py b/python/qpid_dispatch_internal/router/mobile.py
index c29d038..6e768c2 100644
--- a/python/qpid_dispatch_internal/router/mobile.py
+++ b/python/qpid_dispatch_internal/router/mobile.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 from .data import MessageMAR, MessageMAU
 from ..dispatch import LOG_TRACE
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_internal/router/node.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/router/node.py b/python/qpid_dispatch_internal/router/node.py
index 68d40ef..8d8841e 100644
--- a/python/qpid_dispatch_internal/router/node.py
+++ b/python/qpid_dispatch_internal/router/node.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 from ..dispatch import LOG_INFO, LOG_TRACE, LOG_DEBUG
 from .data import LinkState, ProtocolVersion
 from .address import Address

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_internal/router/path.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/router/path.py b/python/qpid_dispatch_internal/router/path.py
index 548f4e8..cc089d5 100644
--- a/python/qpid_dispatch_internal/router/path.py
+++ b/python/qpid_dispatch_internal/router/path.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 from ..compat import dict_items
 from ..compat import dict_keys
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_internal/tools/__init__.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/tools/__init__.py b/python/qpid_dispatch_internal/tools/__init__.py
index ddda43d..157f503 100644
--- a/python/qpid_dispatch_internal/tools/__init__.py
+++ b/python/qpid_dispatch_internal/tools/__init__.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 from .display import Display, Header, Sorter, YN, Commas, TimeLong, TimeShort, Sortable
 
 __all__ = ["Display", "Header", "Sorter", "YN", "Commas", "TimeLong", "TimeShort", "Sortable"]

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_internal/tools/command.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/tools/command.py b/python/qpid_dispatch_internal/tools/command.py
index 6153c9e..ace9391 100644
--- a/python/qpid_dispatch_internal/tools/command.py
+++ b/python/qpid_dispatch_internal/tools/command.py
@@ -20,6 +20,9 @@
 """
 Utilities for command-line programs.
 """
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
 from __future__ import print_function
 
 import sys, json, optparse, os

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_internal/tools/display.py
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_internal/tools/display.py b/python/qpid_dispatch_internal/tools/display.py
index 86d67ac..ead8077 100644
--- a/python/qpid_dispatch_internal/tools/display.py
+++ b/python/qpid_dispatch_internal/tools/display.py
@@ -17,6 +17,9 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
 from __future__ import print_function
 
 from time import strftime, gmtime

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/python/qpid_dispatch_site.py.in
----------------------------------------------------------------------
diff --git a/python/qpid_dispatch_site.py.in b/python/qpid_dispatch_site.py.in
index aec93dd..da7925a 100644
--- a/python/qpid_dispatch_site.py.in
+++ b/python/qpid_dispatch_site.py.in
@@ -20,6 +20,10 @@
 """
 INTERNAL USE ONLY - Install locations and other site information for qpid dispatch.
 """
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
 
 from os.path import join
 from os import environ

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/run.py.in
----------------------------------------------------------------------
diff --git a/run.py.in b/run.py.in
index 5f050e2..3233e3d 100755
--- a/run.py.in
+++ b/run.py.in
@@ -18,6 +18,9 @@
 ## under the License
 ##
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
 from __future__ import print_function
 
 """

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/src/entity.c
----------------------------------------------------------------------
diff --git a/src/entity.c b/src/entity.c
index 9128752..59717ab 100644
--- a/src/entity.c
+++ b/src/entity.c
@@ -17,11 +17,11 @@
  * under the License.
  */
 
+#include "python_private.h"  // must be first!
 
 #include <qpid/dispatch/error.h>
 #include "dispatch_private.h"
 #include "entity.h"
-#include "python_private.h"
 
 struct qd_entity_t {
     PyObject py_object;      /* Any object supporting __set/get_item__, e.g. dict. */

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/src/error.c
----------------------------------------------------------------------
diff --git a/src/error.c b/src/error.c
index e3009cb..b62ae1d 100644
--- a/src/error.c
+++ b/src/error.c
@@ -17,19 +17,15 @@
  * under the License.
  */
 
-
-/* Make sure we get the XSI compliant strerror_r from string.h not the GNU one. */
-/*#define _POSIX_C_SOURCE 200112L
-  #undef _GNU_SOURCE*/
-#include <string.h>
+#include <qpid/dispatch/python_embedded.h>  // must be first!
 
 #include <qpid/dispatch/error.h>
 #include <qpid/dispatch/enum.h>
 #include <qpid/dispatch/log.h>
-#include <qpid/dispatch/python_embedded.h>
 #include <stdarg.h>
 #include <stdio.h>
 #include <errno.h>
+#include <string.h>
 #include "log_private.h"
 #include "aprintf.h"
 #include "python_private.h"

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/src/log.c
----------------------------------------------------------------------
diff --git a/src/log.c b/src/log.c
index fbb757a..c4c6c84 100644
--- a/src/log.c
+++ b/src/log.c
@@ -17,6 +17,8 @@
  * under the License.
  */
 
+#include "python_private.h"   // must be first!
+
 #include "log_private.h"
 #include "entity.h"
 #include "entity_cache.h"
@@ -32,7 +34,6 @@
 #include <string.h>
 #include <time.h>
 #include <syslog.h>
-#include "python_private.h"
 
 #define TEXT_MAX QD_LOG_TEXT_MAX
 #define LOG_MAX (QD_LOG_TEXT_MAX+128)

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/src/python_embedded.c
----------------------------------------------------------------------
diff --git a/src/python_embedded.c b/src/python_embedded.c
index 027f280..12464f1 100644
--- a/src/python_embedded.c
+++ b/src/python_embedded.c
@@ -17,9 +17,10 @@
  * under the License.
  */
 
-#include "entity_cache.h"
-#include "python_private.h"
 #include <qpid/dispatch/python_embedded.h>
+#include "python_private.h"
+
+#include "entity_cache.h"
 #include <qpid/dispatch/threading.h>
 #include <qpid/dispatch/log.h>
 #include <qpid/dispatch/error.h>
@@ -28,6 +29,8 @@
 #include <qpid/dispatch/router.h>
 #include <qpid/dispatch/error.h>
 
+#include <ctype.h>
+
 
 #define DISPATCH_MODULE "qpid_dispatch_internal.dispatch"
 
@@ -164,7 +167,7 @@ qd_error_t qd_py_to_composed(PyObject *value, qd_composed_field_t *field)
         qd_compose_insert_null(field);
     }
     else if (PyBool_Check(value)) {
-        qd_compose_insert_bool(field, PyLong_AS_LONG(value) ? 1 : 0);
+        qd_compose_insert_bool(field, PyLong_AsLong(value) ? 1 : 0);
     }
     else if (QD_PY_INT_CHECK(value)) {
         // We are now sure that the value is an integer type
@@ -549,27 +552,25 @@ static int IoAdapter_init(IoAdapter *self, PyObject *args, PyObject *kwds)
     char aclass    = 'L';
     char phase     = '0';
     int  treatment = QD_TREATMENT_ANYCAST_CLOSEST;
-    if (PY_MAJOR_VERSION == 2) {
-        if (!PyArg_ParseTuple(args, "OO|cci", &self->handler, &addr, &aclass, &phase, &treatment))
-            return -1;
-    } else {
-        // In Python3 all string text is unicode.  Therefore the ParseTuple format
-        // no longer allows use of a char byte for extracted characters since a
-        // single character may be up to 4 bytes in length.  Since class and
-        // phase can only be ascii we can simply downcast the returned value
-        // (being careful we do not overflow a single character).
-        unsigned int i_aclass = (int) aclass;
-        unsigned int i_phase = (int) phase;
-        if (!PyArg_ParseTuple(args, "OO|CCi", &self->handler, &addr, &i_aclass, &i_phase, &treatment))
+
+    const char *aclass_str = NULL;
+    const char *phase_str = NULL;
+    if (!PyArg_ParseTuple(args, "OO|ssi", &self->handler, &addr, &aclass_str, &phase_str, &treatment))
+        return -1;
+    if (aclass_str) {
+        if (strlen(aclass_str) != 1 || !isalpha(*aclass_str)) {
+            PyErr_SetString(PyExc_TypeError, "Address class not a single character");
             return -1;
-        if (i_aclass > 0x7F || i_phase > 0x7F) {
-            PyErr_SetString(PyExc_TypeError, "Address class or phase not a single alpha character");
+        }
+        aclass = *aclass_str;
+    }
+    if (phase_str) {
+        if (strlen(phase_str) != 1 || !isdigit(*phase_str)) {
+            PyErr_SetString(PyExc_TypeError, "Phase not a single numeric character");
             return -1;
         }
-        aclass = (char) i_aclass;
-        phase = (char) i_phase;
+        phase = *phase_str;
     }
-
     if (!PyCallable_Check(self->handler)) {
         PyErr_SetString(PyExc_TypeError, "IoAdapter.__init__ handler is not callable");
         return -1;

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/src/python_private.h
----------------------------------------------------------------------
diff --git a/src/python_private.h b/src/python_private.h
index ec85505..b344a0f 100644
--- a/src/python_private.h
+++ b/src/python_private.h
@@ -18,8 +18,8 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-#include <stdint.h>
 #include <Python.h>
+#include <stdint.h>
 
 #if PY_MAJOR_VERSION <= 2
 // deal with the two integer types in Python2

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/src/schema_c.py
----------------------------------------------------------------------
diff --git a/src/schema_c.py b/src/schema_c.py
index 3c90b4d..3ce2e93 100644
--- a/src/schema_c.py
+++ b/src/schema_c.py
@@ -20,6 +20,10 @@
 """
 Generate C code from the router schema.
 """
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
 
 import re
 from qpid_dispatch_internal.management.schema import EnumType

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/src/server.c
----------------------------------------------------------------------
diff --git a/src/server.c b/src/server.c
index 64819d5..171c729 100644
--- a/src/server.c
+++ b/src/server.c
@@ -17,6 +17,9 @@
  * under the License.
  */
 
+#include "python_private.h"             // must be first!
+#include <qpid/dispatch/python_embedded.h>
+
 #include <qpid/dispatch/ctools.h>
 #include <qpid/dispatch/threading.h>
 #include <qpid/dispatch/log.h>
@@ -31,7 +34,7 @@
 #include <proton/proactor.h>
 #include <proton/sasl.h>
 
-#include "qpid/dispatch/python_embedded.h"
+
 #include "entity.h"
 #include "entity_cache.h"
 #include "dispatch_private.h"
@@ -40,7 +43,6 @@
 #include "timer_private.h"
 #include "config.h"
 #include "remote_sasl.h"
-#include "python_private.h"
 #include <stdio.h>
 #include <string.h>
 #include <errno.h>

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/authservice.py
----------------------------------------------------------------------
diff --git a/tests/authservice.py b/tests/authservice.py
index c46a9ae..7693b42 100755
--- a/tests/authservice.py
+++ b/tests/authservice.py
@@ -18,7 +18,11 @@
 # under the License.
 #
 
-from __future__ import print_function, unicode_literals
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import signal, optparse
 from proton.handlers import MessagingHandler
 from proton.reactor import Container

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/management/entity.py
----------------------------------------------------------------------
diff --git a/tests/management/entity.py b/tests/management/entity.py
index b5939b0..fa27e81 100644
--- a/tests/management/entity.py
+++ b/tests/management/entity.py
@@ -17,6 +17,11 @@
 # under the License
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import unittest
 from qpid_dispatch.management.entity import EntityBase, camelcase
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/management/qdrouter.py
----------------------------------------------------------------------
diff --git a/tests/management/qdrouter.py b/tests/management/qdrouter.py
index 46455ef..2c8f7b1 100644
--- a/tests/management/qdrouter.py
+++ b/tests/management/qdrouter.py
@@ -19,6 +19,11 @@
 
 #pylint: disable=wildcard-import,unused-wildcard-import,missing-docstring,too-many-public-methods
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import unittest, sys
 from qpid_dispatch_internal.management.config import Config
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/management/schema.py
----------------------------------------------------------------------
diff --git a/tests/management/schema.py b/tests/management/schema.py
index ad2340b..64b0ab5 100644
--- a/tests/management/schema.py
+++ b/tests/management/schema.py
@@ -20,6 +20,11 @@
 
 #pylint: disable=wildcard-import,missing-docstring,too-many-public-methods
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import unittest, json
 from qpid_dispatch_internal.management.schema import Schema, BooleanType, EnumType, AttributeType, ValidationError, EnumValue, EntityType
 from qpid_dispatch_internal.compat import OrderedDict

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/mock/__init__.py
----------------------------------------------------------------------
diff --git a/tests/mock/__init__.py b/tests/mock/__init__.py
index 9e870bb..3a008f0 100644
--- a/tests/mock/__init__.py
+++ b/tests/mock/__init__.py
@@ -20,6 +20,10 @@
 """
 Mock implementation of the dispatch C extension module for use in unit tests.
 """
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
 
 from qpid_dispatch_internal import dispatch as real_dispatch
 from . import dispatch as mock_dispatch

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/mock/dispatch.py
----------------------------------------------------------------------
diff --git a/tests/mock/dispatch.py b/tests/mock/dispatch.py
index 5a34e43..ca6b370 100644
--- a/tests/mock/dispatch.py
+++ b/tests/mock/dispatch.py
@@ -19,8 +19,13 @@
 """
 Mock implementation of the dispatch C extension module for use in unit tests.
 """
+
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
 from __future__ import print_function
 
+
 LOG_TRACE    = 1
 LOG_DEBUG    = 2
 LOG_INFO     = 4

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/router_engine_test.py
----------------------------------------------------------------------
diff --git a/tests/router_engine_test.py b/tests/router_engine_test.py
index 0442088..58d27ef 100644
--- a/tests/router_engine_test.py
+++ b/tests/router_engine_test.py
@@ -17,6 +17,9 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
 from __future__ import print_function
 
 import os

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/router_policy_test.py
----------------------------------------------------------------------
diff --git a/tests/router_policy_test.py b/tests/router_policy_test.py
index 3421250..a437668 100644
--- a/tests/router_policy_test.py
+++ b/tests/router_policy_test.py
@@ -17,6 +17,9 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
 from __future__ import print_function
 
 import unittest2 as unittest

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/run_system_tests.py
----------------------------------------------------------------------
diff --git a/tests/run_system_tests.py b/tests/run_system_tests.py
index 460692f..2e4c959 100644
--- a/tests/run_system_tests.py
+++ b/tests/run_system_tests.py
@@ -24,6 +24,10 @@ Note that each system test is an executable script, you can run them directly.
 Run without any environment settings, this will test a dispatch router installed in
 the standard system places. Use run.py or config.sh to run against dispatch build.
 """
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
 
 import os
 import sys

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_test.py
----------------------------------------------------------------------
diff --git a/tests/system_test.py b/tests/system_test.py
index 0ff97da..37056b6 100755
--- a/tests/system_test.py
+++ b/tests/system_test.py
@@ -27,6 +27,10 @@ Features:
 - Tools to manipulate qdrouter configuration files.
 - Sundry other tools.
 """
+
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
 from __future__ import print_function
 
 import errno, os, time, socket, random, subprocess, shutil, unittest, __main__, re, sys

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_auth_service_plugin.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_auth_service_plugin.py b/tests/system_tests_auth_service_plugin.py
index 013c87e..5b48e40 100644
--- a/tests/system_tests_auth_service_plugin.py
+++ b/tests/system_tests_auth_service_plugin.py
@@ -17,8 +17,12 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
 from __future__ import print_function
 
+
 import unittest2 as unittest
 import os
 from subprocess import PIPE, Popen

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_authz_service_plugin.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_authz_service_plugin.py b/tests/system_tests_authz_service_plugin.py
index 994079d..c3180a6 100644
--- a/tests/system_tests_authz_service_plugin.py
+++ b/tests/system_tests_authz_service_plugin.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import unittest2 as unittest
 import os, json
 from subprocess import PIPE, Popen, STDOUT

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_autolinks.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_autolinks.py b/tests/system_tests_autolinks.py
index 952644b..a74bcef 100644
--- a/tests/system_tests_autolinks.py
+++ b/tests/system_tests_autolinks.py
@@ -17,6 +17,12 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
+
 import unittest2 as unittest
 import json
 from proton import Message

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_bad_configuration.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_bad_configuration.py b/tests/system_tests_bad_configuration.py
index 8dd379d..9fe0522 100644
--- a/tests/system_tests_bad_configuration.py
+++ b/tests/system_tests_bad_configuration.py
@@ -23,6 +23,12 @@ that might cause problems, or caused issues in the past.
 For example, unresolvable host names.
 """
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
+
 from threading import Timer
 import re
 from subprocess import PIPE, STDOUT

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_broker.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_broker.py b/tests/system_tests_broker.py
index bef3008..ab94911 100644
--- a/tests/system_tests_broker.py
+++ b/tests/system_tests_broker.py
@@ -21,6 +21,13 @@
 System tests involving one or more brokers and dispatch routers integrated
 with waypoints.
 """
+
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
+
 import unittest2 as unittest
 import system_test
 from system_test import Qdrouterd, message, MISSING_REQUIREMENTS

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_cmdline_parsing.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_cmdline_parsing.py b/tests/system_tests_cmdline_parsing.py
index 75526fb..7fe3f2d 100644
--- a/tests/system_tests_cmdline_parsing.py
+++ b/tests/system_tests_cmdline_parsing.py
@@ -24,6 +24,11 @@ in order to ensure it won't break, causing bad experiences
 to the users.
 """
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import os
 import signal
 from subprocess import PIPE, STDOUT

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_default_distribution.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_default_distribution.py b/tests/system_tests_default_distribution.py
index 2bb9b4d..a265969 100644
--- a/tests/system_tests_default_distribution.py
+++ b/tests/system_tests_default_distribution.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import unittest2 as unittest
 import re
 from subprocess import PIPE

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_delivery_abort.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_delivery_abort.py b/tests/system_tests_delivery_abort.py
index 6051ebf..909b805 100644
--- a/tests/system_tests_delivery_abort.py
+++ b/tests/system_tests_delivery_abort.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import unittest2 as unittest
 from proton import Message, Timeout
 from system_test import TestCase, Qdrouterd, main_module

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_deprecated.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_deprecated.py b/tests/system_tests_deprecated.py
index 6809e94..6d5e9ed 100644
--- a/tests/system_tests_deprecated.py
+++ b/tests/system_tests_deprecated.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 from system_test import TestCase, Qdrouterd
 
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_disallow_link_resumable_link_route.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_disallow_link_resumable_link_route.py b/tests/system_tests_disallow_link_resumable_link_route.py
index 05d2ae8..f485601 100644
--- a/tests/system_tests_disallow_link_resumable_link_route.py
+++ b/tests/system_tests_disallow_link_resumable_link_route.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import unittest2 as unittest
 from time import sleep, time
 from subprocess import PIPE, STDOUT

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_distribution.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_distribution.py b/tests/system_tests_distribution.py
index b3484fd..9a2ae71 100644
--- a/tests/system_tests_distribution.py
+++ b/tests/system_tests_distribution.py
@@ -17,6 +17,9 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
 from __future__ import print_function
 
 import unittest2 as unittest

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_drain.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_drain.py b/tests/system_tests_drain.py
index b2ecadb..b9fd547 100644
--- a/tests/system_tests_drain.py
+++ b/tests/system_tests_drain.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import unittest2 as unittest
 from system_test import TestCase, Qdrouterd, main_module
 from system_tests_drain_support import DrainMessagesHandler, DrainOneMessageHandler

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_drain_support.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_drain_support.py b/tests/system_tests_drain_support.py
index 2600ec0..930a486 100644
--- a/tests/system_tests_drain_support.py
+++ b/tests/system_tests_drain_support.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import unittest2 as unittest
 from proton.handlers import MessagingHandler
 from proton.reactor import Container
@@ -208,4 +213,4 @@ class DrainNoMoreMessagesHandler(MessagingHandler):
 
 
 if __name__ == '__main__':
-    unittest.main(main_module())
\ No newline at end of file
+    unittest.main(main_module())

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_dynamic_terminus.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_dynamic_terminus.py b/tests/system_tests_dynamic_terminus.py
index 8a76e53..4ad5e19 100644
--- a/tests/system_tests_dynamic_terminus.py
+++ b/tests/system_tests_dynamic_terminus.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import unittest2 as unittest
 from proton import Message, Timeout
 from system_test import TestCase, Qdrouterd, main_module, TIMEOUT

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_exchange_bindings.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_exchange_bindings.py b/tests/system_tests_exchange_bindings.py
index 1449f77..e8325a4 100644
--- a/tests/system_tests_exchange_bindings.py
+++ b/tests/system_tests_exchange_bindings.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import ast
 import unittest2 as unittest
 from time import sleep

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_failover_list.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_failover_list.py b/tests/system_tests_failover_list.py
index 6a5fcb4..123ceb3 100644
--- a/tests/system_tests_failover_list.py
+++ b/tests/system_tests_failover_list.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import unittest2 as unittest
 from proton import Timeout
 from system_test import TestCase, Qdrouterd, main_module, TIMEOUT

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_handle_failover.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_handle_failover.py b/tests/system_tests_handle_failover.py
index dcd9893..f2615c2 100644
--- a/tests/system_tests_handle_failover.py
+++ b/tests/system_tests_handle_failover.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 from threading import Timer
 import unittest2 as unittest
 import json, re

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_http.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_http.py b/tests/system_tests_http.py
index a436e3a..2ba494c 100644
--- a/tests/system_tests_http.py
+++ b/tests/system_tests_http.py
@@ -16,6 +16,10 @@
 # specific language governing permissions and limitations
 # under the License.
 #
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
 
 import unittest2 as unittest
 import os, threading, sys, urllib2

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_link_routes.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_link_routes.py b/tests/system_tests_link_routes.py
index 713d8f2..8740c80 100644
--- a/tests/system_tests_link_routes.py
+++ b/tests/system_tests_link_routes.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import unittest2 as unittest
 from time import sleep, time
 from subprocess import PIPE, STDOUT
@@ -771,7 +776,7 @@ class DeliveryTagsTest(MessagingHandler):
         self.delivery_tag_verified = False
         # The delivery tag we are going to send in the transfer frame
         # We will later make sure that the same delivery tag shows up on the receiving end in the link routed case.
-        self.delivery_tag = '92319'
+        self.delivery_tag = b'92319'
         self.error = None
 
     def timeout(self):

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_log_message_components.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_log_message_components.py b/tests/system_tests_log_message_components.py
index e66dcce..c497839 100644
--- a/tests/system_tests_log_message_components.py
+++ b/tests/system_tests_log_message_components.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import unittest2 as unittest
 import json
 from proton import Message, symbol

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_management.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_management.py b/tests/system_tests_management.py
index 51e8ad3..f0a12b5 100644
--- a/tests/system_tests_management.py
+++ b/tests/system_tests_management.py
@@ -19,6 +19,11 @@
 
 """System tests for management of qdrouter"""
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import unittest2 as unittest
 import system_test, re, os, json
 from proton.handlers import MessagingHandler

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_multi_tenancy.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_multi_tenancy.py b/tests/system_tests_multi_tenancy.py
index 78dc1d8..2319236 100644
--- a/tests/system_tests_multi_tenancy.py
+++ b/tests/system_tests_multi_tenancy.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import unittest2 as unittest
 from proton import Message, Timeout
 from system_test import TestCase, Qdrouterd, main_module, TIMEOUT

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_one_router.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_one_router.py b/tests/system_tests_one_router.py
index a15866f..ea8e13f 100644
--- a/tests/system_tests_one_router.py
+++ b/tests/system_tests_one_router.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import unittest2 as unittest
 from proton import Condition, Message, Delivery, PENDING, ACCEPTED, REJECTED, Url, symbol, Timeout
 from system_test import TestCase, Qdrouterd, main_module, TIMEOUT
@@ -2664,7 +2669,9 @@ class RejectDispositionTest(MessagingHandler):
         self.sent = False
         self.received_error = False
         self.dest = "rejectDispositionTest"
-        self.error_description = 'you were out of luck this time!'
+        # explicitly convert to str due to
+        # https://issues.apache.org/jira/browse/PROTON-1843
+        self.error_description = str('you were out of luck this time!')
         self.error_name = u'amqp:internal-error'
         self.reject_count_match = False
         self.rejects_at_start = 0

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_policy.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_policy.py b/tests/system_tests_policy.py
index 4c81496..b747f0d 100644
--- a/tests/system_tests_policy.py
+++ b/tests/system_tests_policy.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import unittest as unittest
 import os, json
 from system_test import TestCase, Qdrouterd, main_module, Process, TIMEOUT, DIR
@@ -735,7 +740,7 @@ class PolicyLinkNamePatternTest(TestCase):
             qdm_out = self.run_qdmanage('create --type=vhost --name=DISPATCH-1993-2 --stdin', input=self.disallowed_source())
         except Exception as e:
             exception = True
-            self.assertTrue("InternalServerErrorStatus: PolicyError: \"Policy 'DISPATCH-1993-2' is invalid:" in str(e))
+            self.assertTrue("InternalServerErrorStatus: PolicyError: Policy 'DISPATCH-1993-2' is invalid:" in str(e))
         self.assertTrue(exception)
 
         # attempt another create that should be rejected
@@ -745,7 +750,7 @@ class PolicyLinkNamePatternTest(TestCase):
             qdm_out = self.run_qdmanage('create --type=vhost --name=DISPATCH-1993-3 --stdin', input=self.disallowed_target())
         except Exception as e:
             exception = True
-            self.assertTrue("InternalServerErrorStatus: PolicyError: \"Policy 'DISPATCH-1993-3' is invalid:" in str(e))
+            self.assertTrue("InternalServerErrorStatus: PolicyError: Policy 'DISPATCH-1993-3' is invalid:" in str(e))
         self.assertTrue(exception)
 
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_protocol_family.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_protocol_family.py b/tests/system_tests_protocol_family.py
index 0aea0ef..16aea3d 100644
--- a/tests/system_tests_protocol_family.py
+++ b/tests/system_tests_protocol_family.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import unittest2 as unittest
 from proton import Message
 from proton.handlers import MessagingHandler
@@ -149,4 +154,4 @@ class SimpleSndRecv(MessagingHandler):
 
 
 if __name__ == '__main__':
-    unittest.main(main_module())
\ No newline at end of file
+    unittest.main(main_module())

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_protocol_settings.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_protocol_settings.py b/tests/system_tests_protocol_settings.py
index 523a03b..af3a4f1 100644
--- a/tests/system_tests_protocol_settings.py
+++ b/tests/system_tests_protocol_settings.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import unittest2 as unittest
 from system_test import TestCase, Qdrouterd, main_module
 from proton.utils import BlockingConnection

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_qdmanage.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_qdmanage.py b/tests/system_tests_qdmanage.py
index 0275e53..15012ce 100644
--- a/tests/system_tests_qdmanage.py
+++ b/tests/system_tests_qdmanage.py
@@ -17,6 +17,11 @@
 # under the License
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import json, unittest2 as unittest, os
 
 from system_test import TestCase, Process, Qdrouterd, main_module, TIMEOUT, DIR
@@ -408,7 +413,7 @@ class QdmanageTest(TestCase):
             self.run_qdmanage(delete_command)
         except Exception as e:
             exception_occurred = True
-            self.assertTrue("NotFoundStatus: No entity with name='" + name + "'" in str(e))
+            self.assertTrue(("NotFoundStatus: No entity with name=%s" % name) in str(e))
 
         self.assertTrue(exception_occurred)
 

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_qdstat.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_qdstat.py b/tests/system_tests_qdstat.py
index c786598..a043d9f 100644
--- a/tests/system_tests_qdstat.py
+++ b/tests/system_tests_qdstat.py
@@ -17,6 +17,11 @@
 # under the License
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import os
 import re
 import system_test

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_sasl_plain.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_sasl_plain.py b/tests/system_tests_sasl_plain.py
index 1b67b2c..2285eee 100644
--- a/tests/system_tests_sasl_plain.py
+++ b/tests/system_tests_sasl_plain.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import unittest2 as unittest, os
 from subprocess import PIPE, Popen
 from system_test import TestCase, Qdrouterd, main_module, DIR, TIMEOUT

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_topology.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_topology.py b/tests/system_tests_topology.py
index e5af286..afe5633 100644
--- a/tests/system_tests_topology.py
+++ b/tests/system_tests_topology.py
@@ -17,6 +17,9 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
 from __future__ import print_function
 
 import unittest2 as unittest

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_topology_addition.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_topology_addition.py b/tests/system_tests_topology_addition.py
index 51d2643..2e06b55 100644
--- a/tests/system_tests_topology_addition.py
+++ b/tests/system_tests_topology_addition.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 import unittest, os, json
 from subprocess      import PIPE, STDOUT
 from proton          import Message, PENDING, ACCEPTED, REJECTED, RELEASED, SSLDomain, SSLUnavailable, Timeout

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_topology_disposition.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_topology_disposition.py b/tests/system_tests_topology_disposition.py
index d902ad5..035ba7e 100644
--- a/tests/system_tests_topology_disposition.py
+++ b/tests/system_tests_topology_disposition.py
@@ -17,6 +17,9 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
 from __future__ import print_function
 
 import unittest, os, json

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_two_routers.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_two_routers.py b/tests/system_tests_two_routers.py
index 83902fe..2a86c3d 100644
--- a/tests/system_tests_two_routers.py
+++ b/tests/system_tests_two_routers.py
@@ -17,6 +17,11 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
+
 from time import sleep
 import unittest2 as unittest
 import logging

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_user_id.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_user_id.py b/tests/system_tests_user_id.py
index 52093a7..827cd0f 100644
--- a/tests/system_tests_user_id.py
+++ b/tests/system_tests_user_id.py
@@ -17,6 +17,10 @@
 # under the License
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
 
 import os
 import unittest2 as unittest

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tests/system_tests_user_id_proxy.py
----------------------------------------------------------------------
diff --git a/tests/system_tests_user_id_proxy.py b/tests/system_tests_user_id_proxy.py
index ecea4cc..c2ea86f 100644
--- a/tests/system_tests_user_id_proxy.py
+++ b/tests/system_tests_user_id_proxy.py
@@ -17,6 +17,10 @@
 # under the License
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from __future__ import print_function
 
 import os
 import unittest2 as unittest

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tools/qdmanage
----------------------------------------------------------------------
diff --git a/tools/qdmanage b/tools/qdmanage
index bacef3c..ffef1f1 100755
--- a/tools/qdmanage
+++ b/tools/qdmanage
@@ -19,6 +19,9 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
 from __future__ import print_function
 
 import sys, json, re

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tools/qdstat
----------------------------------------------------------------------
diff --git a/tools/qdstat b/tools/qdstat
index 6b8db4d..1e3a3a3 100755
--- a/tools/qdstat
+++ b/tools/qdstat
@@ -19,6 +19,9 @@
 # under the License.
 #
 
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
 from __future__ import print_function
 
 import os

http://git-wip-us.apache.org/repos/asf/qpid-dispatch/blob/7bdd55c7/tox.ini
----------------------------------------------------------------------
diff --git a/tox.ini b/tox.ini
index 879569f..6f749fd 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,5 +1,5 @@
 [tox]
-envlist = py26,py27,py35,py36
+envlist = py27,py35,py36
 skipsdist = True
 minversion = 1.4
 # note: when minversion is >= 1.7.2, uncomment the
@@ -12,8 +12,9 @@ minversion = 1.4
 commands = flake8 --count python console doc tests tools
 deps = hacking
 
-[testenv:py26]
-basepython = python2.6
+# flake8 no longer supports python2.6
+# [testenv:py26]
+# basepython = python2.6
 
 [testenv:py27]
 basepython = python2.7


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org