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
coverage.xml coverage.xml
.noseids .noseids
.tox
nosetests.xml nosetests.xml
syntax: regexp syntax: regexp

View File

@ -1,4 +1,5 @@
import os import os
import sys
from setuptools import setup from setuptools import setup
@ -21,8 +22,9 @@ setup(
'wsme.protocols': ['templates/*.html'], 'wsme.protocols': ['templates/*.html'],
}, },
install_requires=[ install_requires=[
'six',
'simplegeneric', 'simplegeneric',
'webob', 'webob' + ('<=1.1.1' if sys.version_info[:2] <= (2, 5) else ''),
], ],
classifiers=[ classifiers=[
'Development Status :: 3 - Alpha', 'Development Status :: 3 - Alpha',

View File

@ -1,7 +1,8 @@
import __builtin__ import six
from six.moves import builtins
if '_' not in __builtin__.__dict__: if '_' not in builtins.__dict__:
__builtin__._ = lambda s: s builtins._ = lambda s: s
class ClientSideError(RuntimeError): class ClientSideError(RuntimeError):
@ -18,7 +19,8 @@ class InvalidInput(ClientSideError):
@property @property
def faultstring(self): 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) self.fieldname, self.value, self.msg)
@ -29,7 +31,7 @@ class MissingArgument(ClientSideError):
@property @property
def faultstring(self): def faultstring(self):
return _(u'Missing argument: "%s"%s') % ( return _(six.u('Missing argument: "%s"%s')) % (
self.argname, self.msg and ": " + self.msg or "") self.argname, self.msg and ": " + self.msg or "")
@ -40,7 +42,7 @@ class UnknownArgument(ClientSideError):
@property @property
def faultstring(self): def faultstring(self):
return _(u'Unknown argument: "%s"%s') % ( return _(six.u('Unknown argument: "%s"%s')) % (
self.argname, self.msg and ": " + self.msg or "") self.argname, self.msg and ": " + self.msg or "")
@ -50,4 +52,4 @@ class UnknownFunction(ClientSideError):
@property @property
def faultstring(self): 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 sys
import traceback import traceback
import weakref import weakref
import six
import webob import webob
@ -127,9 +128,9 @@ class WSRoot(object):
context.path = protocol.extract_path(context) context.path = protocol.extract_path(context)
if context.path is None: if context.path is None:
raise exc.ClientSideError( raise exc.ClientSideError(six.u(
u'The %s protocol was unable to extract a function ' 'The %s protocol was unable to extract a function '
u'path from the request' % protocol.name) 'path from the request') % protocol.name)
context.func, context.funcdef = self._lookup_function(context.path) context.func, context.funcdef = self._lookup_function(context.path)
kw = protocol.read_arguments(context) kw = protocol.read_arguments(context)
@ -153,7 +154,8 @@ class WSRoot(object):
# TODO make sure result type == a._wsme_definition.return_type # TODO make sure result type == a._wsme_definition.return_type
return protocol.encode_result(context, result) return protocol.encode_result(context, result)
except Exception, e: except Exception:
e = sys.exc_info()[1]
infos = self._format_exception(sys.exc_info()) infos = self._format_exception(sys.exc_info())
if isinstance(e, exc.ClientSideError): if isinstance(e, exc.ClientSideError):
request.client_errorcount += 1 request.client_errorcount += 1
@ -171,7 +173,8 @@ class WSRoot(object):
try: try:
msg = None msg = None
protocol = self._select_protocol(request) protocol = self._select_protocol(request)
except Exception, e: except Exception:
e = sys.exc_info()[1]
msg = ("Error while selecting protocol: %s" % str(e)) msg = ("Error while selecting protocol: %s" % str(e))
log.exception(msg) log.exception(msg)
protocol = None protocol = None
@ -312,7 +315,8 @@ class WSRoot(object):
return html_body % dict( return html_body % dict(
css=formatter.get_style_defs(), css=formatter.get_style_defs(),
content=highlight(content, lexer, formatter).encode('utf8')) content=highlight(content, lexer, formatter).encode('utf8'))
except Exception, e: except Exception:
e = sys.exc_info()[1]
log.warning( log.warning(
"Could not pygment the content because of the following " "Could not pygment the content because of the following "
"error :\n%s" % e) "error :\n%s" % e)

View File

