From 6d92008e46d850ee034d59de72d7f92bfde12220 Mon Sep 17 00:00:00 2001 From: Christophe de Vienne Date: Tue, 24 Apr 2012 10:47:27 +0200 Subject: [PATCH] test_types unit tests now successfully pass under python 3.2 --- .hgignore | 1 + setup.py | 4 +++- wsme/exc.py | 16 +++++++++------- wsme/root.py | 16 ++++++++++------ wsme/tests/test_api.py | 18 ++++++++++-------- wsme/tests/test_types.py | 28 ++++++++++++++++------------ wsme/tests/test_utils.py | 2 +- wsme/types.py | 29 ++++++++++++++++++----------- 8 files changed, 68 insertions(+), 46 deletions(-) diff --git a/.hgignore b/.hgignore index 42eda0d..9ca10e5 100644 --- a/.hgignore +++ b/.hgignore @@ -9,6 +9,7 @@ syntax: glob .coverage coverage.xml .noseids +.tox nosetests.xml syntax: regexp diff --git a/setup.py b/setup.py index 6b50ee7..3239b9c 100644 --- a/setup.py +++ b/setup.py @@ -1,4 +1,5 @@ import os +import sys from setuptools import setup @@ -21,8 +22,9 @@ setup( 'wsme.protocols': ['templates/*.html'], }, install_requires=[ + 'six', 'simplegeneric', - 'webob', + 'webob' + ('<=1.1.1' if sys.version_info[:2] <= (2, 5) else ''), ], classifiers=[ 'Development Status :: 3 - Alpha', diff --git a/wsme/exc.py b/wsme/exc.py index d3eb496..4feac7a 100644 --- a/wsme/exc.py +++ b/wsme/exc.py @@ -1,7 +1,8 @@ -import __builtin__ +import six +from six.moves import builtins -if '_' not in __builtin__.__dict__: - __builtin__._ = lambda s: s +if '_' not in builtins.__dict__: + builtins._ = lambda s: s class ClientSideError(RuntimeError): @@ -18,7 +19,8 @@ class InvalidInput(ClientSideError): @property def faultstring(self): - return _(u"Invalid input for field/attribute %s. Value: '%s'. %s") % ( + return _(six.u( + "Invalid input for field/attribute %s. Value: '%s'. %s")) % ( self.fieldname, self.value, self.msg) @@ -29,7 +31,7 @@ class MissingArgument(ClientSideError): @property def faultstring(self): - return _(u'Missing argument: "%s"%s') % ( + return _(six.u('Missing argument: "%s"%s')) % ( self.argname, self.msg and ": " + self.msg or "") @@ -40,7 +42,7 @@ class UnknownArgument(ClientSideError): @property def faultstring(self): - return _(u'Unknown argument: "%s"%s') % ( + return _(six.u('Unknown argument: "%s"%s')) % ( self.argname, self.msg and ": " + self.msg or "") @@ -50,4 +52,4 @@ class UnknownFunction(ClientSideError): @property def faultstring(self): - return _(u"Unknown function name: %s") % (self.name) + return _(six.u("Unknown function name: %s")) % (self.name) diff --git a/wsme/root.py b/wsme/root.py index 87227c8..2a2c0e1 100644 --- a/wsme/root.py +++ b/wsme/root.py @@ -2,6 +2,7 @@ import logging import sys import traceback import weakref +import six import webob @@ -127,9 +128,9 @@ class WSRoot(object): context.path = protocol.extract_path(context) if context.path is None: - raise exc.ClientSideError( - u'The %s protocol was unable to extract a function ' - u'path from the request' % protocol.name) + raise exc.ClientSideError(six.u( + 'The %s protocol was unable to extract a function ' + 'path from the request') % protocol.name) context.func, context.funcdef = self._lookup_function(context.path) kw = protocol.read_arguments(context) @@ -153,7 +154,8 @@ class WSRoot(object): # TODO make sure result type == a._wsme_definition.return_type return protocol.encode_result(context, result) - except Exception, e: + except Exception: + e = sys.exc_info()[1] infos = self._format_exception(sys.exc_info()) if isinstance(e, exc.ClientSideError): request.client_errorcount += 1 @@ -171,7 +173,8 @@ class WSRoot(object): try: msg = None protocol = self._select_protocol(request) - except Exception, e: + except Exception: + e = sys.exc_info()[1] msg = ("Error while selecting protocol: %s" % str(e)) log.exception(msg) protocol = None @@ -312,7 +315,8 @@ class WSRoot(object): return html_body % dict( css=formatter.get_style_defs(), content=highlight(content, lexer, formatter).encode('utf8')) - except Exception, e: + except Exception: + e = sys.exc_info()[1] log.warning( "Could not pygment the content because of the following " "error :\n%s" % e) diff --git a/wsme/tests/test_api.py b/wsme/tests/test_api.py index e0f4c8d..0e552a3 100644 --- a/wsme/tests/test_api.py +++ b/wsme/tests/test_api.py @@ -1,11 +1,12 @@ # encoding=utf8 +import six +import sys + import unittest -import webob -from webob.dec import wsgify import webtest -from wsme import * +from wsme import WSRoot, expose, validate from wsme.api import scan_api, pexpose from wsme.api import FunctionArgument, FunctionDefinition from wsme.types import iscomplex @@ -28,7 +29,7 @@ def test_pexpose(): @pexpose(None, "text/xml") def ufunc(self): - return u"

é

" + return six.u("

\xc3\xa9

") func, fd = FunctionDefinition.get(Proto.func) assert fd.return_type is None @@ -44,7 +45,7 @@ def test_pexpose(): assert res.status_int == 200 assert res.body == "

", res.body res = app.get('/ufunc') - assert res.unicode_body == u"

é

", res.body + assert res.unicode_body == six.u("

\xc3\xa9

"), res.body class TestController(unittest.TestCase): @@ -131,7 +132,8 @@ class TestController(unittest.TestCase): try: list(scan_api(r)) assert False, "ValueError not raised" - except ValueError, e: + except ValueError: + e = sys.exc_info()[1] assert str(e).startswith("Path is too long") def test_handle_request(self): @@ -165,7 +167,7 @@ class TestController(unittest.TestCase): app = webtest.TestApp(wsme.wsgi.adapt(r)) res = app.get('/', expect_errors=True) - print res.status, res.body + print(res.status, res.body) assert res.status_int == 400 def test_no_available_protocol(self): @@ -175,7 +177,7 @@ class TestController(unittest.TestCase): res = app.get('/', expect_errors=True) assert res.status_int == 500 - print res.body + print(res.body) assert res.body.find( "None of the following protocols can handle this request") != -1 diff --git a/wsme/tests/test_types.py b/wsme/tests/test_types.py index 0208781..1ec41a5 100644 --- a/wsme/tests/test_types.py +++ b/wsme/tests/test_types.py @@ -1,4 +1,7 @@ import unittest +import sys +import six + from wsme import types @@ -27,25 +30,25 @@ class TestTypes(unittest.TestCase): def test_flat_type(self): class Flat(object): aint = int - astr = str - auni = unicode + abytes = six.binary_type + atext = six.text_type afloat = float types.register_type(Flat) assert len(Flat._wsme_attributes) == 4 attrs = Flat._wsme_attributes - print attrs + print(attrs) assert attrs[0].key == 'aint' assert attrs[0].name == 'aint' assert isinstance(attrs[0], types.wsattr) assert attrs[0].datatype == int assert attrs[0].mandatory == False - assert attrs[1].key == 'astr' - assert attrs[1].name == 'astr' - assert attrs[2].key == 'auni' - assert attrs[2].name == 'auni' + assert attrs[1].key == 'abytes' + assert attrs[1].name == 'abytes' + assert attrs[2].key == 'atext' + assert attrs[2].name == 'atext' assert attrs[3].key == 'afloat' assert attrs[3].name == 'afloat' @@ -66,13 +69,13 @@ class TestTypes(unittest.TestCase): types.register_type(ForcedOrder) - print ForcedOrder._wsme_attributes + print(ForcedOrder._wsme_attributes) assert ForcedOrder._wsme_attributes[0].key == 'a2' assert ForcedOrder._wsme_attributes[1].key == 'a1' assert ForcedOrder._wsme_attributes[2].key == 'a3' c = gen_class() - print c + print(c) types.register_type(c) del c._wsme_attributes @@ -101,7 +104,7 @@ class TestTypes(unittest.TestCase): types.register_type(WithWSProp) - print WithWSProp._wsme_attributes + print(WithWSProp._wsme_attributes) assert len(WithWSProp._wsme_attributes) == 1 a = WithWSProp._wsme_attributes[0] assert a.key == 'aint' @@ -174,7 +177,8 @@ class TestTypes(unittest.TestCase): try: obj.a = 'v3' assert False, 'ValueError was not raised' - except ValueError, e: + except ValueError: + e = sys.exc_info()[1] assert str(e) == \ "a: Value 'v3' is invalid (should be one of: v1, v2)", e @@ -204,7 +208,7 @@ class TestTypes(unittest.TestCase): assert len(AType._wsme_attributes) == 2 attrs = AType._wsme_attributes - print attrs + print(attrs) assert attrs[0].key == 'a_list', attrs[0].key assert attrs[0].name == 'a.list', attrs[0].name diff --git a/wsme/tests/test_utils.py b/wsme/tests/test_utils.py index 2c540b2..a9c5030 100644 --- a/wsme/tests/test_utils.py +++ b/wsme/tests/test_utils.py @@ -8,7 +8,7 @@ class TestUtils(unittest.TestCase): def test_parse_isodate(self): good_dates = [ ('2008-02-01', datetime.date(2008, 2, 1)), - ('2009-01-04', datetime.date(2009, 01, 04)), + ('2009-01-04', datetime.date(2009, 1, 4)), ] ill_formatted_dates = [ '24-12-2004' diff --git a/wsme/types.py b/wsme/types.py index 91ee70d..6d3a73a 100644 --- a/wsme/types.py +++ b/wsme/types.py @@ -3,6 +3,8 @@ import datetime import decimal import inspect import weakref +import six +import sys class UserType(object): @@ -68,9 +70,10 @@ class Enum(UserType): def frombasetype(self, value): return value -pod_types = [str, unicode, int, float, bool] -dt_types = [datetime.date, datetime.time, datetime.datetime] -extra_types = [binary, decimal.Decimal] +pod_types = six.integer_types + ( + six.binary_type, six.text_type, float, bool) +dt_types = (datetime.date, datetime.time, datetime.datetime) +extra_types = (binary, decimal.Decimal) native_types = pod_types + dt_types + extra_types complex_types = [] @@ -79,8 +82,12 @@ dict_types = [] class UnsetType(object): - def __nonzero__(self): - return False + if sys.version < '3': + def __nonzero__(self): + return False + else: + def __bool__(self): + return False Unset = UnsetType() @@ -117,13 +124,12 @@ def validate_value(datatype, value): raise ValueError("Wrong type. Expected '%s', got '%s'" % ( datatype, type(value) )) - key_type = datatype.keys()[0] - value_type = datatype.values()[0] + key_type, value_type = list(datatype.items())[0] for key, v in value.items(): validate_value(key_type, key) validate_value(value_type, v) - elif datatype in (int, long): - if not isinstance(value, int) and not isinstance(value, long): + elif datatype in six.integer_types: + if not isinstance(value, six.integer_types): raise ValueError( "Wrong type. Expected an integer, got '%s'" % ( type(value) @@ -206,7 +212,8 @@ class wsattr(object): def __set__(self, instance, value): try: validate_value(self.datatype, value) - except ValueError, e: + except ValueError: + e = sys.exc_info()[1] raise ValueError("%s: %s" % (self.name, e)) if value is Unset: if hasattr(instance, '_' + self.key): @@ -326,7 +333,7 @@ def register_type(class_): if isinstance(class_, dict): if len(class_) != 1: raise ValueError("Cannot register type %s" % repr(class_)) - key_type, value_type = class_.items()[0] + key_type, value_type = list(class_.items())[0] if key_type not in pod_types: raise ValueError("Dictionnaries key can only be a pod type") register_type(value_type)