PROTON-490: remove dependency on six, provide simple abstractions for language differences
Project: http://git-wip-us.apache.org/repos/asf/qpid-proton/repo Commit: http://git-wip-us.apache.org/repos/asf/qpid-proton/commit/646ee41c Tree: http://git-wip-us.apache.org/repos/asf/qpid-proton/tree/646ee41c Diff: http://git-wip-us.apache.org/repos/asf/qpid-proton/diff/646ee41c Branch: refs/heads/master Commit: 646ee41cbb1071b60394fd85ec44bc515a19605a Parents: d31100a Author: Ken Giusti <[email protected]> Authored: Wed Apr 29 09:44:31 2015 -0400 Committer: Ken Giusti <[email protected]> Committed: Wed Apr 29 09:44:31 2015 -0400 ---------------------------------------------------------------------- proton-c/bindings/python/proton/__init__.py | 26 +- proton-c/bindings/python/proton/_compat.py | 84 +++ proton-c/bindings/python/proton/handlers.py | 1 - proton-c/bindings/python/proton/reactor.py | 16 +- proton-c/bindings/python/proton/utils.py | 2 - proton-c/mllib/__init__.py | 17 +- proton-c/mllib/dom.py | 12 +- proton-c/mllib/transforms.py | 5 +- tests/python/proton-test | 18 +- tests/python/proton_tests/codec.py | 24 +- tests/python/proton_tests/engine.py | 38 +- tests/python/proton_tests/interop.py | 6 +- tests/python/proton_tests/message.py | 6 +- tests/python/proton_tests/messenger.py | 7 +- tests/python/proton_tests/sasl.py | 14 +- tests/python/proton_tests/transport.py | 20 +- tests/python/proton_tests/utils.py | 3 +- tests/python/six.py | 849 ----------------------- 18 files changed, 198 insertions(+), 950 deletions(-) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/646ee41c/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 399aec7..864b25e 100644 --- a/proton-c/bindings/python/proton/__init__.py +++ b/proton-c/bindings/python/proton/__init__.py @@ -33,8 +33,8 @@ from __future__ import absolute_import from cproton import * from .wrapper import Wrapper +from . import _compat -import six import weakref, socket, sys, threading try: @@ -805,7 +805,7 @@ class Message(object): self.annotations = None self.properties = None self.body = body - for k,v in six.iteritems(kwargs): + for k,v in _compat.iteritems(kwargs): getattr(self, k) # Raise exception if it's not a valid attribute. setattr(self, k, v) @@ -950,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 six.integer_types: + if type(value) in _compat.INT_TYPES: value = ulong(value) self._id.rewind() self._id.put_object(value) @@ -1006,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 six.integer_types: + if type(value) in _compat.INT_TYPES: value = ulong(value) self._correlation_id.rewind() self._correlation_id.put_object(value) @@ -1438,7 +1438,7 @@ class Data: def type_name(type): return Data.type_names[type] def __init__(self, capacity=16): - if type(capacity) in six.integer_types: + if type(capacity) in _compat.INT_TYPES: self._data = pn_data(capacity) self._free = True else: @@ -1941,7 +1941,7 @@ class Data: If the current node is a char, returns its value, returns 0 otherwise. """ - return char(six.unichr(pn_data_get_char(self._data))) + return char(_compat.unichar(pn_data_get_char(self._data))) def get_ulong(self): """ @@ -2340,12 +2340,12 @@ def unicode2utf8(string): """ if string is None: return None - if six.PY2: + if _compat.IS_PY2: if isinstance(string, unicode): return string.encode('utf-8') elif isinstance(string, str): return string - elif six.PY3: + else: # decoding a string results in bytes if isinstance(string, str): string = string.encode('utf-8') @@ -2358,10 +2358,10 @@ 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): + if isinstance(string, _compat.TEXT_TYPES): # already unicode return string - elif isinstance(string, six.binary_type): + elif isinstance(string, _compat.BINARY_TYPES): return string.decode('utf8') else: raise TypeError("Unrecognized string type") @@ -2892,8 +2892,6 @@ class Sender(Link): @type data: binary @param data: data to send """ - #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): @@ -3767,7 +3765,7 @@ class _cadapter: def exception(self, exc, val, tb): if self.on_error is None: - six.reraise(exc, val, tb) + _compat.raise_(exc, val, tb) else: self.on_error((exc, val, tb)) @@ -3788,7 +3786,7 @@ class WrappedHandler(Wrapper): def _on_error(self, info): on_error = getattr(self, "on_error", None) if on_error is None: - six.reraise(info[0], info[1], info[2]) + _compat.raise_(info[0], info[1], info[2]) else: on_error(info) http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/646ee41c/proton-c/bindings/python/proton/_compat.py ---------------------------------------------------------------------- diff --git a/proton-c/bindings/python/proton/_compat.py b/proton-c/bindings/python/proton/_compat.py new file mode 100644 index 0000000..4585dfc --- /dev/null +++ b/proton-c/bindings/python/proton/_compat.py @@ -0,0 +1,84 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +""" +Utilities to help Proton support both python2 and python3. +""" + +import sys +import types +IS_PY2 = sys.version_info[0] == 2 +IS_PY3 = sys.version_info[0] == 3 + +if IS_PY3: + INT_TYPES = (int,) + TEXT_TYPES = (str,) + STRING_TYPES = (str,) + BINARY_TYPES = (bytes,) + CLASS_TYPES = (type,) + + def raise_(t, v=None, tb=None): + """Mimic the old 2.x raise behavior: + Raise an exception of type t with value v using optional traceback tb + """ + if v is None: + v = t() + if tb is None: + raise v + else: + raise v.with_traceback(tb) + + def iteritems(d): + return iter(d.items()) + + def unichar(i): + return chr(i) + + def str2bin(s, encoding='latin-1'): + """Convert str to binary type""" + return s.encode(encoding) + + def str2unicode(s): + return s + +else: + INT_TYPES = (int, long) + TEXT_TYPES = (unicode,) + # includes both unicode and non-unicode strings: + STRING_TYPES = (basestring,) + BINARY_TYPES = (str,) + CLASS_TYPES = (type, types.ClassType) + + # the raise syntax will cause a parse error in Py3, so 'sneak' in a + # definition that won't cause the parser to barf + exec("""def raise_(t, v=None, tb=None): + raise t, v, tb +""") + + def iteritems(d, **kw): + return d.iteritems() + + def unichar(i): + return unichr(i) + + def str2bin(s, encoding='latin-1'): + return s + + def str2unicode(s): + return unicode(s, "unicode_escape") http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/646ee41c/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 8f00aa3..9464302 100644 --- a/proton-c/bindings/python/proton/handlers.py +++ b/proton-c/bindings/python/proton/handlers.py @@ -17,7 +17,6 @@ # under the License. # 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 http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/646ee41c/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 b792c37..2260375 100644 --- a/proton-c/bindings/python/proton/reactor.py +++ b/proton-c/bindings/python/proton/reactor.py @@ -18,8 +18,6 @@ from __future__ import absolute_import # under the License. # 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 @@ -33,6 +31,12 @@ import traceback from proton import WrappedHandler, _chandler, secs2millis, millis2secs, timeout2millis, millis2timeout, Selectable from .wrapper import Wrapper, PYCTX from cproton import * +from . import _compat + +try: + import Queue +except ImportError: + import queue as Queue class Task(Wrapper): @@ -139,7 +143,7 @@ class Reactor(Wrapper): for exc, value, tb in self.errors[:-1]: traceback.print_exception(exc, value, tb) exc, value, tb = self.errors[-1] - six.reraise(exc, value, tb) + _compat.raise_(exc, value, tb) def process(self): result = pn_reactor_process(self._impl) @@ -211,7 +215,7 @@ class EventInjector(object): of the reactor to which this EventInjector was added. """ self.queue.put(event) - os.write(self.pipe[1], six.b("!")) + os.write(self.pipe[1], _compat.str2bin("!")) def close(self): """ @@ -667,7 +671,7 @@ class Container(Reactor): Various LinkOptions can be specified to further control the attachment. """ - if isinstance(context, six.string_types): + if isinstance(context, _compat.STRING_TYPES): context = Url(context) if isinstance(context, Url) and not target: target = context.path @@ -708,7 +712,7 @@ class Container(Reactor): Various LinkOptions can be specified to further control the attachment. """ - if isinstance(context, six.string_types): + if isinstance(context, _compat.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/646ee41c/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 7b8ec13..880c466 100644 --- a/proton-c/bindings/python/proton/utils.py +++ b/proton-c/bindings/python/proton/utils.py @@ -17,8 +17,6 @@ # 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 from proton import ProtonException, Timeout, Url http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/646ee41c/proton-c/mllib/__init__.py ---------------------------------------------------------------------- diff --git a/proton-c/mllib/__init__.py b/proton-c/mllib/__init__.py index e506060..c0362cd 100644 --- a/proton-c/mllib/__init__.py +++ b/proton-c/mllib/__init__.py @@ -27,12 +27,17 @@ import os, sys import xml.sax, types from xml.sax.handler import ErrorHandler from xml.sax.xmlreader import InputSource -import six -from six.moves import cStringIO as StringIO -from . import dom -from . import transforms -from . import parsers +try: + from io import StringIO +except ImportError: + from cStringIO import StringIO + +if sys.version_info[0] == 2: + import types + CLASS_TYPES = (type, types.ClassType) +else: + CLASS_TYPES = (type,) from . import dom from . import transforms @@ -41,7 +46,7 @@ from . import parsers def transform(node, *args): result = node for t in args: - if isinstance(t, six.class_types): + if isinstance(t, CLASS_TYPES): t = t() result = result.dispatch(t) return result http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/646ee41c/proton-c/mllib/dom.py ---------------------------------------------------------------------- diff --git a/proton-c/mllib/dom.py b/proton-c/mllib/dom.py index b6ca27d..9421504 100644 --- a/proton-c/mllib/dom.py +++ b/proton-c/mllib/dom.py @@ -26,7 +26,11 @@ from __future__ import generators from __future__ import nested_scopes from __future__ import absolute_import -import six +import sys +if sys.version_info[0] == 2: + STRING_TYPES = (basestring,) +else: + STRING_TYPES = (str,) class Container: @@ -179,7 +183,7 @@ class Leaf(Component, Dispatcher): base = None def __init__(self, data): - assert isinstance(data, six.string_types) + assert isinstance(data, STRING_TYPES) self.data = data class Data(Leaf): @@ -269,7 +273,7 @@ class Values(View): yield value def flatten_path(path): - if isinstance(path, six.string_types): + if isinstance(path, STRING_TYPES): for part in path.split("/"): yield part elif callable(path): @@ -292,7 +296,7 @@ class Query(View): select = Query pred = p source = query - elif isinstance(p, six.string_types): + elif isinstance(p, STRING_TYPES): if p[0] == "@": select = Values pred = lambda x, n=p[1:]: x[0] == n http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/646ee41c/proton-c/mllib/transforms.py ---------------------------------------------------------------------- diff --git a/proton-c/mllib/transforms.py b/proton-c/mllib/transforms.py index 43e9ef2..910b507 100644 --- a/proton-c/mllib/transforms.py +++ b/proton-c/mllib/transforms.py @@ -23,7 +23,10 @@ Useful transforms for dom objects. from __future__ import absolute_import from . import dom -from six.moves import cStringIO as StringIO +try: + from io import StringIO +except ImportError: + from cStringIO import StringIO class Visitor: http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/646ee41c/tests/python/proton-test ---------------------------------------------------------------------- diff --git a/tests/python/proton-test b/tests/python/proton-test index 5073ab4..12ccb11 100755 --- a/tests/python/proton-test +++ b/tests/python/proton-test @@ -20,13 +20,17 @@ # 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 from logging import getLogger, StreamHandler, Formatter, Filter, \ WARN, DEBUG, ERROR +if sys.version_info[0] == 3: + CLASS_TYPES = (type,) +else: + CLASS_TYPES = (type, types.ClassType) + levels = { "DEBUG": DEBUG, "WARN": WARN, @@ -555,7 +559,7 @@ class FunctionScanner(PatternMatcher): class ClassScanner(PatternMatcher): def inspect(self, obj): - return type(obj) in six.class_types and self.matches(obj.__name__) + return type(obj) in CLASS_TYPES and self.matches(obj.__name__) def descend(self, cls): # the None is required for older versions of python @@ -566,7 +570,7 @@ class ClassScanner(PatternMatcher): names.sort() for name in names: obj = getattr(cls, name) - if six.callable(obj) and name.startswith("test"): + if hasattr(obj, '__call__') and name.startswith("test"): yield MethodTest(cls, name) class ModuleScanner: @@ -667,19 +671,19 @@ def runthrough(): skip = "skip" else: skip = "pass" - six.print_(colorize("Totals:", 1), end=' ') + sys.stdout.write(colorize("Totals: ", 1)) 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)] - six.print_(", ".join(totals), end=' ') + sys.stdout.write(", ".join(totals)) if opts.hoe and failed > 0: print(" -- (halted after %s)" % run) else: - print() + print("") if opts.time and run > 0: - six.print_(colorize("Timing:", 1), end=' ') + sys.stdout.write(colorize("Timing:", 1)) timing = [colorize_word("elapsed", "%.2fs elapsed" % (end - start)), colorize_word("average", "%.2fs average" % ((end - start)/run))] print(", ".join(timing)) http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/646ee41c/tests/python/proton_tests/codec.py ---------------------------------------------------------------------- diff --git a/tests/python/proton_tests/codec.py b/tests/python/proton_tests/codec.py index e340732..d924027 100644 --- a/tests/python/proton_tests/codec.py +++ b/tests/python/proton_tests/codec.py @@ -18,9 +18,9 @@ # import os, sys -import six from . import common from proton import * +from proton._compat import raise_, str2unicode, unichar, str2bin try: from uuid import uuid4 except ImportError: @@ -129,7 +129,7 @@ class DataTest(Test): putter(v) except Exception: etype, value, trace = sys.exc_info() - six.reraise(etype, etype("%s(%r): %s" % (putter.__name__, v, value)), trace) + raise_(etype, etype("%s(%r): %s" % (putter.__name__, v, value)), trace) return putter # (bits, signed) for each integer type @@ -275,8 +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", six.b("this"), six.b("is"), six.b("a"), six.b("test"), - six.b("of" "b\x00inary")) + self._test("binary", str2bin("this"), str2bin("is"), str2bin("a"), str2bin("test"), + str2bin("of" "b\x00inary")) def testSymbol(self): self._test("symbol", "this is a symbol test", "bleh", "blah") @@ -285,7 +285,7 @@ class DataTest(Test): self._test("timestamp", 0, 12345, 1000000) def testChar(self): - self._test("char", 'a', 'b', 'c', six.u('\u1234')) + self._test("char", 'a', 'b', 'c', unichar(0x20AC)) def testUUID(self): self._test("uuid", uuid4(), uuid4(), uuid4()) @@ -297,7 +297,7 @@ class DataTest(Test): self._test("decimal64", 0, 1, 2, 3, 4, 2**60) def testDecimal128(self): - self._test("decimal128", six.b("fdsaasdf;lkjjkl;"), six.b("x"*16)) + self._test("decimal128", str2bin("fdsaasdf;lkjjkl;"), str2bin("x"*16)) def testCopy(self): self.data.put_described() @@ -338,10 +338,10 @@ class DataTest(Test): obj = {symbol("key"): timestamp(1234), ulong(123): "blah", char("c"): "bleh", - 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} + str2unicode("desc"): Described(symbol("url"), str2unicode("http://example.org")), + str2unicode("array"): Array(UNDESCRIBED, Data.INT, 1, 2, 3), + str2unicode("list"): [1, 2, 3, None, 4], + str2unicode("boolean"): True} self.data.put_object(obj) enc = self.data.encode() data = Data() @@ -352,7 +352,7 @@ class DataTest(Test): assert copy == obj, (copy, obj) def testLookup(self): - obj = {symbol("key"): six.u("value"), + obj = {symbol("key"): str2unicode("value"), symbol("pi"): 3.14159, symbol("list"): [1, 2, 3, 4]} self.data.put_object(obj) @@ -364,7 +364,7 @@ class DataTest(Test): assert self.data.get_object() == 3.14159 self.data.rewind() assert self.data.lookup("key") - assert self.data.get_object() == six.u("value") + assert self.data.get_object() == str2unicode("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/646ee41c/tests/python/proton_tests/engine.py ---------------------------------------------------------------------- diff --git a/tests/python/proton_tests/engine.py b/tests/python/proton_tests/engine.py index 55da0e5..0880682 100644 --- a/tests/python/proton_tests/engine.py +++ b/tests/python/proton_tests/engine.py @@ -1,4 +1,3 @@ -from __future__ import absolute_import # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file @@ -17,14 +16,15 @@ from __future__ import absolute_import # specific language governing permissions and limitations # under the License. # +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 +from proton._compat import str2bin # older versions of gc do not provide the garbage list if not hasattr(gc, "garbage"): @@ -48,7 +48,7 @@ try: bytearray() except: def bytearray(x): - return six.b('\x00') * x + return str2bin('\x00') * x OUTPUT_SIZE = 10*1024 @@ -749,7 +749,7 @@ class TransferTest(Test): assert tag == "tag", tag assert d.writable - n = self.snd.send(six.b("this is a test")) + n = self.snd.send(str2bin("this is a test")) assert self.snd.advance() assert self.c1.work_head is None @@ -762,7 +762,7 @@ class TransferTest(Test): def test_multiframe(self): self.rcv.flow(1) self.snd.delivery("tag") - msg = six.b("this is a test") + msg = str2bin("this is a test") n = self.snd.send(msg) assert n == len(msg) @@ -777,9 +777,9 @@ class TransferTest(Test): assert binary == msg, (binary, msg) binary = self.rcv.recv(1024) - assert binary == six.b("") + assert binary == str2bin("") - msg = six.b("this is more") + msg = str2bin("this is more") n = self.snd.send(msg) assert n == len(msg) assert self.snd.advance() @@ -798,7 +798,7 @@ class TransferTest(Test): self.pump() sd = self.snd.delivery("tag") - msg = six.b("this is a test") + msg = str2bin("this is a test") n = self.snd.send(msg) assert n == len(msg) assert self.snd.advance() @@ -897,7 +897,7 @@ class TransferTest(Test): for x in range(10): self.snd.delivery("tag%d" % x) - msg = six.b("this is a test") + msg = str2bin("this is a test") n = self.snd.send(msg) assert n == len(msg) assert self.snd.advance() @@ -1413,7 +1413,7 @@ class CreditTest(Test): sd = self.snd.delivery("tagA") assert sd - n = self.snd.send(six.b("A")) + n = self.snd.send(str2bin("A")) assert n == 1 self.pump() self.snd.advance() @@ -1430,7 +1430,7 @@ class CreditTest(Test): assert self.rcv.credit == 10, self.rcv.credit data = self.rcv.recv(10) - assert data == six.b("A"), data + assert data == str2bin("A"), data self.rcv.advance() self.pump() assert self.snd.credit == 9, self.snd.credit @@ -1451,7 +1451,7 @@ class CreditTest(Test): sd = self.snd.delivery("tagB") assert sd - n = self.snd.send(six.b("B")) + n = self.snd.send(str2bin("B")) assert n == 1 self.snd.advance() self.pump() @@ -1465,7 +1465,7 @@ class CreditTest(Test): sd = self.snd.delivery("tagC") assert sd - n = self.snd.send(six.b("C")) + n = self.snd.send(str2bin("C")) assert n == 1 self.snd.advance() self.pump() @@ -1480,10 +1480,10 @@ class CreditTest(Test): assert self.rcv.credit == 2, self.rcv.credit data = self.rcv.recv(10) - assert data == six.b("B"), data + assert data == str2bin("B"), data self.rcv.advance() data = self.rcv.recv(10) - assert data == six.b("C"), data + assert data == str2bin("C"), data self.rcv.advance() self.pump() assert self.snd.credit == 0, self.snd.credit @@ -1818,7 +1818,7 @@ class PipelineTest(Test): for i in range(10): d = snd.delivery("delivery-%s" % i) - snd.send(six.b("delivery-%s" % i)) + snd.send(str2bin("delivery-%s" % i)) d.settle() snd.close() @@ -2250,7 +2250,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(six.b("Hello World!")) + snd.send(str2bin("Hello World!")) snd.advance() self.pump() self.expect() @@ -2266,7 +2266,7 @@ class EventTest(CollectorTest): snd, rcv = self.testFlowEvents() snd.open() dlv = snd.delivery("delivery") - snd.send(six.b("Hello World!")) + snd.send(str2bin("Hello World!")) assert snd.advance() self.expect(Event.LINK_LOCAL_OPEN, Event.TRANSPORT) self.pump() @@ -2297,7 +2297,7 @@ class EventTest(CollectorTest): t.bind(c) self.expect(Event.CONNECTION_BOUND) assert t.condition is None - t.push(six.b("asdf")) + t.push(str2bin("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/646ee41c/tests/python/proton_tests/interop.py ---------------------------------------------------------------------- diff --git a/tests/python/proton_tests/interop.py b/tests/python/proton_tests/interop.py index 5cbab99..4eedf3c 100644 --- a/tests/python/proton_tests/interop.py +++ b/tests/python/proton_tests/interop.py @@ -19,8 +19,8 @@ from proton import * import os -import six from . import common +from proton._compat import str2bin def find_test_interop_dir(): @@ -100,10 +100,10 @@ class InteropTest(common.Test): def test_strings(self): self.decode_data_file("strings") - self.assert_next(Data.BINARY, six.b("abc\0defg")) + self.assert_next(Data.BINARY, str2bin("abc\0defg")) self.assert_next(Data.STRING, "abcdefg") self.assert_next(Data.SYMBOL, "abcdefg") - self.assert_next(Data.BINARY, six.b("")) + self.assert_next(Data.BINARY, str2bin("")) self.assert_next(Data.STRING, "") self.assert_next(Data.SYMBOL, "") assert self.data.next() is None http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/646ee41c/tests/python/proton_tests/message.py ---------------------------------------------------------------------- diff --git a/tests/python/proton_tests/message.py b/tests/python/proton_tests/message.py index 10d2326..2f7cb4f 100644 --- a/tests/python/proton_tests/message.py +++ b/tests/python/proton_tests/message.py @@ -18,9 +18,9 @@ # import os -import six from . import common from proton import * +from proton._compat import str2bin try: from uuid import uuid4 except ImportError: @@ -73,8 +73,8 @@ class AccessorsTest(Test): self._test("delivery_count", 0, range(0, 1024)) def testUserId(self): - self._test("user_id", six.b(""), (six.b("asdf"), six.b("fdsa"), - six.b("asd\x00fdsa"), six.b(""))) + self._test("user_id", str2bin(""), (str2bin("asdf"), str2bin("fdsa"), + str2bin("asd\x00fdsa"), str2bin(""))) def testAddress(self): self._test_str("address") http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/646ee41c/tests/python/proton_tests/messenger.py ---------------------------------------------------------------------- diff --git a/tests/python/proton_tests/messenger.py b/tests/python/proton_tests/messenger.py index 30d0ec5..e139b3c 100644 --- a/tests/python/proton_tests/messenger.py +++ b/tests/python/proton_tests/messenger.py @@ -19,7 +19,6 @@ 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 @@ -762,8 +761,8 @@ class NBMessengerTest(common.Test): msg = Message() msg.address = self.address - for i in xrange(16): - for i in xrange(1024): + for i in range(16): + for i in range(1024): self.client.put(msg) self.pump() if self.client.outgoing > 0: @@ -801,7 +800,7 @@ class NBMessengerTest(common.Test): deadline = time() + self.timeout while time() < deadline: old = self.server.incoming - for j in xrange(1001): + for j in range(1001): self.client.put(msg) self.pump() if old == self.server.incoming: http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/646ee41c/tests/python/proton_tests/sasl.py ---------------------------------------------------------------------- diff --git a/tests/python/proton_tests/sasl.py b/tests/python/proton_tests/sasl.py index 2734364..ce10882 100644 --- a/tests/python/proton_tests/sasl.py +++ b/tests/python/proton_tests/sasl.py @@ -1,4 +1,3 @@ -from __future__ import absolute_import # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file @@ -17,12 +16,13 @@ from __future__ import absolute_import # specific language governing permissions and limitations # under the License. # +from __future__ import absolute_import import sys, os -import six from . import common from proton import * from .common import pump, Skipped +from proton._compat import str2bin class Test(common.Test): pass @@ -122,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 = six.b("") + out1_sasl_and_amqp = str2bin("") t1_still_producing = True while t1_still_producing: out1 = self.t1.peek(1024) @@ -172,17 +172,17 @@ class SaslTest(Test): out = self.t1.peek(1024) self.t1.pop(len(out)) - self.t1.push(six.b("AMQP\x03\x01\x00\x00")) + self.t1.push(str2bin("AMQP\x03\x01\x00\x00")) out = self.t1.peek(1024) self.t1.pop(len(out)) - self.t1.push(six.b("\x00\x00\x00")) + self.t1.push(str2bin("\x00\x00\x00")) out = self.t1.peek(1024) self.t1.pop(len(out)) - self.t1.push(six.b("6\x02\x01\x00\x00\x00S@\xc04\x01\xe01\x04\xa3\x05PLAIN\x0aDIGEST-MD5\x09ANONYMOUS\x08CRAM-MD5")) + self.t1.push(str2bin("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(six.b("\x00\x00\x00\x10\x02\x01\x00\x00\x00SD\xc0\x03\x01P\x00")) + self.t1.push(str2bin("\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/646ee41c/tests/python/proton_tests/transport.py ---------------------------------------------------------------------- diff --git a/tests/python/proton_tests/transport.py b/tests/python/proton_tests/transport.py index 0b22f4e..243b3cb 100644 --- a/tests/python/proton_tests/transport.py +++ b/tests/python/proton_tests/transport.py @@ -18,9 +18,9 @@ # import os -import six from . import common from proton import * +from proton._compat import str2bin class Test(common.Test): @@ -62,16 +62,16 @@ class TransportTest(Test): assert self.conn.remote_condition.name == name, self.conn.remote_condition def testEOS(self): - self.transport.push(six.b("")) # should be a noop + self.transport.push(str2bin("")) # 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(six.b("AMQ")) # partial header + self.transport.push(str2bin("AMQ")) # partial header self.transport.close_tail() # should result in framing error self.assert_error(u'amqp:connection:framing-error') - def testGarbage(self, garbage=six.b("GARBAGE_")): + def testGarbage(self, garbage=str2bin("GARBAGE_")): self.transport.push(garbage) self.assert_error(u'amqp:connection:framing-error') assert self.transport.pending() < 0 @@ -79,13 +79,13 @@ class TransportTest(Test): assert self.transport.pending() < 0 def testSmallGarbage(self): - self.testGarbage(six.b("XXX")) + self.testGarbage(str2bin("XXX")) def testBigGarbage(self): - self.testGarbage(six.b("GARBAGE_XXX")) + self.testGarbage(str2bin("GARBAGE_XXX")) def testHeader(self): - self.transport.push(six.b("AMQP\x00\x01\x00\x00")) + self.transport.push(str2bin("AMQP\x00\x01\x00\x00")) self.transport.close_tail() self.assert_error(u'amqp:connection:framing-error') @@ -103,8 +103,8 @@ class TransportTest(Test): trn = Transport() trn.bind(conn) out = trn.peek(1024) - assert six.b("test-container") in out, repr(out) - assert six.b("test-hostname") in out, repr(out) + assert str2bin("test-container") in out, repr(out) + assert str2bin("test-hostname") in out, repr(out) self.transport.push(out) c = Connection() @@ -161,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) == six.b("") + assert self.transport.peek(1024) == str2bin("") self.peer.push(dat1) self.peer.push(dat2[len(dat1):]) http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/646ee41c/tests/python/proton_tests/utils.py ---------------------------------------------------------------------- diff --git a/tests/python/proton_tests/utils.py b/tests/python/proton_tests/utils.py index 86eb6f3..1ddccc4 100644 --- a/tests/python/proton_tests/utils.py +++ b/tests/python/proton_tests/utils.py @@ -18,7 +18,6 @@ # 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 @@ -78,7 +77,7 @@ class SyncRequestResponseTest(Test): def test_request_response(self): def test(name, address="x"): - for i in xrange(5): + for i in range(5): body="%s%s" % (name, i) response = client.call(Message(address=address, body=body)) self.assertEquals(response.address, client.reply_to) http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/646ee41c/tests/python/six.py ---------------------------------------------------------------------- diff --git a/tests/python/six.py b/tests/python/six.py deleted file mode 100644 index 4b572bb..0000000 --- a/tests/python/six.py +++ /dev/null @@ -1,849 +0,0 @@ -"""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 <[email protected]>" -__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 - -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: [email protected] For additional commands, e-mail: [email protected]
