test_types unit tests now successfully pass under python 3.2

This commit is contained in:
Christophe de Vienne 2012-04-24 10:47:27 +02:00
parent 765a4baf8b
commit 6d92008e46
8 changed files with 68 additions and 46 deletions

View File

@ -9,6 +9,7 @@ syntax: glob
.coverage
coverage.xml
.noseids
.tox
nosetests.xml
syntax: regexp

View File

@ -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',

View File

@ -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)

View File

@ -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)

View File

@ -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"<p>é</p>"
return six.u("<p>\xc3\xa9</p>")
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 == "<p></p>", res.body
res = app.get('/ufunc')
assert res.unicode_body == u"<p>é</p>", res.body
assert res.unicode_body == six.u("<p>\xc3\xa9</p>"), 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

View File

@ -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

View File

@ -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'

View File

@ -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)