@ -1,11 +1,12 @@
# encoding=utf8 # encoding=utf8
import six
import sys
import unittest import unittest
import webob
from webob.dec import wsgify
import webtest import webtest
from wsme import * from wsme import WSRoot, expose, validate
from wsme.api import scan_api, pexpose from wsme.api import scan_api, pexpose
from wsme.api import FunctionArgument, FunctionDefinition from wsme.api import FunctionArgument, FunctionDefinition
from wsme.types import iscomplex from wsme.types import iscomplex
@ -28,7 +29,7 @@ def test_pexpose():
@pexpose(None, "text/xml") @pexpose(None, "text/xml")
def ufunc(self): def ufunc(self):
return u"<p>é</p>" return six.u("<p>\xc3\xa9</p>")
func, fd = FunctionDefinition.get(Proto.func) func, fd = FunctionDefinition.get(Proto.func)
assert fd.return_type is None assert fd.return_type is None
@ -44,7 +45,7 @@ def test_pexpose():
assert res.status_int == 200 assert res.status_int == 200
assert res.body == "<p></p>", res.body assert res.body == "<p></p>", res.body
res = app.get('/ufunc') 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): class TestController(unittest.TestCase):
@ -131,7 +132,8 @@ class TestController(unittest.TestCase):
try: try:
list(scan_api(r)) list(scan_api(r))
assert False, "ValueError not raised" assert False, "ValueError not raised"
except ValueError, e: except ValueError:
e = sys.exc_info()[1]
assert str(e).startswith("Path is too long") assert str(e).startswith("Path is too long")
def test_handle_request(self): def test_handle_request(self):
@ -165,7 +167,7 @@ class TestController(unittest.TestCase):
app = webtest.TestApp(wsme.wsgi.adapt(r)) app = webtest.TestApp(wsme.wsgi.adapt(r))
res = app.get('/', expect_errors=True) res = app.get('/', expect_errors=True)
print res.status, res.body print(res.status, res.body)
assert res.status_int == 400 assert res.status_int == 400
def test_no_available_protocol(self): def test_no_available_protocol(self):
@ -175,7 +177,7 @@ class TestController(unittest.TestCase):
res = app.get('/', expect_errors=True) res = app.get('/', expect_errors=True)
assert res.status_int == 500 assert res.status_int == 500
print res.body print(res.body)
assert res.body.find( assert res.body.find(
"None of the following protocols can handle this request") != -1 "None of the following protocols can handle this request") != -1

View File

@ -1,4 +1,7 @@
import unittest import unittest
import sys
import six
from wsme import types from wsme import types
@ -27,25 +30,25 @@ class TestTypes(unittest.TestCase):
def test_flat_type(self): def test_flat_type(self):
class Flat(object): class Flat(object):
aint = int aint = int
astr = str abytes = six.binary_type
auni = unicode atext = six.text_type
afloat = float afloat = float
types.register_type(Flat) types.register_type(Flat)
assert len(Flat._wsme_attributes) == 4 assert len(Flat._wsme_attributes) == 4
attrs = Flat._wsme_attributes attrs = Flat._wsme_attributes
print attrs print(attrs)
assert attrs[0].key == 'aint' assert attrs[0].key == 'aint'
assert attrs[0].name == 'aint' assert attrs[0].name == 'aint'
assert isinstance(attrs[0], types.wsattr) assert isinstance(attrs[0], types.wsattr)
assert attrs[0].datatype == int assert attrs[0].datatype == int
assert attrs[0].mandatory == False assert attrs[0].mandatory == False
assert attrs[1].key == 'astr' assert attrs[1].key == 'abytes'
assert attrs[1].name == 'astr' assert attrs[1].name == 'abytes'
assert attrs[2].key == 'auni' assert attrs[2].key == 'atext'
assert attrs[2].name == 'auni' assert attrs[2].name == 'atext'
assert attrs[3].key == 'afloat' assert attrs[3].key == 'afloat'
assert attrs[3].name == 'afloat' assert attrs[3].name == 'afloat'
@ -66,13 +69,13 @@ class TestTypes(unittest.TestCase):
types.register_type(ForcedOrder) types.register_type(ForcedOrder)
print ForcedOrder._wsme_attributes print(ForcedOrder._wsme_attributes)
assert ForcedOrder._wsme_attributes[0].key == 'a2' assert ForcedOrder._wsme_attributes[0].key == 'a2'
assert ForcedOrder._wsme_attributes[1].key == 'a1' assert ForcedOrder._wsme_attributes[1].key == 'a1'
assert ForcedOrder._wsme_attributes[2].key == 'a3' assert ForcedOrder._wsme_attributes[2].key == 'a3'
c = gen_class() c = gen_class()
print c print(c)
types.register_type(c) types.register_type(c)
del c._wsme_attributes del c._wsme_attributes
@ -101,7 +104,7 @@ class TestTypes(unittest.TestCase):
types.register_type(WithWSProp) types.register_type(WithWSProp)
print WithWSProp._wsme_attributes print(WithWSProp._wsme_attributes)
assert len(WithWSProp._wsme_attributes) == 1 assert len(WithWSProp._wsme_attributes) == 1
a = WithWSProp._wsme_attributes[0] a = WithWSProp._wsme_attributes[0]
assert a.key == 'aint' assert a.key == 'aint'
@ -174,7 +177,8 @@ class TestTypes(unittest.TestCase):
try: try:
obj.a = 'v3' obj.a = 'v3'
assert False, 'ValueError was not raised' assert False, 'ValueError was not raised'
except ValueError, e: except ValueError:
e = sys.exc_info()[1]
assert str(e) == \ assert str(e) == \
"a: Value 'v3' is invalid (should be one of: v1, v2)", 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 assert len(AType._wsme_attributes) == 2
attrs = AType._wsme_attributes attrs = AType._wsme_attributes
print attrs print(attrs)
assert attrs[0].key == 'a_list', attrs[0].key assert attrs[0].key == 'a_list', attrs[0].key
assert attrs[0].name == 'a.list', attrs[0].name assert attrs[0].name == 'a.list', attrs[0].name

