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 2015/04/24 21:59:58 UTC
[1/4] qpid-proton git commit: PROTON-490: JYTHON tests cannot access
site six.py so include a copy
Repository: qpid-proton
Updated Branches:
refs/heads/kgiusti-python3 e87a6d313 -> 99299d3b3
PROTON-490: JYTHON tests cannot access site six.py so include a copy
Project: http://git-wip-us.apache.org/repos/asf/qpid-proton/repo
Commit: http://git-wip-us.apache.org/repos/asf/qpid-proton/commit/adfe2a20
Tree: http://git-wip-us.apache.org/repos/asf/qpid-proton/tree/adfe2a20
Diff: http://git-wip-us.apache.org/repos/asf/qpid-proton/diff/adfe2a20
Branch: refs/heads/kgiusti-python3
Commit: adfe2a20f0e07a6b8445b45975f15d1512599866
Parents: e87a6d3
Author: Ken Giusti <kg...@apache.org>
Authored: Wed Apr 22 15:07:47 2015 -0400
Committer: Ken Giusti <kg...@apache.org>
Committed: Wed Apr 22 15:07:47 2015 -0400
----------------------------------------------------------------------
tests/python/six.py | 838 +++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 838 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/adfe2a20/tests/python/six.py
----------------------------------------------------------------------
diff --git a/tests/python/six.py b/tests/python/six.py
new file mode 100644
index 0000000..ffa3fe1
--- /dev/null
+++ b/tests/python/six.py
@@ -0,0 +1,838 @@
+"""Utilities for writing code that runs on Python 2 and 3"""
+
+# Copyright (c) 2010-2015 Benjamin Peterson
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in all
+# copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+# SOFTWARE.
+
+from __future__ import absolute_import
+
+import functools
+import itertools
+import operator
+import sys
+import types
+
+__author__ = "Benjamin Peterson <be...@python.org>"
+__version__ = "1.9.0"
+
+
+# Useful for very coarse version differentiation.
+PY2 = sys.version_info[0] == 2
+PY3 = sys.version_info[0] == 3
+
+if PY3:
+ string_types = str,
+ integer_types = int,
+ class_types = type,
+ text_type = str
+ binary_type = bytes
+
+ MAXSIZE = sys.maxsize
+else:
+ string_types = basestring,
+ integer_types = (int, long)
+ class_types = (type, types.ClassType)
+ text_type = unicode
+ binary_type = str
+
+ if sys.platform.startswith("java"):
+ # Jython always uses 32 bits.
+ MAXSIZE = int((1 << 31) - 1)
+ else:
+ # It's possible to have sizeof(long) != sizeof(Py_ssize_t).
+ class X(object):
+ def __len__(self):
+ return 1 << 31
+ try:
+ len(X())
+ except OverflowError:
+ # 32-bit
+ MAXSIZE = int((1 << 31) - 1)
+ else:
+ # 64-bit
+ MAXSIZE = int((1 << 63) - 1)
+ del X
+
+
+def _add_doc(func, doc):
+ """Add documentation to a function."""
+ func.__doc__ = doc
+
+
+def _import_module(name):
+ """Import module, returning the module after the last dot."""
+ __import__(name)
+ return sys.modules[name]
+
+
+class _LazyDescr(object):
+
+ def __init__(self, name):
+ self.name = name
+
+ def __get__(self, obj, tp):
+ result = self._resolve()
+ setattr(obj, self.name, result) # Invokes __set__.
+ try:
+ # This is a bit ugly, but it avoids running this again by
+ # removing this descriptor.
+ delattr(obj.__class__, self.name)
+ except AttributeError:
+ pass
+ return result
+
+
+class MovedModule(_LazyDescr):
+
+ def __init__(self, name, old, new=None):
+ super(MovedModule, self).__init__(name)
+ if PY3:
+ if new is None:
+ new = name
+ self.mod = new
+ else:
+ self.mod = old
+
+ def _resolve(self):
+ return _import_module(self.mod)
+
+ def __getattr__(self, attr):
+ _module = self._resolve()
+ value = getattr(_module, attr)
+ setattr(self, attr, value)
+ return value
+
+
+class _LazyModule(types.ModuleType):
+
+ def __init__(self, name):
+ super(_LazyModule, self).__init__(name)
+ self.__doc__ = self.__class__.__doc__
+
+ def __dir__(self):
+ attrs = ["__doc__", "__name__"]
+ attrs += [attr.name for attr in self._moved_attributes]
+ return attrs
+
+ # Subclasses should override this
+ _moved_attributes = []
+
+
+class MovedAttribute(_LazyDescr):
+
+ def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):
+ super(MovedAttribute, self).__init__(name)
+ if PY3:
+ if new_mod is None:
+ new_mod = name
+ self.mod = new_mod
+ if new_attr is None:
+ if old_attr is None:
+ new_attr = name
+ else:
+ new_attr = old_attr
+ self.attr = new_attr
+ else:
+ self.mod = old_mod
+ if old_attr is None:
+ old_attr = name
+ self.attr = old_attr
+
+ def _resolve(self):
+ module = _import_module(self.mod)
+ return getattr(module, self.attr)
+
+
+class _SixMetaPathImporter(object):
+ """
+ A meta path importer to import six.moves and its submodules.
+
+ This class implements a PEP302 finder and loader. It should be compatible
+ with Python 2.5 and all existing versions of Python3
+ """
+ def __init__(self, six_module_name):
+ self.name = six_module_name
+ self.known_modules = {}
+
+ def _add_module(self, mod, *fullnames):
+ for fullname in fullnames:
+ self.known_modules[self.name + "." + fullname] = mod
+
+ def _get_module(self, fullname):
+ return self.known_modules[self.name + "." + fullname]
+
+ def find_module(self, fullname, path=None):
+ if fullname in self.known_modules:
+ return self
+ return None
+
+ def __get_module(self, fullname):
+ try:
+ return self.known_modules[fullname]
+ except KeyError:
+ raise ImportError("This loader does not know module " + fullname)
+
+ def load_module(self, fullname):
+ try:
+ # in case of a reload
+ return sys.modules[fullname]
+ except KeyError:
+ pass
+ mod = self.__get_module(fullname)
+ if isinstance(mod, MovedModule):
+ mod = mod._resolve()
+ else:
+ mod.__loader__ = self
+ sys.modules[fullname] = mod
+ return mod
+
+ def is_package(self, fullname):
+ """
+ Return true, if the named module is a package.
+
+ We need this method to get correct spec objects with
+ Python 3.4 (see PEP451)
+ """
+ return hasattr(self.__get_module(fullname), "__path__")
+
+ def get_code(self, fullname):
+ """Return None
+
+ Required, if is_package is implemented"""
+ self.__get_module(fullname) # eventually raises ImportError
+ return None
+ get_source = get_code # same as get_code
+
+_importer = _SixMetaPathImporter(__name__)
+
+
+class _MovedItems(_LazyModule):
+ """Lazy loading of moved objects"""
+ __path__ = [] # mark as package
+
+
+_moved_attributes = [
+ MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),
+ MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),
+ MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"),
+ MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"),
+ MovedAttribute("intern", "__builtin__", "sys"),
+ MovedAttribute("map", "itertools", "builtins", "imap", "map"),
+ MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"),
+ MovedAttribute("reload_module", "__builtin__", "imp", "reload"),
+ MovedAttribute("reduce", "__builtin__", "functools"),
+ MovedAttribute("shlex_quote", "pipes", "shlex", "quote"),
+ MovedAttribute("StringIO", "StringIO", "io"),
+ MovedAttribute("UserDict", "UserDict", "collections"),
+ MovedAttribute("UserList", "UserList", "collections"),
+ MovedAttribute("UserString", "UserString", "collections"),
+ MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),
+ MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),
+ MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"),
+
+ MovedModule("builtins", "__builtin__"),
+ MovedModule("configparser", "ConfigParser"),
+ MovedModule("copyreg", "copy_reg"),
+ MovedModule("dbm_gnu", "gdbm", "dbm.gnu"),
+ MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"),
+ MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),
+ MovedModule("http_cookies", "Cookie", "http.cookies"),
+ MovedModule("html_entities", "htmlentitydefs", "html.entities"),
+ MovedModule("html_parser", "HTMLParser", "html.parser"),
+ MovedModule("http_client", "httplib", "http.client"),
+ MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"),
+ MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"),
+ MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"),
+ MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"),
+ MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),
+ MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),
+ MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),
+ MovedModule("cPickle", "cPickle", "pickle"),
+ MovedModule("queue", "Queue"),
+ MovedModule("reprlib", "repr"),
+ MovedModule("socketserver", "SocketServer"),
+ MovedModule("_thread", "thread", "_thread"),
+ MovedModule("tkinter", "Tkinter"),
+ MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),
+ MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),
+ MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),
+ MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),
+ MovedModule("tkinter_tix", "Tix", "tkinter.tix"),
+ MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"),
+ MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),
+ MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),
+ MovedModule("tkinter_colorchooser", "tkColorChooser",
+ "tkinter.colorchooser"),
+ MovedModule("tkinter_commondialog", "tkCommonDialog",
+ "tkinter.commondialog"),
+ MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),
+ MovedModule("tkinter_font", "tkFont", "tkinter.font"),
+ MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),
+ MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",
+ "tkinter.simpledialog"),
+ MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"),
+ MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"),
+ MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"),
+ MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),
+ MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"),
+ MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"),
+ MovedModule("winreg", "_winreg"),
+]
+for attr in _moved_attributes:
+ setattr(_MovedItems, attr.name, attr)
+ if isinstance(attr, MovedModule):
+ _importer._add_module(attr, "moves." + attr.name)
+del attr
+
+_MovedItems._moved_attributes = _moved_attributes
+
+moves = _MovedItems(__name__ + ".moves")
+_importer._add_module(moves, "moves")
+
+
+class Module_six_moves_urllib_parse(_LazyModule):
+ """Lazy loading of moved objects in six.moves.urllib_parse"""
+
+
+_urllib_parse_moved_attributes = [
+ MovedAttribute("ParseResult", "urlparse", "urllib.parse"),
+ MovedAttribute("SplitResult", "urlparse", "urllib.parse"),
+ MovedAttribute("parse_qs", "urlparse", "urllib.parse"),
+ MovedAttribute("parse_qsl", "urlparse", "urllib.parse"),
+ MovedAttribute("urldefrag", "urlparse", "urllib.parse"),
+ MovedAttribute("urljoin", "urlparse", "urllib.parse"),
+ MovedAttribute("urlparse", "urlparse", "urllib.parse"),
+ MovedAttribute("urlsplit", "urlparse", "urllib.parse"),
+ MovedAttribute("urlunparse", "urlparse", "urllib.parse"),
+ MovedAttribute("urlunsplit", "urlparse", "urllib.parse"),
+ MovedAttribute("quote", "urllib", "urllib.parse"),
+ MovedAttribute("quote_plus", "urllib", "urllib.parse"),
+ MovedAttribute("unquote", "urllib", "urllib.parse"),
+ MovedAttribute("unquote_plus", "urllib", "urllib.parse"),
+ MovedAttribute("urlencode", "urllib", "urllib.parse"),
+ MovedAttribute("splitquery", "urllib", "urllib.parse"),
+ MovedAttribute("splittag", "urllib", "urllib.parse"),
+ MovedAttribute("splituser", "urllib", "urllib.parse"),
+ MovedAttribute("uses_fragment", "urlparse", "urllib.parse"),
+ MovedAttribute("uses_netloc", "urlparse", "urllib.parse"),
+ MovedAttribute("uses_params", "urlparse", "urllib.parse"),
+ MovedAttribute("uses_query", "urlparse", "urllib.parse"),
+ MovedAttribute("uses_relative", "urlparse", "urllib.parse"),
+]
+for attr in _urllib_parse_moved_attributes:
+ setattr(Module_six_moves_urllib_parse, attr.name, attr)
+del attr
+
+Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes
+
+_importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"),
+ "moves.urllib_parse", "moves.urllib.parse")
+
+
+class Module_six_moves_urllib_error(_LazyModule):
+ """Lazy loading of moved objects in six.moves.urllib_error"""
+
+
+_urllib_error_moved_attributes = [
+ MovedAttribute("URLError", "urllib2", "urllib.error"),
+ MovedAttribute("HTTPError", "urllib2", "urllib.error"),
+ MovedAttribute("ContentTooShortError", "urllib", "urllib.error"),
+]
+for attr in _urllib_error_moved_attributes:
+ setattr(Module_six_moves_urllib_error, attr.name, attr)
+del attr
+
+Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes
+
+_importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"),
+ "moves.urllib_error", "moves.urllib.error")
+
+
+class Module_six_moves_urllib_request(_LazyModule):
+ """Lazy loading of moved objects in six.moves.urllib_request"""
+
+
+_urllib_request_moved_attributes = [
+ MovedAttribute("urlopen", "urllib2", "urllib.request"),
+ MovedAttribute("install_opener", "urllib2", "urllib.request"),
+ MovedAttribute("build_opener", "urllib2", "urllib.request"),
+ MovedAttribute("pathname2url", "urllib", "urllib.request"),
+ MovedAttribute("url2pathname", "urllib", "urllib.request"),
+ MovedAttribute("getproxies", "urllib", "urllib.request"),
+ MovedAttribute("Request", "urllib2", "urllib.request"),
+ MovedAttribute("OpenerDirector", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"),
+ MovedAttribute("ProxyHandler", "urllib2", "urllib.request"),
+ MovedAttribute("BaseHandler", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"),
+ MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"),
+ MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"),
+ MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"),
+ MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPHandler", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"),
+ MovedAttribute("FileHandler", "urllib2", "urllib.request"),
+ MovedAttribute("FTPHandler", "urllib2", "urllib.request"),
+ MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"),
+ MovedAttribute("UnknownHandler", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"),
+ MovedAttribute("urlretrieve", "urllib", "urllib.request"),
+ MovedAttribute("urlcleanup", "urllib", "urllib.request"),
+ MovedAttribute("URLopener", "urllib", "urllib.request"),
+ MovedAttribute("FancyURLopener", "urllib", "urllib.request"),
+ MovedAttribute("proxy_bypass", "urllib", "urllib.request"),
+]
+for attr in _urllib_request_moved_attributes:
+ setattr(Module_six_moves_urllib_request, attr.name, attr)
+del attr
+
+Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes
+
+_importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"),
+ "moves.urllib_request", "moves.urllib.request")
+
+
+class Module_six_moves_urllib_response(_LazyModule):
+ """Lazy loading of moved objects in six.moves.urllib_response"""
+
+
+_urllib_response_moved_attributes = [
+ MovedAttribute("addbase", "urllib", "urllib.response"),
+ MovedAttribute("addclosehook", "urllib", "urllib.response"),
+ MovedAttribute("addinfo", "urllib", "urllib.response"),
+ MovedAttribute("addinfourl", "urllib", "urllib.response"),
+]
+for attr in _urllib_response_moved_attributes:
+ setattr(Module_six_moves_urllib_response, attr.name, attr)
+del attr
+
+Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes
+
+_importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"),
+ "moves.urllib_response", "moves.urllib.response")
+
+
+class Module_six_moves_urllib_robotparser(_LazyModule):
+ """Lazy loading of moved objects in six.moves.urllib_robotparser"""
+
+
+_urllib_robotparser_moved_attributes = [
+ MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"),
+]
+for attr in _urllib_robotparser_moved_attributes:
+ setattr(Module_six_moves_urllib_robotparser, attr.name, attr)
+del attr
+
+Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes
+
+_importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"),
+ "moves.urllib_robotparser", "moves.urllib.robotparser")
+
+
+class Module_six_moves_urllib(types.ModuleType):
+ """Create a six.moves.urllib namespace that resembles the Python 3 namespace"""
+ __path__ = [] # mark as package
+ parse = _importer._get_module("moves.urllib_parse")
+ error = _importer._get_module("moves.urllib_error")
+ request = _importer._get_module("moves.urllib_request")
+ response = _importer._get_module("moves.urllib_response")
+ robotparser = _importer._get_module("moves.urllib_robotparser")
+
+ def __dir__(self):
+ return ['parse', 'error', 'request', 'response', 'robotparser']
+
+_importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"),
+ "moves.urllib")
+
+
+def add_move(move):
+ """Add an item to six.moves."""
+ setattr(_MovedItems, move.name, move)
+
+
+def remove_move(name):
+ """Remove item from six.moves."""
+ try:
+ delattr(_MovedItems, name)
+ except AttributeError:
+ try:
+ del moves.__dict__[name]
+ except KeyError:
+ raise AttributeError("no such move, %r" % (name,))
+
+
+if PY3:
+ _meth_func = "__func__"
+ _meth_self = "__self__"
+
+ _func_closure = "__closure__"
+ _func_code = "__code__"
+ _func_defaults = "__defaults__"
+ _func_globals = "__globals__"
+else:
+ _meth_func = "im_func"
+ _meth_self = "im_self"
+
+ _func_closure = "func_closure"
+ _func_code = "func_code"
+ _func_defaults = "func_defaults"
+ _func_globals = "func_globals"
+
+
+try:
+ advance_iterator = next
+except NameError:
+ def advance_iterator(it):
+ return it.next()
+next = advance_iterator
+
+
+try:
+ callable = callable
+except NameError:
+ def callable(obj):
+ return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
+
+
+if PY3:
+ def get_unbound_function(unbound):
+ return unbound
+
+ create_bound_method = types.MethodType
+
+ Iterator = object
+else:
+ def get_unbound_function(unbound):
+ return unbound.im_func
+
+ def create_bound_method(func, obj):
+ return types.MethodType(func, obj, obj.__class__)
+
+ class Iterator(object):
+
+ def next(self):
+ return type(self).__next__(self)
+
+ callable = callable
+_add_doc(get_unbound_function,
+ """Get the function out of a possibly unbound function""")
+
+
+get_method_function = operator.attrgetter(_meth_func)
+get_method_self = operator.attrgetter(_meth_self)
+get_function_closure = operator.attrgetter(_func_closure)
+get_function_code = operator.attrgetter(_func_code)
+get_function_defaults = operator.attrgetter(_func_defaults)
+get_function_globals = operator.attrgetter(_func_globals)
+
+
+if PY3:
+ def iterkeys(d, **kw):
+ return iter(d.keys(**kw))
+
+ def itervalues(d, **kw):
+ return iter(d.values(**kw))
+
+ def iteritems(d, **kw):
+ return iter(d.items(**kw))
+
+ def iterlists(d, **kw):
+ return iter(d.lists(**kw))
+
+ viewkeys = operator.methodcaller("keys")
+
+ viewvalues = operator.methodcaller("values")
+
+ viewitems = operator.methodcaller("items")
+else:
+ def iterkeys(d, **kw):
+ return iter(d.iterkeys(**kw))
+
+ def itervalues(d, **kw):
+ return iter(d.itervalues(**kw))
+
+ def iteritems(d, **kw):
+ return iter(d.iteritems(**kw))
+
+ def iterlists(d, **kw):
+ return iter(d.iterlists(**kw))
+
+ viewkeys = operator.methodcaller("viewkeys")
+
+ viewvalues = operator.methodcaller("viewvalues")
+
+ viewitems = operator.methodcaller("viewitems")
+
+_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.")
+_add_doc(itervalues, "Return an iterator over the values of a dictionary.")
+_add_doc(iteritems,
+ "Return an iterator over the (key, value) pairs of a dictionary.")
+_add_doc(iterlists,
+ "Return an iterator over the (key, [values]) pairs of a dictionary.")
+
+
+if PY3:
+ def b(s):
+ return s.encode("latin-1")
+ def u(s):
+ return s
+ unichr = chr
+ if sys.version_info[1] <= 1:
+ def int2byte(i):
+ return bytes((i,))
+ else:
+ # This is about 2x faster than the implementation above on 3.2+
+ int2byte = operator.methodcaller("to_bytes", 1, "big")
+ byte2int = operator.itemgetter(0)
+ indexbytes = operator.getitem
+ iterbytes = iter
+ import io
+ StringIO = io.StringIO
+ BytesIO = io.BytesIO
+ _assertCountEqual = "assertCountEqual"
+ _assertRaisesRegex = "assertRaisesRegex"
+ _assertRegex = "assertRegex"
+else:
+ def b(s):
+ return s
+ # Workaround for standalone backslash
+ def u(s):
+ return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")
+ unichr = unichr
+ int2byte = chr
+ def byte2int(bs):
+ return ord(bs[0])
+ def indexbytes(buf, i):
+ return ord(buf[i])
+ iterbytes = functools.partial(itertools.imap, ord)
+ import StringIO
+ StringIO = BytesIO = StringIO.StringIO
+ _assertCountEqual = "assertItemsEqual"
+ _assertRaisesRegex = "assertRaisesRegexp"
+ _assertRegex = "assertRegexpMatches"
+_add_doc(b, """Byte literal""")
+_add_doc(u, """Text literal""")
+
+
+def assertCountEqual(self, *args, **kwargs):
+ return getattr(self, _assertCountEqual)(*args, **kwargs)
+
+
+def assertRaisesRegex(self, *args, **kwargs):
+ return getattr(self, _assertRaisesRegex)(*args, **kwargs)
+
+
+def assertRegex(self, *args, **kwargs):
+ return getattr(self, _assertRegex)(*args, **kwargs)
+
+
+if PY3:
+ exec_ = getattr(moves.builtins, "exec")
+
+
+ def reraise(tp, value, tb=None):
+ if value is None:
+ value = tp()
+ if value.__traceback__ is not tb:
+ raise value.with_traceback(tb)
+ raise value
+
+else:
+ def exec_(_code_, _globs_=None, _locs_=None):
+ """Execute code in a namespace."""
+ if _globs_ is None:
+ frame = sys._getframe(1)
+ _globs_ = frame.f_globals
+ if _locs_ is None:
+ _locs_ = frame.f_locals
+ del frame
+ elif _locs_ is None:
+ _locs_ = _globs_
+ exec("""exec _code_ in _globs_, _locs_""")
+
+
+ exec_("""def reraise(tp, value, tb=None):
+ raise tp, value, tb
+""")
+
+
+if sys.version_info[:2] == (3, 2):
+ exec_("""def raise_from(value, from_value):
+ if from_value is None:
+ raise value
+ raise value from from_value
+""")
+elif sys.version_info[:2] > (3, 2):
+ exec_("""def raise_from(value, from_value):
+ raise value from from_value
+""")
+else:
+ def raise_from(value, from_value):
+ raise value
+
+
+print_ = getattr(moves.builtins, "print", None)
+if print_ is None:
+ def print_(*args, **kwargs):
+ """The new-style print function for Python 2.4 and 2.5."""
+ fp = kwargs.pop("file", sys.stdout)
+ if fp is None:
+ return
+ def write(data):
+ if not isinstance(data, basestring):
+ data = str(data)
+ # If the file has an encoding, encode unicode with it.
+ if (isinstance(fp, file) and
+ isinstance(data, unicode) and
+ fp.encoding is not None):
+ errors = getattr(fp, "errors", None)
+ if errors is None:
+ errors = "strict"
+ data = data.encode(fp.encoding, errors)
+ fp.write(data)
+ want_unicode = False
+ sep = kwargs.pop("sep", None)
+ if sep is not None:
+ if isinstance(sep, unicode):
+ want_unicode = True
+ elif not isinstance(sep, str):
+ raise TypeError("sep must be None or a string")
+ end = kwargs.pop("end", None)
+ if end is not None:
+ if isinstance(end, unicode):
+ want_unicode = True
+ elif not isinstance(end, str):
+ raise TypeError("end must be None or a string")
+ if kwargs:
+ raise TypeError("invalid keyword arguments to print()")
+ if not want_unicode:
+ for arg in args:
+ if isinstance(arg, unicode):
+ want_unicode = True
+ break
+ if want_unicode:
+ newline = unicode("\n")
+ space = unicode(" ")
+ else:
+ newline = "\n"
+ space = " "
+ if sep is None:
+ sep = space
+ if end is None:
+ end = newline
+ for i, arg in enumerate(args):
+ if i:
+ write(sep)
+ write(arg)
+ write(end)
+if sys.version_info[:2] < (3, 3):
+ _print = print_
+ def print_(*args, **kwargs):
+ fp = kwargs.get("file", sys.stdout)
+ flush = kwargs.pop("flush", False)
+ _print(*args, **kwargs)
+ if flush and fp is not None:
+ fp.flush()
+
+_add_doc(reraise, """Reraise an exception.""")
+
+if sys.version_info[0:2] < (3, 4):
+ def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS,
+ updated=functools.WRAPPER_UPDATES):
+ def wrapper(f):
+ f = functools.wraps(wrapped, assigned, updated)(f)
+ f.__wrapped__ = wrapped
+ return f
+ return wrapper
+else:
+ wraps = functools.wraps
+
+def with_metaclass(meta, *bases):
+ """Create a base class with a metaclass."""
+ # This requires a bit of explanation: the basic idea is to make a dummy
+ # metaclass for one level of class instantiation that replaces itself with
+ # the actual metaclass.
+ class metaclass(meta):
+ def __new__(cls, name, this_bases, d):
+ return meta(name, bases, d)
+ return type.__new__(metaclass, 'temporary_class', (), {})
+
+
+def add_metaclass(metaclass):
+ """Class decorator for creating a class with a metaclass."""
+ def wrapper(cls):
+ orig_vars = cls.__dict__.copy()
+ slots = orig_vars.get('__slots__')
+ if slots is not None:
+ if isinstance(slots, str):
+ slots = [slots]
+ for slots_var in slots:
+ orig_vars.pop(slots_var)
+ orig_vars.pop('__dict__', None)
+ orig_vars.pop('__weakref__', None)
+ return metaclass(cls.__name__, cls.__bases__, orig_vars)
+ return wrapper
+
+
+def python_2_unicode_compatible(klass):
+ """
+ A decorator that defines __unicode__ and __str__ methods under Python 2.
+ Under Python 3 it does nothing.
+
+ To support Python 2 and 3 with a single code base, define a __str__ method
+ returning text and apply this decorator to the class.
+ """
+ if PY2:
+ if '__str__' not in klass.__dict__:
+ raise ValueError("@python_2_unicode_compatible cannot be applied "
+ "to %s because it doesn't define __str__()." %
+ klass.__name__)
+ klass.__unicode__ = klass.__str__
+ klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
+ return klass
+
+
+# Complete the moves implementation.
+# This code is at the end of this module to speed up module loading.
+# Turn this module into a package.
+__path__ = [] # required for PEP 302 and PEP 451
+__package__ = __name__ # see PEP 366 @ReservedAssignment
+if globals().get("__spec__") is not None:
+ __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable
+# Remove other six meta path importers, since they cause problems. This can
+# happen if six is removed from sys.modules and then reloaded. (Setuptools does
+# this for some reason.)
+if sys.meta_path:
+ for i, importer in enumerate(sys.meta_path):
+ # Here's some real nastiness: Another "instance" of the six module might
+ # be floating around. Therefore, we can't use isinstance() to check for
+ # the six meta path importer, since the other six instance will have
+ # inserted an importer with different class.
+ if (type(importer).__name__ == "_SixMetaPathImporter" and
+ importer.name == __name__):
+ del sys.meta_path[i]
+ break
+ del i, importer
+# Finally, add the importer to the meta path import hook.
+sys.meta_path.append(_importer)
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org
[3/4] qpid-proton git commit: PROTON-490: port python C wrapper to
Python 3
Posted by kg...@apache.org.
PROTON-490: port python C wrapper to Python 3
Original patch provided by Mickael Maison.
Project: http://git-wip-us.apache.org/repos/asf/qpid-proton/repo
Commit: http://git-wip-us.apache.org/repos/asf/qpid-proton/commit/efa1f684
Tree: http://git-wip-us.apache.org/repos/asf/qpid-proton/tree/efa1f684
Diff: http://git-wip-us.apache.org/repos/asf/qpid-proton/diff/efa1f684
Branch: refs/heads/kgiusti-python3
Commit: efa1f6840225baf6902d7b0eff3d6c3e2f994bc2
Parents: 93ccc73
Author: Ken Giusti <kg...@apache.org>
Authored: Wed Apr 22 15:13:01 2015 -0400
Committer: Ken Giusti <kg...@apache.org>
Committed: Wed Apr 22 15:13:01 2015 -0400
----------------------------------------------------------------------
proton-c/bindings/python/cproton.i | 62 ++++++++++++++++--------
proton-c/bindings/python/proton/__init__.py | 33 ++++++++++---
proton-c/bindings/python/proton/handlers.py | 4 +-
proton-c/bindings/python/proton/reactor.py | 6 ++-
proton-c/bindings/python/proton/utils.py | 4 +-
5 files changed, 77 insertions(+), 32 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/efa1f684/proton-c/bindings/python/cproton.i
----------------------------------------------------------------------
diff --git a/proton-c/bindings/python/cproton.i b/proton-c/bindings/python/cproton.i
index 70d6c42..5744a2d 100644
--- a/proton-c/bindings/python/cproton.i
+++ b/proton-c/bindings/python/cproton.i
@@ -38,6 +38,27 @@
%cstring_output_allocate_size(char **ALLOC_OUTPUT, size_t *ALLOC_SIZE, free(*$1));
%cstring_output_maxsize(char *OUTPUT, size_t MAX_OUTPUT_SIZE)
+// Typemap for methods that return binary data:
+// force the return type as binary - this is necessary for Python3
+%typemap(in,noblock=1,fragment=SWIG_AsVal_frag(size_t)) (char *BIN_OUT, size_t *BIN_SIZE)
+(int res, size_t n, char *buff = 0, $*2_ltype size) {
+ res = SWIG_AsVal(size_t)($input, &n);
+ if (!SWIG_IsOK(res)) {
+ %argument_fail(res, "(char *BIN_OUT, size_t *BIN_SIZE)", $symname, $argnum);
+ }
+ buff= %new_array(n+1, char);
+ $1 = %static_cast(buff, $1_ltype);
+ size = %numeric_cast(n,$*2_ltype);
+ $2 = &size;
+}
+%typemap(freearg,noblock=1,match="in")(char *BIN_OUT, size_t *BIN_SIZE) {
+ if (buff$argnum) %delete_array(buff$argnum);
+}
+%typemap(argout,noblock=1) (char *BIN_OUT, size_t *BIN_SIZE) {
+ %append_output(PyBytes_FromStringAndSize($1,*$2));
+}
+
+
// These are not used/needed in the python binding
%ignore pn_message_get_id;
%ignore pn_message_set_id;
@@ -49,20 +70,21 @@
$1.start = NULL;
$1.size = 0;
} else {
- $1.start = PyString_AsString($input);
+ $1.start = PyBytes_AsString($input);
+
if (!$1.start) {
return NULL;
}
- $1.size = PyString_Size($input);
+ $1.size = PyBytes_Size($input);
}
}
%typemap(out) pn_bytes_t {
- $result = PyString_FromStringAndSize($1.start, $1.size);
+ $result = PyBytes_FromStringAndSize($1.start, $1.size);
}
%typemap(out) pn_delivery_tag_t {
- $result = PyString_FromStringAndSize($1.bytes, $1.size);
+ $result = PyBytes_FromStringAndSize($1.bytes, $1.size);
}
%typemap(in) pn_uuid_t {
@@ -70,9 +92,9 @@
if ($input == Py_None) {
; // Already zeroed out
} else {
- const char* b = PyString_AsString($input);
+ const char* b = PyBytes_AsString($input);
if (b) {
- memmove($1.bytes, b, (PyString_Size($input) < 16 ? PyString_Size($input) : 16));
+ memmove($1.bytes, b, (PyBytes_Size($input) < 16 ? PyBytes_Size($input) : 16));
} else {
return NULL;
}
@@ -80,12 +102,12 @@
}
%typemap(out) pn_uuid_t {
- $result = PyString_FromStringAndSize($1.bytes, 16);
+ $result = PyBytes_FromStringAndSize($1.bytes, 16);
}
%apply pn_uuid_t { pn_decimal128_t };
-int pn_message_encode(pn_message_t *msg, char *OUTPUT, size_t *OUTPUT_SIZE);
+int pn_message_encode(pn_message_t *msg, char *BIN_OUT, size_t *BIN_SIZE);
%ignore pn_message_encode;
ssize_t pn_link_send(pn_link_t *transport, char *STRING, size_t LENGTH);
@@ -93,12 +115,12 @@ ssize_t pn_link_send(pn_link_t *transport, char *STRING, size_t LENGTH);
%rename(pn_link_recv) wrap_pn_link_recv;
%inline %{
- int wrap_pn_link_recv(pn_link_t *link, char *OUTPUT, size_t *OUTPUT_SIZE) {
- ssize_t sz = pn_link_recv(link, OUTPUT, *OUTPUT_SIZE);
+ int wrap_pn_link_recv(pn_link_t *link, char *BIN_OUT, size_t *BIN_SIZE) {
+ ssize_t sz = pn_link_recv(link, BIN_OUT, *BIN_SIZE);
if (sz >= 0) {
- *OUTPUT_SIZE = sz;
+ *BIN_SIZE = sz;
} else {
- *OUTPUT_SIZE = 0;
+ *BIN_SIZE = 0;
}
return sz;
}
@@ -110,12 +132,12 @@ ssize_t pn_transport_push(pn_transport_t *transport, char *STRING, size_t LENGTH
%rename(pn_transport_peek) wrap_pn_transport_peek;
%inline %{
- int wrap_pn_transport_peek(pn_transport_t *transport, char *OUTPUT, size_t *OUTPUT_SIZE) {
- ssize_t sz = pn_transport_peek(transport, OUTPUT, *OUTPUT_SIZE);
+ int wrap_pn_transport_peek(pn_transport_t *transport, char *BIN_OUT, size_t *BIN_SIZE) {
+ ssize_t sz = pn_transport_peek(transport, BIN_OUT, *BIN_SIZE);
if (sz >= 0) {
- *OUTPUT_SIZE = sz;
+ *BIN_SIZE = sz;
} else {
- *OUTPUT_SIZE = 0;
+ *BIN_SIZE = 0;
}
return sz;
}
@@ -146,12 +168,12 @@ ssize_t pn_data_decode(pn_data_t *data, char *STRING, size_t LENGTH);
%rename(pn_data_encode) wrap_pn_data_encode;
%inline %{
- int wrap_pn_data_encode(pn_data_t *data, char *OUTPUT, size_t *OUTPUT_SIZE) {
- ssize_t sz = pn_data_encode(data, OUTPUT, *OUTPUT_SIZE);
+ int wrap_pn_data_encode(pn_data_t *data, char *BIN_OUT, size_t *BIN_SIZE) {
+ ssize_t sz = pn_data_encode(data, BIN_OUT, *BIN_SIZE);
if (sz >= 0) {
- *OUTPUT_SIZE = sz;
+ *BIN_SIZE = sz;
} else {
- *OUTPUT_SIZE = 0;
+ *BIN_SIZE = 0;
}
return sz;
}
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/efa1f684/proton-c/bindings/python/proton/__init__.py
----------------------------------------------------------------------
diff --git a/proton-c/bindings/python/proton/__init__.py b/proton-c/bindings/python/proton/__init__.py
index cf73a53..8871eda 100644
--- a/proton-c/bindings/python/proton/__init__.py
+++ b/proton-c/bindings/python/proton/__init__.py
@@ -34,7 +34,9 @@ from __future__ import absolute_import
from cproton import *
from .wrapper import Wrapper
+import six
import weakref, socket, sys, threading
+
try:
import uuid
@@ -94,10 +96,22 @@ except ImportError:
def generate_uuid():
return uuid4()
+#
+# Hacks to provide Python2 <---> Python3 compatibility
+#
try:
bytes()
except NameError:
bytes = str
+try:
+ long()
+except NameError:
+ long = int
+try:
+ unicode()
+except NameError:
+ unicode = str
+
VERSION_MAJOR = PN_VERSION_MAJOR
VERSION_MINOR = PN_VERSION_MINOR
@@ -936,7 +950,7 @@ The number of delivery attempts made for this message.
def _get_id(self):
return self._id.get_object()
def _set_id(self, value):
- if type(value) in (int, long):
+ if type(value) in six.integer_types:
value = ulong(value)
self._id.rewind()
self._id.put_object(value)
@@ -992,7 +1006,7 @@ The reply-to address for the message.
def _get_correlation_id(self):
return self._correlation_id.get_object()
def _set_correlation_id(self, value):
- if type(value) in (int, long):
+ if type(value) in six.integer_types:
value = ulong(value)
self._correlation_id.rewind()
self._correlation_id.put_object(value)
@@ -1424,7 +1438,7 @@ class Data:
def type_name(type): return Data.type_names[type]
def __init__(self, capacity=16):
- if type(capacity) in (int, long):
+ if type(capacity) in six.integer_types:
self._data = pn_data(capacity)
self._free = True
else:
@@ -2146,7 +2160,6 @@ class Data:
symbol: put_symbol,
int: put_long,
char: put_char,
- long: put_long,
ulong: put_ulong,
timestamp: put_timestamp,
float: put_double,
@@ -2154,6 +2167,10 @@ class Data:
Described: put_py_described,
Array: put_py_array
}
+ # for python 2.x:
+ if long not in put_mappings:
+ put_mappings[long] = put_long
+
get_mappings = {
NULL: lambda s: None,
BOOL: get_bool,
@@ -2319,7 +2336,7 @@ def millis2timeout(millis):
def unicode2utf8(string):
if string is None:
return None
- if isinstance(string, unicode):
+ if isinstance(string, six.text_type):
return string.encode('utf8')
elif isinstance(string, str):
return string
@@ -2329,7 +2346,7 @@ def unicode2utf8(string):
def utf82unicode(string):
if string is None:
return None
- if isinstance(string, unicode):
+ if isinstance(string, six.text_type):
return string
elif isinstance(string, str):
return string.decode('utf8')
@@ -3733,7 +3750,7 @@ class _cadapter:
def exception(self, exc, val, tb):
if self.on_error is None:
- raise exc, val, tb
+ six.reraise(exc, val, tb)
else:
self.on_error((exc, val, tb))
@@ -3754,7 +3771,7 @@ class WrappedHandler(Wrapper):
def _on_error(self, info):
on_error = getattr(self, "on_error", None)
if on_error is None:
- raise info[0], info[1], info[2]
+ six.reraise(info[0], info[1], info[2])
else:
on_error(info)
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/efa1f684/proton-c/bindings/python/proton/handlers.py
----------------------------------------------------------------------
diff --git a/proton-c/bindings/python/proton/handlers.py b/proton-c/bindings/python/proton/handlers.py
index 6836788..8f00aa3 100644
--- a/proton-c/bindings/python/proton/handlers.py
+++ b/proton-c/bindings/python/proton/handlers.py
@@ -16,7 +16,9 @@
# specific language governing permissions and limitations
# under the License.
#
-import heapq, logging, os, Queue, re, socket, time, types
+import heapq, logging, os, re, socket, time, types
+from six.moves import queue as Queue
+
from proton import dispatch, generate_uuid, PN_ACCEPTED, SASL, symbol, ulong, Url
from proton import Collector, Connection, Delivery, Described, Endpoint, Event, Link, Terminus, Timeout
from proton import Message, Handler, ProtonException, Transport, TransportException, ConnectionException
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/efa1f684/proton-c/bindings/python/proton/reactor.py
----------------------------------------------------------------------
diff --git a/proton-c/bindings/python/proton/reactor.py b/proton-c/bindings/python/proton/reactor.py
index 03d8af3..a9bd3cc 100644
--- a/proton-c/bindings/python/proton/reactor.py
+++ b/proton-c/bindings/python/proton/reactor.py
@@ -17,7 +17,9 @@ from __future__ import absolute_import
# specific language governing permissions and limitations
# under the License.
#
-import logging, os, Queue, socket, time, types
+import logging, os, socket, time, types
+import six
+from six.moves import queue as Queue
from heapq import heappush, heappop, nsmallest
from proton import Collector, Connection, ConnectionException, Delivery, Described, dispatch
from proton import Endpoint, Event, EventBase, EventType, generate_uuid, Handler, Link, Message
@@ -137,7 +139,7 @@ class Reactor(Wrapper):
for exc, value, tb in self.errors[:-1]:
traceback.print_exception(exc, value, tb)
exc, value, tb = self.errors[-1]
- raise exc, value, tb
+ six.reraise(exc, value, tb)
def process(self):
result = pn_reactor_process(self._impl)
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/efa1f684/proton-c/bindings/python/proton/utils.py
----------------------------------------------------------------------
diff --git a/proton-c/bindings/python/proton/utils.py b/proton-c/bindings/python/proton/utils.py
index cb65fda..0d7f39e 100644
--- a/proton-c/bindings/python/proton/utils.py
+++ b/proton-c/bindings/python/proton/utils.py
@@ -16,7 +16,9 @@
# specific language governing permissions and limitations
# under the License.
#
-import collections, Queue, socket, time, threading
+import collections, socket, time, threading
+from six.moves import queue as Queue
+
from proton import ConnectionException, Delivery, Endpoint, Handler, LinkException, Message
from proton import ProtonException, Timeout, Url
from proton.reactor import Container
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org
[4/4] qpid-proton git commit: PROTON-490: get the python unit test to
run in Python 3
Posted by kg...@apache.org.
PROTON-490: get the python unit test to run in Python 3
Project: http://git-wip-us.apache.org/repos/asf/qpid-proton/repo
Commit: http://git-wip-us.apache.org/repos/asf/qpid-proton/commit/99299d3b
Tree: http://git-wip-us.apache.org/repos/asf/qpid-proton/tree/99299d3b
Diff: http://git-wip-us.apache.org/repos/asf/qpid-proton/diff/99299d3b
Branch: refs/heads/kgiusti-python3
Commit: 99299d3b33e5e5ae9fbeff51ac6b7b25cacd6e85
Parents: efa1f68
Author: Ken Giusti <kg...@apache.org>
Authored: Wed Apr 22 16:54:25 2015 -0400
Committer: Ken Giusti <kg...@apache.org>
Committed: Fri Apr 24 15:59:03 2015 -0400
----------------------------------------------------------------------
proton-c/bindings/python/cproton.i | 12 ++-
proton-c/bindings/python/proton/__init__.py | 97 ++++++++++--------
proton-c/bindings/python/proton/reactor.py | 10 +-
proton-c/bindings/python/proton/utils.py | 14 +--
proton-c/bindings/python/proton/wrapper.py | 12 ++-
proton-j/src/main/resources/cmessage.py | 2 +-
tests/python/proton-test | 28 ++---
tests/python/proton_tests/codec.py | 109 ++++++++++----------
tests/python/proton_tests/common.py | 9 +-
tests/python/proton_tests/engine.py | 125 +++++++++++++----------
tests/python/proton_tests/interop.py | 23 +++--
tests/python/proton_tests/message.py | 6 +-
tests/python/proton_tests/messenger.py | 1 +
tests/python/proton_tests/sasl.py | 11 +-
tests/python/proton_tests/transport.py | 25 ++---
tests/python/proton_tests/utils.py | 1 +
tests/tools/apps/python/msgr-recv.py | 5 +
tests/tools/apps/python/msgr-send.py | 5 +
tests/tools/soak-check | 5 +-
19 files changed, 279 insertions(+), 221 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/99299d3b/proton-c/bindings/python/cproton.i
----------------------------------------------------------------------
diff --git a/proton-c/bindings/python/cproton.i b/proton-c/bindings/python/cproton.i
index 5744a2d..328d68a 100644
--- a/proton-c/bindings/python/cproton.i
+++ b/proton-c/bindings/python/cproton.i
@@ -38,6 +38,9 @@
%cstring_output_allocate_size(char **ALLOC_OUTPUT, size_t *ALLOC_SIZE, free(*$1));
%cstring_output_maxsize(char *OUTPUT, size_t MAX_OUTPUT_SIZE)
+%include <pybuffer.i>
+%pybuffer_binary(const char *BIN_IN, size_t BIN_LEN)
+
// Typemap for methods that return binary data:
// force the return type as binary - this is necessary for Python3
%typemap(in,noblock=1,fragment=SWIG_AsVal_frag(size_t)) (char *BIN_OUT, size_t *BIN_SIZE)
@@ -110,7 +113,10 @@
int pn_message_encode(pn_message_t *msg, char *BIN_OUT, size_t *BIN_SIZE);
%ignore pn_message_encode;
-ssize_t pn_link_send(pn_link_t *transport, char *STRING, size_t LENGTH);
+int pn_message_decode(pn_message_t *msg, const char *BIN_IN, size_t BIN_LEN);
+%ignore pn_message_encode;
+
+ssize_t pn_link_send(pn_link_t *transport, const char *BIN_IN, size_t BIN_LEN);
%ignore pn_link_send;
%rename(pn_link_recv) wrap_pn_link_recv;
@@ -127,7 +133,7 @@ ssize_t pn_link_send(pn_link_t *transport, char *STRING, size_t LENGTH);
%}
%ignore pn_link_recv;
-ssize_t pn_transport_push(pn_transport_t *transport, char *STRING, size_t LENGTH);
+ssize_t pn_transport_push(pn_transport_t *transport, const char *BIN_IN, size_t BIN_LEN);
%ignore pn_transport_push;
%rename(pn_transport_peek) wrap_pn_transport_peek;
@@ -163,7 +169,7 @@ ssize_t pn_transport_push(pn_transport_t *transport, char *STRING, size_t LENGTH
%}
%ignore pn_delivery_tag;
-ssize_t pn_data_decode(pn_data_t *data, char *STRING, size_t LENGTH);
+ssize_t pn_data_decode(pn_data_t *data, const char *BIN_IN, size_t BIN_LEN);
%ignore pn_data_decode;
%rename(pn_data_encode) wrap_pn_data_encode;
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/99299d3b/proton-c/bindings/python/proton/__init__.py
----------------------------------------------------------------------
diff --git a/proton-c/bindings/python/proton/__init__.py b/proton-c/bindings/python/proton/__init__.py
index 8871eda..399aec7 100644
--- a/proton-c/bindings/python/proton/__init__.py
+++ b/proton-c/bindings/python/proton/__init__.py
@@ -79,16 +79,16 @@ except ImportError:
rand = random.Random()
rand.seed((os.getpid(), time.time(), socket.gethostname()))
def random_uuid():
- bytes = [rand.randint(0, 255) for i in xrange(16)]
+ data = [rand.randint(0, 255) for i in xrange(16)]
# From RFC4122, the version bits are set to 0100
- bytes[7] &= 0x0F
- bytes[7] |= 0x40
+ data[7] &= 0x0F
+ data[7] |= 0x40
# From RFC4122, the top two bits of byte 8 get set to 01
- bytes[8] &= 0x3F
- bytes[8] |= 0x80
- return "".join(map(chr, bytes))
+ data[8] &= 0x3F
+ data[8] |= 0x80
+ return "".join(map(chr, data))
def uuid4():
return uuid.UUID(bytes=random_uuid())
@@ -805,7 +805,7 @@ class Message(object):
self.annotations = None
self.properties = None
self.body = body
- for k,v in kwargs.iteritems():
+ for k,v in six.iteritems(kwargs):
getattr(self, k) # Raise exception if it's not a valid attribute.
setattr(self, k, v)
@@ -846,19 +846,19 @@ class Message(object):
props = Data(pn_message_properties(self._msg))
body = Data(pn_message_body(self._msg))
- if next(inst):
+ if inst.next():
self.instructions = inst.get_object()
else:
self.instructions = None
- if next(ann):
+ if ann.next():
self.annotations = ann.get_object()
else:
self.annotations = None
- if next(props):
+ if props.next():
self.properties = props.get_object()
else:
self.properties = None
- if next(body):
+ if body.next():
self.body = body.get_object()
else:
self.body = None
@@ -1106,7 +1106,7 @@ The group-id for any replies.
return data
def decode(self, data):
- self._check(pn_message_decode(self._msg, data, len(data)))
+ self._check(pn_message_decode(self._msg, data))
self._post_decode()
def send(self, sender, tag=None):
@@ -1803,7 +1803,7 @@ class Data:
@type s: string
@param s: the symbol name
"""
- self._check(pn_data_put_symbol(self._data, s))
+ self._check(pn_data_put_symbol(self._data, s.encode('ascii')))
def get_list(self):
"""
@@ -1941,7 +1941,7 @@ class Data:
If the current node is a char, returns its value, returns 0
otherwise.
"""
- return char(unichr(pn_data_get_char(self._data)))
+ return char(six.unichr(pn_data_get_char(self._data)))
def get_ulong(self):
"""
@@ -2031,7 +2031,7 @@ class Data:
If the current node is a symbol, returns its value, returns ""
otherwise.
"""
- return symbol(pn_data_get_symbol(self._data))
+ return symbol(pn_data_get_symbol(self._data).decode('ascii'))
def copy(self, src):
self._check(pn_data_copy(self._data, src._data))
@@ -2064,9 +2064,9 @@ class Data:
if self.enter():
try:
result = {}
- while next(self):
+ while self.next():
k = self.get_object()
- if next(self):
+ if self.next():
v = self.get_object()
else:
v = None
@@ -2088,7 +2088,7 @@ class Data:
if self.enter():
try:
result = []
- while next(self):
+ while self.next():
result.append(self.get_object())
finally:
self.exit()
@@ -2097,9 +2097,9 @@ class Data:
def get_py_described(self):
if self.enter():
try:
- next(self)
+ self.next()
descriptor = self.get_object()
- next(self)
+ self.next()
value = self.get_object()
finally:
self.exit()
@@ -2126,12 +2126,12 @@ class Data:
if self.enter():
try:
if described:
- next(self)
+ self.next()
descriptor = self.get_object()
else:
descriptor = UNDESCRIBED
elements = []
- while next(self):
+ while self.next():
elements.append(self.get_object())
finally:
self.exit()
@@ -2309,7 +2309,7 @@ def dat2obj(dimpl):
if dimpl:
d = Data(dimpl)
d.rewind()
- next(d)
+ d.next()
obj = d.get_object()
d.rewind()
return obj
@@ -2334,21 +2334,34 @@ def millis2timeout(millis):
return millis2secs(millis)
def unicode2utf8(string):
+ """Some Proton APIs expect a null terminated string. Convert python text
+ types to UTF8 to avoid zero bytes introduced by other multi-byte encodings.
+ This method will throw if the string cannot be converted.
+ """
if string is None:
return None
- if isinstance(string, six.text_type):
- return string.encode('utf8')
- elif isinstance(string, str):
- return string
- else:
- raise TypeError("Unrecognized string type: %r" % string)
+ if six.PY2:
+ if isinstance(string, unicode):
+ return string.encode('utf-8')
+ elif isinstance(string, str):
+ return string
+ elif six.PY3:
+ # decoding a string results in bytes
+ if isinstance(string, str):
+ string = string.encode('utf-8')
+ # fall through
+ if isinstance(string, bytes):
+ return string.decode('utf-8')
+ raise TypeError("Unrecognized string type: %r (%s)" % (string, type(string)))
def utf82unicode(string):
+ """Covert C strings returned from proton-c into python unicode"""
if string is None:
return None
if isinstance(string, six.text_type):
+ # already unicode
return string
- elif isinstance(string, str):
+ elif isinstance(string, six.binary_type):
return string.decode('utf8')
else:
raise TypeError("Unrecognized string type")
@@ -2872,11 +2885,16 @@ class Sender(Link):
def offered(self, n):
pn_link_offered(self._impl, n)
- def stream(self, bytes):
+ def stream(self, data):
"""
- Send specified bytes as part of the current delivery
+ Send specified data as part of the current delivery
+
+ @type data: binary
+ @param data: data to send
"""
- return self._check(pn_link_send(self._impl, bytes))
+ #if six.PY3 and isinstance(data, six.text_type):
+ # data = data.encode('utf-8')
+ return self._check(pn_link_send(self._impl, data))
def send(self, obj, tag=None):
"""
@@ -2913,12 +2931,12 @@ class Receiver(Link):
pn_link_flow(self._impl, n)
def recv(self, limit):
- n, bytes = pn_link_recv(self._impl, limit)
+ n, binary = pn_link_recv(self._impl, limit)
if n == PN_EOS:
return None
else:
self._check(n)
- return bytes
+ return binary
def drain(self, n):
pn_link_drain(self._impl, n)
@@ -3232,9 +3250,9 @@ class Transport(Wrapper):
else:
return self._check(c)
- def push(self, bytes):
- n = self._check(pn_transport_push(self._impl, bytes))
- if n != len(bytes):
+ def push(self, binary):
+ n = self._check(pn_transport_push(self._impl, binary))
+ if n != len(binary):
raise OverflowError("unable to process all bytes")
def close_tail(self):
@@ -3370,7 +3388,6 @@ class SASL(Wrapper):
def done(self, outcome):
pn_sasl_done(self._sasl, outcome)
-
class SSLException(TransportException):
pass
@@ -3853,7 +3870,7 @@ class Url(object):
If specified, replaces corresponding part in url string.
"""
if url:
- self._url = pn_url_parse(str(url))
+ self._url = pn_url_parse(unicode2utf8(str(url)))
if not self._url: raise ValueError("Invalid URL '%s'" % url)
else:
self._url = pn_url()
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/99299d3b/proton-c/bindings/python/proton/reactor.py
----------------------------------------------------------------------
diff --git a/proton-c/bindings/python/proton/reactor.py b/proton-c/bindings/python/proton/reactor.py
index a9bd3cc..dd32648 100644
--- a/proton-c/bindings/python/proton/reactor.py
+++ b/proton-c/bindings/python/proton/reactor.py
@@ -482,9 +482,9 @@ class Connector(Handler):
self.ssl_domain = None
def _connect(self, connection):
- url = next(self.address)
+ url = self.address.next()
# IoHandler uses the hostname to determine where to try to connect to
- connection.hostname = "%s:%i" % (url.host, url.port)
+ connection.hostname = "%s:%s" % (url.host, url.port)
logging.info("connecting to %s..." % connection.hostname)
transport = Transport()
@@ -517,7 +517,7 @@ class Connector(Handler):
if self.connection and self.connection.state & Endpoint.LOCAL_ACTIVE:
if self.reconnect:
event.transport.unbind()
- delay = next(self.reconnect)
+ delay = self.reconnect.next()
if delay == 0:
logging.info("Disconnected, reconnecting...")
self._connect(self.connection)
@@ -667,7 +667,7 @@ class Container(Reactor):
Various LinkOptions can be specified to further control the
attachment.
"""
- if isinstance(context, basestring):
+ if isinstance(context, six.string_types):
context = Url(context)
if isinstance(context, Url) and not target:
target = context.path
@@ -708,7 +708,7 @@ class Container(Reactor):
Various LinkOptions can be specified to further control the
attachment.
"""
- if isinstance(context, basestring):
+ if isinstance(context, six.string_types):
context = Url(context)
if isinstance(context, Url) and not source:
source = context.path
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/99299d3b/proton-c/bindings/python/proton/utils.py
----------------------------------------------------------------------
diff --git a/proton-c/bindings/python/proton/utils.py b/proton-c/bindings/python/proton/utils.py
index 0d7f39e..7b8ec13 100644
--- a/proton-c/bindings/python/proton/utils.py
+++ b/proton-c/bindings/python/proton/utils.py
@@ -17,6 +17,7 @@
# under the License.
#
import collections, socket, time, threading
+import six
from six.moves import queue as Queue
from proton import ConnectionException, Delivery, Endpoint, Handler, LinkException, Message
@@ -24,11 +25,6 @@ from proton import ProtonException, Timeout, Url
from proton.reactor import Container
from proton.handlers import MessagingHandler, IncomingMessageHandler
-def utf8(s):
- if isinstance(s, unicode):
- return s.encode('utf8')
- else:
- return s
class BlockingLink(object):
def __init__(self, connection, link):
@@ -196,13 +192,13 @@ class BlockingConnection(Handler):
self.container = container or Container()
self.container.timeout = self.timeout
self.container.start()
- self.url = Url(utf8(url)).defaults()
+ self.url = Url(url).defaults()
self.conn = self.container.connect(url=self.url, handler=self, ssl_domain=ssl_domain, reconnect=False)
self.wait(lambda: not (self.conn.state & Endpoint.REMOTE_UNINIT),
msg="Opening connection")
def create_sender(self, address, handler=None, name=None, options=None):
- return BlockingSender(self, self.container.create_sender(self.conn, utf8(address), name=utf8(name), handler=handler, options=options))
+ return BlockingSender(self, self.container.create_sender(self.conn, address, name=name, handler=handler, options=options))
def create_receiver(self, address, credit=None, dynamic=False, handler=None, name=None, options=None):
prefetch = credit
@@ -213,7 +209,7 @@ class BlockingConnection(Handler):
else:
fetcher = Fetcher(self, credit)
return BlockingReceiver(
- self, self.container.create_receiver(self.conn, utf8(address), name=utf8(name), dynamic=dynamic, handler=handler or fetcher, options=options), fetcher, credit=prefetch)
+ self, self.container.create_receiver(self.conn, address, name=name, dynamic=dynamic, handler=handler or fetcher, options=options), fetcher, credit=prefetch)
def close(self):
self.conn.close()
@@ -314,7 +310,7 @@ class SyncRequestResponse(IncomingMessageHandler):
if not self.address and not request.address:
raise ValueError("Request message has no address: %s" % request)
request.reply_to = self.reply_to
- request.correlation_id = correlation_id = next(self.correlation_id)
+ request.correlation_id = correlation_id = self.correlation_id.next()
self.sender.send(request)
def wakeup():
return self.response and (self.response.correlation_id == correlation_id)
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/99299d3b/proton-c/bindings/python/proton/wrapper.py
----------------------------------------------------------------------
diff --git a/proton-c/bindings/python/proton/wrapper.py b/proton-c/bindings/python/proton/wrapper.py
index 2911d3a..d3923cf 100644
--- a/proton-c/bindings/python/proton/wrapper.py
+++ b/proton-c/bindings/python/proton/wrapper.py
@@ -81,11 +81,15 @@ class Wrapper(object):
def __hash__(self):
return hash(addressof(self._impl))
- def __cmp__(self, other):
+ def __eq__(self, other):
if isinstance(other, Wrapper):
- return cmp(addressof(self._impl), addressof(other._impl))
- else:
- return -1
+ return addressof(self._impl) == addressof(other._impl)
+ return False
+
+ def __ne__(self, other):
+ if isinstance(other, Wrapper):
+ return addressof(self._impl) != addressof(other._impl)
+ return True
def __del__(self):
pn_decref(self._impl)
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/99299d3b/proton-j/src/main/resources/cmessage.py
----------------------------------------------------------------------
diff --git a/proton-j/src/main/resources/cmessage.py b/proton-j/src/main/resources/cmessage.py
index 6035d54..a338da2 100644
--- a/proton-j/src/main/resources/cmessage.py
+++ b/proton-j/src/main/resources/cmessage.py
@@ -215,7 +215,7 @@ def pn_message_properties(msg):
def pn_message_body(msg):
return msg.body
-def pn_message_decode(msg, data, n):
+def pn_message_decode(msg, data):
n = msg.impl.decode(array(data, 'b'), 0, len(data))
msg.post_decode()
return n
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/99299d3b/tests/python/proton-test
----------------------------------------------------------------------
diff --git a/tests/python/proton-test b/tests/python/proton-test
index 66113dc..5073ab4 100755
--- a/tests/python/proton-test
+++ b/tests/python/proton-test
@@ -20,6 +20,7 @@
# TODO: summarize, test harness preconditions (e.g. broker is alive)
+import six
import logging, optparse, os, struct, sys, time, traceback, types, cgi
from fnmatch import fnmatchcase as match
from getopt import GetoptError
@@ -32,7 +33,7 @@ levels = {
"ERROR": ERROR
}
-sorted_levels = [(v, k) for k, v in levels.items()]
+sorted_levels = [(v, k) for k, v in list(levels.items())]
sorted_levels.sort()
sorted_levels = [v for k, v in sorted_levels]
@@ -446,9 +447,9 @@ def run_test(name, test, config):
if interceptor.last != "\n":
sys.stdout.write("\n")
sys.stdout.write(output)
- print " %s" % colorize_word(runner.status())
+ print(" %s" % colorize_word(runner.status()))
if runner.failed() or runner.skipped():
- print runner.get_formatted_exception_trace()
+ print(runner.get_formatted_exception_trace())
root.setLevel(level)
filter.patterns = patterns
return TestResult(end - start,
@@ -554,7 +555,7 @@ class FunctionScanner(PatternMatcher):
class ClassScanner(PatternMatcher):
def inspect(self, obj):
- return type(obj) in (types.ClassType, types.TypeType) and self.matches(obj.__name__)
+ return type(obj) in six.class_types and self.matches(obj.__name__)
def descend(self, cls):
# the None is required for older versions of python
@@ -565,8 +566,7 @@ class ClassScanner(PatternMatcher):
names.sort()
for name in names:
obj = getattr(cls, name)
- t = type(obj)
- if t == types.MethodType and name.startswith("test"):
+ if six.callable(obj) and name.startswith("test"):
yield MethodTest(cls, name)
class ModuleScanner:
@@ -633,7 +633,7 @@ def runthrough():
start = time.time()
for t in filtered:
if list_only:
- print t.name()
+ print(t.name())
else:
st = t.run()
if xmlr:
@@ -667,22 +667,22 @@ def runthrough():
skip = "skip"
else:
skip = "pass"
- print colorize("Totals:", 1),
+ six.print_(colorize("Totals:", 1), end=' ')
totals = [colorize_word("total", "%s tests" % total),
colorize_word(_pass, "%s passed" % passed),
colorize_word(skip, "%s skipped" % skipped),
colorize_word(ign, "%s ignored" % len(ignored)),
colorize_word(outcome, "%s failed" % failed)]
- print ", ".join(totals),
+ six.print_(", ".join(totals), end=' ')
if opts.hoe and failed > 0:
- print " -- (halted after %s)" % run
+ print(" -- (halted after %s)" % run)
else:
- print
+ print()
if opts.time and run > 0:
- print colorize("Timing:", 1),
+ six.print_(colorize("Timing:", 1), end=' ')
timing = [colorize_word("elapsed", "%.2fs elapsed" % (end - start)),
colorize_word("average", "%.2fs average" % ((end - start)/run))]
- print ", ".join(timing)
+ print(", ".join(timing))
if xmlr:
xmlr.end()
@@ -697,7 +697,7 @@ while limit == 0 or count < limit:
if runthrough():
failures = True
if count > 1:
- print " -- (failures after %s runthroughs)" % count
+ print(" -- (failures after %s runthroughs)" % count)
else:
continue
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/99299d3b/tests/python/proton_tests/codec.py
----------------------------------------------------------------------
diff --git a/tests/python/proton_tests/codec.py b/tests/python/proton_tests/codec.py
index e8893cf..e340732 100644
--- a/tests/python/proton_tests/codec.py
+++ b/tests/python/proton_tests/codec.py
@@ -18,13 +18,13 @@
#
import os, sys
+import six
from . import common
from proton import *
try:
from uuid import uuid4
except ImportError:
from proton import uuid4
-
class Test(common.Test):
@@ -37,58 +37,58 @@ class Test(common.Test):
class DataTest(Test):
def testTopLevelNext(self):
- assert next(self.data) is None
+ assert self.data.next() is None
self.data.put_null()
self.data.put_bool(False)
self.data.put_int(0)
- assert next(self.data) is None
+ assert self.data.next() is None
self.data.rewind()
- assert next(self.data) == Data.NULL
- assert next(self.data) == Data.BOOL
- assert next(self.data) == Data.INT
- assert next(self.data) is None
+ assert self.data.next() == Data.NULL
+ assert self.data.next() == Data.BOOL
+ assert self.data.next() == Data.INT
+ assert self.data.next() is None
def testNestedNext(self):
- assert next(self.data) is None
+ assert self.data.next() is None
self.data.put_null()
- assert next(self.data) is None
+ assert self.data.next() is None
self.data.put_list()
- assert next(self.data) is None
+ assert self.data.next() is None
self.data.put_bool(False)
- assert next(self.data) is None
+ assert self.data.next() is None
self.data.rewind()
- assert next(self.data) is Data.NULL
- assert next(self.data) is Data.LIST
+ assert self.data.next() is Data.NULL
+ assert self.data.next() is Data.LIST
self.data.enter()
- assert next(self.data) is None
+ assert self.data.next() is None
self.data.put_ubyte(0)
- assert next(self.data) is None
+ assert self.data.next() is None
self.data.put_uint(0)
- assert next(self.data) is None
+ assert self.data.next() is None
self.data.put_int(0)
- assert next(self.data) is None
+ assert self.data.next() is None
self.data.exit()
- assert next(self.data) is Data.BOOL
- assert next(self.data) is None
+ assert self.data.next() is Data.BOOL
+ assert self.data.next() is None
self.data.rewind()
- assert next(self.data) is Data.NULL
- assert next(self.data) is Data.LIST
+ assert self.data.next() is Data.NULL
+ assert self.data.next() is Data.LIST
assert self.data.enter()
- assert next(self.data) is Data.UBYTE
- assert next(self.data) is Data.UINT
- assert next(self.data) is Data.INT
- assert next(self.data) is None
+ assert self.data.next() is Data.UBYTE
+ assert self.data.next() is Data.UINT
+ assert self.data.next() is Data.INT
+ assert self.data.next() is None
assert self.data.exit()
- assert next(self.data) is Data.BOOL
- assert next(self.data) is None
+ assert self.data.next() is Data.BOOL
+ assert self.data.next() is None
def testEnterExit(self):
- assert next(self.data) is None
+ assert self.data.next() is None
assert not self.data.enter()
self.data.put_list()
assert self.data.enter()
- assert next(self.data) is None
+ assert self.data.next() is None
self.data.put_list()
assert self.data.enter()
self.data.put_list()
@@ -101,19 +101,19 @@ class DataTest(Test):
assert self.data.get_list() == 1
assert not self.data.exit()
assert self.data.get_list() == 1
- assert next(self.data) is None
+ assert self.data.next() is None
self.data.rewind()
- assert next(self.data) is Data.LIST
+ assert self.data.next() is Data.LIST
assert self.data.get_list() == 1
assert self.data.enter()
- assert next(self.data) is Data.LIST
+ assert self.data.next() is Data.LIST
assert self.data.get_list() == 1
assert self.data.enter()
- assert next(self.data) is Data.LIST
+ assert self.data.next() is Data.LIST
assert self.data.get_list() == 0
assert self.data.enter()
- assert next(self.data) is None
+ assert self.data.next() is None
assert self.data.exit()
assert self.data.get_list() == 0
assert self.data.exit()
@@ -129,7 +129,7 @@ class DataTest(Test):
putter(v)
except Exception:
etype, value, trace = sys.exc_info()
- raise etype, "%s(%r): %s" % (putter.__name__, v, value), trace
+ six.reraise(etype, etype("%s(%r): %s" % (putter.__name__, v, value)), trace)
return putter
# (bits, signed) for each integer type
@@ -148,12 +148,12 @@ class DataTest(Test):
values = [0, 1, 2, 5, 42]
if signed:
min, max = -2**(bits-1), 2**(bits-1)-1
- values.append(max / 2)
+ values.append(max // 2)
values += [-i for i in values if i]
values += [min, max]
else:
max = 2**(bits) - 1
- values += [max / 2, max]
+ values += [max // 2, max]
return sorted(values)
def _testArray(self, dtype, descriptor, atype, *values):
@@ -169,7 +169,7 @@ class DataTest(Test):
self.put(putter, v)
self.data.exit()
self.data.rewind()
- assert next(self.data) == Data.ARRAY
+ assert self.data.next() == Data.ARRAY
count, described, type = self.data.get_array()
assert count == len(values), count
if dtype is None:
@@ -179,17 +179,17 @@ class DataTest(Test):
assert type == aTYPE, type
assert self.data.enter()
if described:
- assert next(self.data) == dTYPE
+ assert self.data.next() == dTYPE
getter = getattr(self.data, "get_%s" % dtype)
gotten = getter()
assert gotten == descriptor, gotten
if values:
getter = getattr(self.data, "get_%s" % atype)
for v in values:
- assert next(self.data) == aTYPE
+ assert self.data.next() == aTYPE
gotten = getter()
assert gotten == v, gotten
- assert next(self.data) is None
+ assert self.data.next() is None
assert self.data.exit()
def testStringArray(self):
@@ -231,7 +231,7 @@ class DataTest(Test):
self.data.rewind()
for v in values:
- vtype = next(self.data)
+ vtype = self.data.next()
assert vtype == ntype, vtype
gotten = getter()
assert eq(gotten, v), (gotten, v)
@@ -246,7 +246,7 @@ class DataTest(Test):
cgetter = getattr(copy, "get_%s" % dtype)
for v in values:
- vtype = next(copy)
+ vtype = copy.next()
assert vtype == ntype, vtype
gotten = cgetter()
assert eq(gotten, v), (gotten, v)
@@ -275,7 +275,8 @@ class DataTest(Test):
self._test("double", 0, 1, 2, 3, 0.1, 0.2, 0.3, -1, -2, -3, -0.1, -0.2, -0.3)
def testBinary(self):
- self._test("binary", "this", "is", "a", "test", "of" "b\x00inary")
+ self._test("binary", six.b("this"), six.b("is"), six.b("a"), six.b("test"),
+ six.b("of" "b\x00inary"))
def testSymbol(self):
self._test("symbol", "this is a symbol test", "bleh", "blah")
@@ -284,7 +285,7 @@ class DataTest(Test):
self._test("timestamp", 0, 12345, 1000000)
def testChar(self):
- self._test("char", 'a', 'b', 'c', u'\u1234')
+ self._test("char", 'a', 'b', 'c', six.u('\u1234'))
def testUUID(self):
self._test("uuid", uuid4(), uuid4(), uuid4())
@@ -296,7 +297,7 @@ class DataTest(Test):
self._test("decimal64", 0, 1, 2, 3, 4, 2**60)
def testDecimal128(self):
- self._test("decimal128", "fdsaasdf;lkjjkl;", "x"*16 )
+ self._test("decimal128", six.b("fdsaasdf;lkjjkl;"), six.b("x"*16))
def testCopy(self):
self.data.put_described()
@@ -337,33 +338,33 @@ class DataTest(Test):
obj = {symbol("key"): timestamp(1234),
ulong(123): "blah",
char("c"): "bleh",
- u"desc": Described(symbol("url"), u"http://example.org"),
- u"array": Array(UNDESCRIBED, Data.INT, 1, 2, 3),
- u"list": [1, 2, 3, None, 4],
- u"boolean": True}
+ six.u("desc"): Described(symbol("url"), six.u("http://example.org")),
+ six.u("array"): Array(UNDESCRIBED, Data.INT, 1, 2, 3),
+ six.u("list"): [1, 2, 3, None, 4],
+ six.u("boolean"): True}
self.data.put_object(obj)
enc = self.data.encode()
data = Data()
data.decode(enc)
data.rewind()
- assert next(data)
+ assert data.next()
copy = data.get_object()
assert copy == obj, (copy, obj)
def testLookup(self):
- obj = {symbol("key"): u"value",
+ obj = {symbol("key"): six.u("value"),
symbol("pi"): 3.14159,
symbol("list"): [1, 2, 3, 4]}
self.data.put_object(obj)
self.data.rewind()
- next(self.data)
+ self.data.next()
self.data.enter()
self.data.narrow()
assert self.data.lookup("pi")
assert self.data.get_object() == 3.14159
self.data.rewind()
assert self.data.lookup("key")
- assert self.data.get_object() == u"value"
+ assert self.data.get_object() == six.u("value")
self.data.rewind()
assert self.data.lookup("list")
assert self.data.get_object() == [1, 2, 3, 4]
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/99299d3b/tests/python/proton_tests/common.py
----------------------------------------------------------------------
diff --git a/tests/python/proton_tests/common.py b/tests/python/proton_tests/common.py
index 585ea02..be9c75a 100644
--- a/tests/python/proton_tests/common.py
+++ b/tests/python/proton_tests/common.py
@@ -88,9 +88,9 @@ def pump_uni(src, dst, buffer_size=1024):
elif p == 0 or c == 0:
return False
else:
- bytes = src.peek(min(c, buffer_size))
- dst.push(bytes)
- src.pop(len(bytes))
+ binary = src.peek(min(c, buffer_size))
+ dst.push(binary)
+ src.pop(len(binary))
return True
@@ -244,7 +244,8 @@ class MessengerApp(object):
del cmd[0:1]
cmd.insert(0, foundfile)
cmd.insert(0, sys.executable)
- self._process = Popen(cmd, stdout=PIPE, stderr=STDOUT, bufsize=4096)
+ self._process = Popen(cmd, stdout=PIPE, stderr=STDOUT,
+ bufsize=4096, universal_newlines=True)
except OSError:
e = sys.exc_info()[1]
print("ERROR: '%s'" % e)
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/99299d3b/tests/python/proton_tests/engine.py
----------------------------------------------------------------------
diff --git a/tests/python/proton_tests/engine.py b/tests/python/proton_tests/engine.py
index 7835792..4670562 100644
--- a/tests/python/proton_tests/engine.py
+++ b/tests/python/proton_tests/engine.py
@@ -21,6 +21,7 @@ from __future__ import absolute_import
import os, gc
from . import common
from time import time, sleep
+import six
from proton import *
from .common import pump
from proton.reactor import Reactor
@@ -36,6 +37,19 @@ if not hasattr(gc, "garbage"):
# + resuming
# - locally and remotely created deliveries with the same tag
+# Jython 2.5 needs this:
+try:
+ bytes()
+except:
+ bytes = str
+
+# and this...
+try:
+ bytearray()
+except:
+ def bytearray(x):
+ return six.b('\x00') * x
+
OUTPUT_SIZE = 10*1024
class Test(common.Test):
@@ -725,7 +739,7 @@ class TransferTest(Test):
assert tag == "tag", tag
assert d.writable
- n = self.snd.send("this is a test")
+ n = self.snd.send(six.b("this is a test"))
assert self.snd.advance()
assert self.c1.work_head is None
@@ -738,7 +752,7 @@ class TransferTest(Test):
def test_multiframe(self):
self.rcv.flow(1)
self.snd.delivery("tag")
- msg = "this is a test"
+ msg = six.b("this is a test")
n = self.snd.send(msg)
assert n == len(msg)
@@ -749,24 +763,24 @@ class TransferTest(Test):
assert d.tag == "tag", repr(d.tag)
assert d.readable
- bytes = self.rcv.recv(1024)
- assert bytes == msg, (bytes, msg)
+ binary = self.rcv.recv(1024)
+ assert binary == msg, (binary, msg)
- bytes = self.rcv.recv(1024)
- assert bytes == ""
+ binary = self.rcv.recv(1024)
+ assert binary == six.b("")
- msg = "this is more"
+ msg = six.b("this is more")
n = self.snd.send(msg)
assert n == len(msg)
assert self.snd.advance()
self.pump()
- bytes = self.rcv.recv(1024)
- assert bytes == msg, (bytes, msg)
+ binary = self.rcv.recv(1024)
+ assert binary == msg, (binary, msg)
- bytes = self.rcv.recv(1024)
- assert bytes is None
+ binary = self.rcv.recv(1024)
+ assert binary is None
def test_disposition(self):
self.rcv.flow(1)
@@ -774,7 +788,7 @@ class TransferTest(Test):
self.pump()
sd = self.snd.delivery("tag")
- msg = "this is a test"
+ msg = six.b("this is a test")
n = self.snd.send(msg)
assert n == len(msg)
assert self.snd.advance()
@@ -809,7 +823,7 @@ class TransferTest(Test):
#fill up delivery buffer on sender
for m in range(1024):
sd = self.snd.delivery("tag%s" % m)
- msg = "message %s" % m
+ msg = ("message %s" % m).encode('ascii')
n = self.snd.send(msg)
assert n == len(msg)
assert self.snd.advance()
@@ -822,7 +836,7 @@ class TransferTest(Test):
assert rd is not None, m
assert rd.tag == ("tag%s" % m), (rd.tag, m)
msg = self.rcv.recv(1024)
- assert msg == ("message %s" % m), (msg, m)
+ assert msg == ("message %s" % m).encode('ascii'), (msg, m)
rd.update(Delivery.ACCEPTED)
rd.settle()
@@ -831,7 +845,7 @@ class TransferTest(Test):
#add some new deliveries
for m in range(1024, 1450):
sd = self.snd.delivery("tag%s" % m)
- msg = "message %s" % m
+ msg = ("message %s" % m).encode('ascii')
n = self.snd.send(msg)
assert n == len(msg)
assert self.snd.advance()
@@ -848,7 +862,7 @@ class TransferTest(Test):
#submit some more deliveries
for m in range(1450, 1500):
sd = self.snd.delivery("tag%s" % m)
- msg = "message %s" % m
+ msg = ("message %s" % m).encode('ascii')
n = self.snd.send(msg)
assert n == len(msg)
assert self.snd.advance()
@@ -863,7 +877,7 @@ class TransferTest(Test):
assert rd is not None, m
assert rd.tag == ("tag%s" % m), (rd.tag, m)
msg = self.rcv.recv(1024)
- assert msg == ("message %s" % m), (msg, m)
+ assert msg == ("message %s" % m).encode('ascii'), (msg, m)
rd.update(Delivery.ACCEPTED)
rd.settle()
@@ -873,7 +887,7 @@ class TransferTest(Test):
for x in range(10):
self.snd.delivery("tag%d" % x)
- msg = "this is a test"
+ msg = six.b("this is a test")
n = self.snd.send(msg)
assert n == len(msg)
assert self.snd.advance()
@@ -915,7 +929,7 @@ class MaxFrameTransferTest(Test):
parts = []
for i in range(size):
parts.append(str(i))
- return "/".join(parts)[:size]
+ return "/".join(parts)[:size].encode("utf-8")
def testMinFrame(self):
"""
@@ -940,11 +954,11 @@ class MaxFrameTransferTest(Test):
self.pump()
- bytes = self.rcv.recv(513)
- assert bytes == msg
+ binary = self.rcv.recv(513)
+ assert binary == msg
- bytes = self.rcv.recv(1024)
- assert bytes == None
+ binary = self.rcv.recv(1024)
+ assert binary == None
def testOddFrame(self):
"""
@@ -962,18 +976,18 @@ class MaxFrameTransferTest(Test):
self.rcv.flow(2)
self.snd.delivery("tag")
- msg = "X" * 1699
+ msg = ("X" * 1699).encode('utf-8')
n = self.snd.send(msg)
assert n == len(msg)
assert self.snd.advance()
self.pump()
- bytes = self.rcv.recv(1699)
- assert bytes == msg
+ binary = self.rcv.recv(1699)
+ assert binary == msg
- bytes = self.rcv.recv(1024)
- assert bytes == None
+ binary = self.rcv.recv(1024)
+ assert binary == None
self.rcv.advance()
@@ -985,13 +999,13 @@ class MaxFrameTransferTest(Test):
self.pump()
- bytes = self.rcv.recv(1426)
- assert bytes == msg
+ binary = self.rcv.recv(1426)
+ assert binary == msg
self.pump()
- bytes = self.rcv.recv(1024)
- assert bytes == None
+ binary = self.rcv.recv(1024)
+ assert binary == None
def testBigMessage(self):
"""
@@ -1013,11 +1027,11 @@ class MaxFrameTransferTest(Test):
self.pump()
- bytes = self.rcv.recv(1024*256)
- assert bytes == msg
+ binary = self.rcv.recv(1024*256)
+ assert binary == msg
- bytes = self.rcv.recv(1024)
- assert bytes == None
+ binary = self.rcv.recv(1024)
+ assert binary == None
class IdleTimeoutTest(Test):
@@ -1389,7 +1403,7 @@ class CreditTest(Test):
sd = self.snd.delivery("tagA")
assert sd
- n = self.snd.send("A")
+ n = self.snd.send(six.b("A"))
assert n == 1
self.pump()
self.snd.advance()
@@ -1405,8 +1419,8 @@ class CreditTest(Test):
assert self.snd.credit == 9, self.snd.credit
assert self.rcv.credit == 10, self.rcv.credit
- bytes = self.rcv.recv(10)
- assert bytes == "A", bytes
+ data = self.rcv.recv(10)
+ assert data == six.b("A"), data
self.rcv.advance()
self.pump()
assert self.snd.credit == 9, self.snd.credit
@@ -1427,7 +1441,7 @@ class CreditTest(Test):
sd = self.snd.delivery("tagB")
assert sd
- n = self.snd.send("B")
+ n = self.snd.send(six.b("B"))
assert n == 1
self.snd.advance()
self.pump()
@@ -1441,7 +1455,7 @@ class CreditTest(Test):
sd = self.snd.delivery("tagC")
assert sd
- n = self.snd.send("C")
+ n = self.snd.send(six.b("C"))
assert n == 1
self.snd.advance()
self.pump()
@@ -1455,11 +1469,11 @@ class CreditTest(Test):
assert self.snd.credit == 0, self.snd.credit
assert self.rcv.credit == 2, self.rcv.credit
- bytes = self.rcv.recv(10)
- assert bytes == "B", bytes
+ data = self.rcv.recv(10)
+ assert data == six.b("B"), data
self.rcv.advance()
- bytes = self.rcv.recv(10)
- assert bytes == "C", bytes
+ data = self.rcv.recv(10)
+ assert data == six.b("C"), data
self.rcv.advance()
self.pump()
assert self.snd.credit == 0, self.snd.credit
@@ -1512,10 +1526,10 @@ class CreditTest(Test):
for i in range(10):
tag = "test %d" % i
self.snd.delivery( tag )
- self.snd.send( tag )
+ self.snd.send( tag.encode("ascii") )
assert self.snd.advance()
self.snd2.delivery( tag )
- self.snd2.send( tag )
+ self.snd2.send( tag.encode("ascii") )
assert self.snd2.advance()
self.pump()
@@ -1554,11 +1568,12 @@ class SessionCreditTest(Test):
assert snd.queued == 0, snd.queued
assert rcv.queued == 0, rcv.queued
+ data = bytes(bytearray(size))
idx = 0
while snd.credit:
d = snd.delivery("tag%s" % idx)
assert d
- n = snd.send(chr(ord("a") + idx)*size)
+ n = snd.send(data)
assert n == size, (n, size)
assert snd.advance()
self.pump()
@@ -1632,7 +1647,7 @@ class SessionCreditTest(Test):
idx = 0
while snd.credit:
d = snd.delivery("tag%s" % idx)
- snd.send("x"*1024)
+ snd.send(("x"*1024).encode('ascii'))
assert d
assert snd.advance()
self.pump()
@@ -1735,7 +1750,7 @@ class SettlementTest(Test):
for i in range(count):
sd = self.snd.delivery("tag%s" % i)
assert sd
- n = self.snd.send("x"*size)
+ n = self.snd.send(("x"*size).encode('ascii'))
assert n == size, n
assert self.snd.advance()
self.pump()
@@ -1793,7 +1808,7 @@ class PipelineTest(Test):
for i in range(10):
d = snd.delivery("delivery-%s" % i)
- snd.send("delivery-%s" % i)
+ snd.send(six.b("delivery-%s" % i))
d.settle()
snd.close()
@@ -2225,7 +2240,7 @@ class EventTest(CollectorTest):
self.expect(Event.CONNECTION_INIT, Event.SESSION_INIT,
Event.LINK_INIT, Event.LINK_LOCAL_OPEN, Event.TRANSPORT)
snd.delivery("delivery")
- snd.send("Hello World!")
+ snd.send(six.b("Hello World!"))
snd.advance()
self.pump()
self.expect()
@@ -2241,7 +2256,7 @@ class EventTest(CollectorTest):
snd, rcv = self.testFlowEvents()
snd.open()
dlv = snd.delivery("delivery")
- snd.send("Hello World!")
+ snd.send(six.b("Hello World!"))
assert snd.advance()
self.expect(Event.LINK_LOCAL_OPEN, Event.TRANSPORT)
self.pump()
@@ -2252,7 +2267,7 @@ class EventTest(CollectorTest):
rdlv.update(Delivery.ACCEPTED)
self.pump()
event = self.expect(Event.DELIVERY)
- assert event.context == dlv
+ assert event.context == dlv, (dlv, event.context)
def testConnectionBOUND_UNBOUND(self):
c = Connection()
@@ -2272,7 +2287,7 @@ class EventTest(CollectorTest):
t.bind(c)
self.expect(Event.CONNECTION_BOUND)
assert t.condition is None
- t.push("asdf")
+ t.push(six.b("asdf"))
self.expect(Event.TRANSPORT_ERROR, Event.TRANSPORT_TAIL_CLOSED)
assert t.condition is not None
assert t.condition.name == "amqp:connection:framing-error"
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/99299d3b/tests/python/proton_tests/interop.py
----------------------------------------------------------------------
diff --git a/tests/python/proton_tests/interop.py b/tests/python/proton_tests/interop.py
index 1ef92dd..5cbab99 100644
--- a/tests/python/proton_tests/interop.py
+++ b/tests/python/proton_tests/interop.py
@@ -19,6 +19,7 @@
from proton import *
import os
+import six
from . import common
@@ -71,7 +72,7 @@ class InteropTest(common.Test):
self.decode_data(body)
def assert_next(self, type, value):
- next_type = next(self.data)
+ next_type = self.data.next()
assert next_type == type, "Type mismatch: %s != %s"%(
Data.type_names[next_type], Data.type_names[type])
next_value = self.data.get_object()
@@ -80,7 +81,7 @@ class InteropTest(common.Test):
def test_message(self):
self.decode_message_file("message")
self.assert_next(Data.STRING, "hello")
- assert next(self.data) is None
+ assert self.data.next() is None
def test_primitives(self):
self.decode_data_file("primitives")
@@ -95,30 +96,30 @@ class InteropTest(common.Test):
self.assert_next(Data.LONG, -12345)
self.assert_next(Data.FLOAT, 0.125)
self.assert_next(Data.DOUBLE, 0.125)
- assert next(self.data) is None
+ assert self.data.next() is None
def test_strings(self):
self.decode_data_file("strings")
- self.assert_next(Data.BINARY, "abc\0defg")
+ self.assert_next(Data.BINARY, six.b("abc\0defg"))
self.assert_next(Data.STRING, "abcdefg")
self.assert_next(Data.SYMBOL, "abcdefg")
- self.assert_next(Data.BINARY, "")
+ self.assert_next(Data.BINARY, six.b(""))
self.assert_next(Data.STRING, "")
self.assert_next(Data.SYMBOL, "")
- assert next(self.data) is None
+ assert self.data.next() is None
def test_described(self):
self.decode_data_file("described")
self.assert_next(Data.DESCRIBED, Described("foo-descriptor", "foo-value"))
self.data.exit()
- assert next(self.data) == Data.DESCRIBED
+ assert self.data.next() == Data.DESCRIBED
self.data.enter()
self.assert_next(Data.INT, 12)
self.assert_next(Data.INT, 13)
self.data.exit()
- assert next(self.data) is None
+ assert self.data.next() is None
def test_described_array(self):
self.decode_data_file("described_array")
@@ -129,17 +130,17 @@ class InteropTest(common.Test):
self.assert_next(Data.ARRAY, Array(UNDESCRIBED, Data.INT, *range(0,100)))
self.assert_next(Data.ARRAY, Array(UNDESCRIBED, Data.STRING, *["a", "b", "c"]))
self.assert_next(Data.ARRAY, Array(UNDESCRIBED, Data.INT))
- assert next(self.data) is None
+ assert self.data.next() is None
def test_lists(self):
self.decode_data_file("lists")
self.assert_next(Data.LIST, [32, "foo", True])
self.assert_next(Data.LIST, [])
- assert next(self.data) is None
+ assert self.data.next() is None
def test_maps(self):
self.decode_data_file("maps")
self.assert_next(Data.MAP, {"one":1, "two":2, "three":3 })
self.assert_next(Data.MAP, {1:"one", 2:"two", 3:"three"})
self.assert_next(Data.MAP, {})
- assert next(self.data) is None
+ assert self.data.next() is None
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/99299d3b/tests/python/proton_tests/message.py
----------------------------------------------------------------------
diff --git a/tests/python/proton_tests/message.py b/tests/python/proton_tests/message.py
index 3366366..10d2326 100644
--- a/tests/python/proton_tests/message.py
+++ b/tests/python/proton_tests/message.py
@@ -18,6 +18,7 @@
#
import os
+import six
from . import common
from proton import *
try:
@@ -38,7 +39,7 @@ class AccessorsTest(Test):
def _test(self, name, default, values):
d = getattr(self.msg, name)
- assert d == default, d
+ assert d == default, (d, default)
for v in values:
setattr(self.msg, name, v)
gotten = getattr(self.msg, name)
@@ -72,7 +73,8 @@ class AccessorsTest(Test):
self._test("delivery_count", 0, range(0, 1024))
def testUserId(self):
- self._test("user_id", "", ("asdf", "fdsa", "asd\x00fdsa", ""))
+ self._test("user_id", six.b(""), (six.b("asdf"), six.b("fdsa"),
+ six.b("asd\x00fdsa"), six.b("")))
def testAddress(self):
self._test_str("address")
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/99299d3b/tests/python/proton_tests/messenger.py
----------------------------------------------------------------------
diff --git a/tests/python/proton_tests/messenger.py b/tests/python/proton_tests/messenger.py
index 03a1b6b..30d0ec5 100644
--- a/tests/python/proton_tests/messenger.py
+++ b/tests/python/proton_tests/messenger.py
@@ -19,6 +19,7 @@ from __future__ import absolute_import
#
import os, sys, traceback
+from six.moves import range as xrange
from . import common
from proton import *
from threading import Thread, Event
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/99299d3b/tests/python/proton_tests/sasl.py
----------------------------------------------------------------------
diff --git a/tests/python/proton_tests/sasl.py b/tests/python/proton_tests/sasl.py
index 4d569bc..2734364 100644
--- a/tests/python/proton_tests/sasl.py
+++ b/tests/python/proton_tests/sasl.py
@@ -19,6 +19,7 @@ from __future__ import absolute_import
#
import sys, os
+import six
from . import common
from proton import *
from .common import pump, Skipped
@@ -121,7 +122,7 @@ class SaslTest(Test):
c1.open()
# get all t1's output in one buffer then pass it all to t2
- out1_sasl_and_amqp = ""
+ out1_sasl_and_amqp = six.b("")
t1_still_producing = True
while t1_still_producing:
out1 = self.t1.peek(1024)
@@ -171,17 +172,17 @@ class SaslTest(Test):
out = self.t1.peek(1024)
self.t1.pop(len(out))
- self.t1.push("AMQP\x03\x01\x00\x00")
+ self.t1.push(six.b("AMQP\x03\x01\x00\x00"))
out = self.t1.peek(1024)
self.t1.pop(len(out))
- self.t1.push("\x00\x00\x00")
+ self.t1.push(six.b("\x00\x00\x00"))
out = self.t1.peek(1024)
self.t1.pop(len(out))
- self.t1.push("6\x02\x01\x00\x00\x00S@\xc04\x01\xe01\x04\xa3\x05PLAIN\x0aDIGEST-MD5\x09ANONYMOUS\x08CRAM-MD5")
+ self.t1.push(six.b("6\x02\x01\x00\x00\x00S@\xc04\x01\xe01\x04\xa3\x05PLAIN\x0aDIGEST-MD5\x09ANONYMOUS\x08CRAM-MD5"))
out = self.t1.peek(1024)
self.t1.pop(len(out))
- self.t1.push("\x00\x00\x00\x10\x02\x01\x00\x00\x00SD\xc0\x03\x01P\x00")
+ self.t1.push(six.b("\x00\x00\x00\x10\x02\x01\x00\x00\x00SD\xc0\x03\x01P\x00"))
out = self.t1.peek(1024)
self.t1.pop(len(out))
while out:
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/99299d3b/tests/python/proton_tests/transport.py
----------------------------------------------------------------------
diff --git a/tests/python/proton_tests/transport.py b/tests/python/proton_tests/transport.py
index e158a5b..0b22f4e 100644
--- a/tests/python/proton_tests/transport.py
+++ b/tests/python/proton_tests/transport.py
@@ -18,6 +18,7 @@
#
import os
+import six
from . import common
from proton import *
@@ -44,9 +45,9 @@ class TransportTest(Test):
if p < 0:
return
elif p > 0:
- bytes = self.transport.peek(p)
- self.peer.push(bytes)
- self.transport.pop(len(bytes))
+ data = self.transport.peek(p)
+ self.peer.push(data)
+ self.transport.pop(len(data))
else:
assert False
@@ -61,16 +62,16 @@ class TransportTest(Test):
assert self.conn.remote_condition.name == name, self.conn.remote_condition
def testEOS(self):
- self.transport.push("") # should be a noop
+ self.transport.push(six.b("")) # should be a noop
self.transport.close_tail() # should result in framing error
self.assert_error(u'amqp:connection:framing-error')
def testPartial(self):
- self.transport.push("AMQ") # partial header
+ self.transport.push(six.b("AMQ")) # partial header
self.transport.close_tail() # should result in framing error
self.assert_error(u'amqp:connection:framing-error')
- def testGarbage(self, garbage="GARBAGE_"):
+ def testGarbage(self, garbage=six.b("GARBAGE_")):
self.transport.push(garbage)
self.assert_error(u'amqp:connection:framing-error')
assert self.transport.pending() < 0
@@ -78,13 +79,13 @@ class TransportTest(Test):
assert self.transport.pending() < 0
def testSmallGarbage(self):
- self.testGarbage("XXX")
+ self.testGarbage(six.b("XXX"))
def testBigGarbage(self):
- self.testGarbage("GARBAGE_XXX")
+ self.testGarbage(six.b("GARBAGE_XXX"))
def testHeader(self):
- self.transport.push("AMQP\x00\x01\x00\x00")
+ self.transport.push(six.b("AMQP\x00\x01\x00\x00"))
self.transport.close_tail()
self.assert_error(u'amqp:connection:framing-error')
@@ -102,8 +103,8 @@ class TransportTest(Test):
trn = Transport()
trn.bind(conn)
out = trn.peek(1024)
- assert "test-container" in out, repr(out)
- assert "test-hostname" in out, repr(out)
+ assert six.b("test-container") in out, repr(out)
+ assert six.b("test-hostname") in out, repr(out)
self.transport.push(out)
c = Connection()
@@ -160,7 +161,7 @@ class TransportTest(Test):
self.transport.pop(len(dat2) - len(dat1))
dat3 = self.transport.peek(1024)
self.transport.pop(len(dat3))
- assert self.transport.peek(1024) == ""
+ assert self.transport.peek(1024) == six.b("")
self.peer.push(dat1)
self.peer.push(dat2[len(dat1):])
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/99299d3b/tests/python/proton_tests/utils.py
----------------------------------------------------------------------
diff --git a/tests/python/proton_tests/utils.py b/tests/python/proton_tests/utils.py
index 727b586..86eb6f3 100644
--- a/tests/python/proton_tests/utils.py
+++ b/tests/python/proton_tests/utils.py
@@ -18,6 +18,7 @@
#
import os, time
+from six.moves import range as xrange
from threading import Thread, Event
from unittest import TestCase
from proton_tests.common import Test, free_tcp_port
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/99299d3b/tests/tools/apps/python/msgr-recv.py
----------------------------------------------------------------------
diff --git a/tests/tools/apps/python/msgr-recv.py b/tests/tools/apps/python/msgr-recv.py
index 079c871..757b19c 100755
--- a/tests/tools/apps/python/msgr-recv.py
+++ b/tests/tools/apps/python/msgr-recv.py
@@ -23,6 +23,11 @@ import sys, optparse, time
import logging
from proton import *
+# Hi python3!
+try:
+ long()
+except:
+ long = int
usage = """
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/99299d3b/tests/tools/apps/python/msgr-send.py
----------------------------------------------------------------------
diff --git a/tests/tools/apps/python/msgr-send.py b/tests/tools/apps/python/msgr-send.py
index a2f67c5..2e2583f 100755
--- a/tests/tools/apps/python/msgr-send.py
+++ b/tests/tools/apps/python/msgr-send.py
@@ -23,6 +23,11 @@ import sys, optparse, time
import logging
from proton import *
+# Hi python3!
+try:
+ long()
+except:
+ long = int
usage = """
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/99299d3b/tests/tools/soak-check
----------------------------------------------------------------------
diff --git a/tests/tools/soak-check b/tests/tools/soak-check
index 36d7984..bf5b147 100755
--- a/tests/tools/soak-check
+++ b/tests/tools/soak-check
@@ -17,13 +17,14 @@
# specific language governing permissions and limitations
# under the License.
#
+from __future__ import print_function
import sys, optparse
from subprocess import Popen,PIPE
def run_test(cmd):
try:
process = Popen(cmd)
- except OSError, e:
+ except OSError:
assert False, "Unable to execute command '%s', is it in your PATH?" % cmd[0]
return process.wait()
@@ -121,7 +122,7 @@ def main(argv=None):
command.append( "-Dverbose" )
command.append( pattern )
if verbose:
- print "command='%s'" % str(command)
+ print("command='%s'" % str(command))
run_test(command)
return 0
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org
[2/4] qpid-proton git commit: PROTON-490: enable six.py support for
operator method calls
Posted by kg...@apache.org.
PROTON-490: enable six.py support for operator method calls
Project: http://git-wip-us.apache.org/repos/asf/qpid-proton/repo
Commit: http://git-wip-us.apache.org/repos/asf/qpid-proton/commit/93ccc736
Tree: http://git-wip-us.apache.org/repos/asf/qpid-proton/tree/93ccc736
Diff: http://git-wip-us.apache.org/repos/asf/qpid-proton/diff/93ccc736
Branch: refs/heads/kgiusti-python3
Commit: 93ccc7364bfe28d3076a441409be8cbc5c88128b
Parents: adfe2a2
Author: Ken Giusti <kg...@apache.org>
Authored: Wed Apr 22 15:09:45 2015 -0400
Committer: Ken Giusti <kg...@apache.org>
Committed: Wed Apr 22 15:09:45 2015 -0400
----------------------------------------------------------------------
tests/python/six.py | 11 +++++++++++
1 file changed, 11 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/93ccc736/tests/python/six.py
----------------------------------------------------------------------
diff --git a/tests/python/six.py b/tests/python/six.py
index ffa3fe1..4b572bb 100644
--- a/tests/python/six.py
+++ b/tests/python/six.py
@@ -32,6 +32,17 @@ __author__ = "Benjamin Peterson <be...@python.org>"
__version__ = "1.9.0"
+# begin QPID
+# added to support running the unit tests under JYTHON
+if not hasattr(operator, 'methodcaller'):
+ def _methodcaller(cls, name, *args, **kwargs):
+ def caller(obj):
+ return getattr(obj, name)(*args, **kwargs)
+ return caller
+ operator.methodcaller = classmethod(_methodcaller)
+# QPID end
+
+
# Useful for very coarse version differentiation.
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org