View File

@ -8,7 +8,7 @@ class TestUtils(unittest.TestCase):
def test_parse_isodate(self): def test_parse_isodate(self):
good_dates = [ good_dates = [
('2008-02-01', datetime.date(2008, 2, 1)), ('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 = [ ill_formatted_dates = [
'24-12-2004' '24-12-2004'

View File

@ -3,6 +3,8 @@ import datetime
import decimal import decimal
import inspect import inspect
import weakref import weakref
import six
import sys
class UserType(object): class UserType(object):
@ -68,9 +70,10 @@ class Enum(UserType):
def frombasetype(self, value): def frombasetype(self, value):
return value return value
pod_types = [str, unicode, int, float, bool] pod_types = six.integer_types + (
dt_types = [datetime.date, datetime.time, datetime.datetime] six.binary_type, six.text_type, float, bool)
extra_types = [binary, decimal.Decimal] dt_types = (datetime.date, datetime.time, datetime.datetime)
extra_types = (binary, decimal.Decimal)
native_types = pod_types + dt_types + extra_types native_types = pod_types + dt_types + extra_types
complex_types = [] complex_types = []
@ -79,8 +82,12 @@ dict_types = []
class UnsetType(object): class UnsetType(object):
def __nonzero__(self): if sys.version < '3':
return False def __nonzero__(self):
return False
else:
def __bool__(self):
return False
Unset = UnsetType() Unset = UnsetType()
@ -117,13 +124,12 @@ def validate_value(datatype, value):
raise ValueError("Wrong type. Expected '%s', got '%s'" % ( raise ValueError("Wrong type. Expected '%s', got '%s'" % (
datatype, type(value) datatype, type(value)
)) ))
key_type = datatype.keys()[0] key_type, value_type = list(datatype.items())[0]
value_type = datatype.values()[0]
for key, v in value.items(): for key, v in value.items():
validate_value(key_type, key) validate_value(key_type, key)
validate_value(value_type, v) validate_value(value_type, v)
elif datatype in (int, long): elif datatype in six.integer_types:
if not isinstance(value, int) and not isinstance(value, long): if not isinstance(value, six.integer_types):
raise ValueError( raise ValueError(
"Wrong type. Expected an integer, got '%s'" % ( "Wrong type. Expected an integer, got '%s'" % (
type(value) type(value)
@ -206,7 +212,8 @@ class wsattr(object):
def __set__(self, instance, value): def __set__(self, instance, value):
try: try:
validate_value(self.datatype, value) validate_value(self.datatype, value)
except ValueError, e: except ValueError:
e = sys.exc_info()[1]
raise ValueError("%s: %s" % (self.name, e)) raise ValueError("%s: %s" % (self.name, e))
if value is Unset: if value is Unset:
if hasattr(instance, '_' + self.key): if hasattr(instance, '_' + self.key):
@ -326,7 +333,7 @@ def register_type(class_):
if isinstance(class_, dict): if isinstance(class_, dict):
if len(class_) != 1: if len(class_) != 1:
raise ValueError("Cannot register type %s" % repr(class_)) 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: if key_type not in pod_types:
raise ValueError("Dictionnaries key can only be a pod type") raise ValueError("Dictionnaries key can only be a pod type")
register_type(value_type) register_type(value_type)