pep8 fixes, including a declaration in tox.ini for running flake8

Change-Id: I2adc6a5cbd76edd16e6079046b67b8fc10bf1671
This commit is contained in:
Ryan Petrello 2013-09-05 10:56:35 -04:00
parent 72c20e7ea1
commit f91767bf1e
26 changed files with 271 additions and 263 deletions

View File

@ -1,6 +1,6 @@
# content of: tox.ini , put in same dir as setup.py
[tox]
envlist = py26,py26-nolxml,py27,py27-nolxml,py32,py32-nolxml,pypy,sphinxext,tg11,tg15,pecan,flask,cornice,coverage,py33,py33-nolxml
envlist = py26,py26-nolxml,py27,py27-nolxml,py32,py32-nolxml,pypy,sphinxext,tg11,tg15,pecan,flask,cornice,coverage,py33,py33-nolxml,pep8
[common]
testtools=
@ -209,3 +209,7 @@ changedir=
commands=
make clean ziphtml
[testenv:pep8]
deps = flake8
commands = flake8 wsme wsmeext setup.py

View File

@ -1,5 +1,5 @@
[tox]
envlist = py26,py26-nolxml,py27,py27-nolxml,py32,py32-nolxml,pypy,sphinxext,tg11,tg15,pecan,flask,cornice,coverage,py33,py33-nolxml
envlist = py26,py26-nolxml,py27,py27-nolxml,py32,py32-nolxml,pypy,sphinxext,tg11,tg15,pecan,flask,cornice,coverage,py33,py33-nolxml,pep8
[common]
testtools =
@ -130,6 +130,10 @@ changedir =
commands =
make clean ziphtml
[testenv:pep8]
deps = flake8
commands = flake8 wsme wsmeext setup.py
[testenv:py26-sa5-lxml-json]
commands =
{envbindir}/coverage run {envbindir}/nosetests --nologcapture --with-xunit --xunit-file nosetests-{envname}.xml wsme/tests wsmeext/tests --verbose {posargs}

View File

@ -68,8 +68,10 @@ def from_params(datatype, params, path, hit_paths):
if objfound:
r = datatype()
for attrdef in list_attributes(datatype):
value = from_params(attrdef.datatype,
params, '%s.%s' % (path, attrdef.key), hit_paths)
value = from_params(
attrdef.datatype,
params, '%s.%s' % (path, attrdef.key), hit_paths
)
if value is not Unset:
setattr(r, attrdef.key, value)
return r

View File

@ -239,9 +239,8 @@ def encode_error(context, errordetail):
def encode_sample_value(datatype, value, format=False):
r = tojson(datatype, value)
content = json.dumps(r, ensure_ascii=False,
indent=4 if format else 0,
sort_keys=format)
content = json.dumps(r, ensure_ascii=False, indent=4 if format else 0,
sort_keys=format)
return ('javascript', content)
@ -249,9 +248,8 @@ def encode_sample_params(params, format=False):
kw = {}
for name, datatype, value in params:
kw[name] = tojson(datatype, value)
content = json.dumps(kw, ensure_ascii=False,
indent=4 if format else 0,
sort_keys=format)
content = json.dumps(kw, ensure_ascii=False, indent=4 if format else 0,
sort_keys=format)
return ('javascript', content)
@ -259,7 +257,6 @@ def encode_sample_result(datatype, value, format=False):
r = tojson(datatype, value)
#if self.nest_result:
#r = {'result': r}
content = json.dumps(r, ensure_ascii=False,
indent=4 if format else 0,
sort_keys=format)
content = json.dumps(r, ensure_ascii=False, indent=4 if format else 0,
sort_keys=format)
return ('javascript', content)

View File

@ -79,7 +79,7 @@ class WSRoot(object):
__registry__ = wsme.types.registry
def __init__(self, protocols=[], webpath='', transaction=None,
scan_api=scan_api):
scan_api=scan_api):
self._debug = True
self._webpath = webpath
self.protocols = []
@ -242,8 +242,8 @@ class WSRoot(object):
if protocol is None:
if msg is None:
msg = ("None of the following protocols can handle this "
"request : %s" % ','.join(
(p.name for p in self.protocols)))
"request : %s" % ','.join((
p.name for p in self.protocols)))
res.status = 500
res.content_type = 'text/plain'
res.text = u(msg)

View File

@ -35,7 +35,8 @@ class CallException(RuntimeError):
def __str__(self):
return 'faultcode=%s, faultstring=%s, debuginfo=%s' % (
self.faultcode, self.faultstring, self.debuginfo)
self.faultcode, self.faultstring, self.debuginfo
)
myenumtype = wsme.types.Enum(wsme.types.bytes, 'v1', 'v2')
@ -382,7 +383,7 @@ class ProtocolTestCase(unittest.TestCase):
e = sys.exc_info()[1]
self.assertEquals(e.faultcode, 'Client')
self.assertEquals(e.faultstring.lower(),
u('unknown function name: invalid_function'))
u('unknown function name: invalid_function'))
def test_serverside_error(self):
try:
@ -471,23 +472,21 @@ class ProtocolTestCase(unittest.TestCase):
def test_return_nesteddict(self):
r = self.call('returntypes/getnesteddict',
_rt={wsme.types.bytes: NestedOuter})
_rt={wsme.types.bytes: NestedOuter})
self.assertEquals(r, {
b('a'): {'inner': {'aint': 0}},
b('b'): {'inner': {'aint': 0}}
})
def test_return_objectarrayattribute(self):
r = self.call('returntypes/getobjectarrayattribute',
_rt=NestedOuter)
r = self.call('returntypes/getobjectarrayattribute', _rt=NestedOuter)
self.assertEquals(r, {
'inner': {'aint': 0},
'inner_array': [{'aint': 12}, {'aint': 13}]
})
def test_return_objectdictattribute(self):
r = self.call('returntypes/getobjectdictattribute',
_rt=NestedOuter)
r = self.call('returntypes/getobjectdictattribute', _rt=NestedOuter)
self.assertEquals(r, {
'inner': {'aint': 0},
'inner_dict': {
@ -506,15 +505,15 @@ class ProtocolTestCase(unittest.TestCase):
def test_setbytes(self):
assert self.call('argtypes/setbytes', value=b('astring'),
_rt=wsme.types.bytes) == b('astring')
_rt=wsme.types.bytes) == b('astring')
def test_settext(self):
assert self.call('argtypes/settext', value=u('\xe3\x81\xae'),
_rt=wsme.types.text) == u('\xe3\x81\xae')
_rt=wsme.types.text) == u('\xe3\x81\xae')
def test_settext_empty(self):
assert self.call('argtypes/settext', value=u(''),
_rt=wsme.types.text) == u('')
_rt=wsme.types.text) == u('')
def test_settext_none(self):
self.assertEquals(
@ -564,14 +563,14 @@ class ProtocolTestCase(unittest.TestCase):
def test_setbinary(self):
value = binarysample
r = self.call('argtypes/setbinary', value=(value, wsme.types.binary),
_rt=wsme.types.binary) == value
_rt=wsme.types.binary) == value
print(r)
def test_setnested(self):
value = {'inner': {'aint': 54}}
r = self.call('argtypes/setnested',
value=(value, NestedOuter),
_rt=NestedOuter)
value=(value, NestedOuter),
_rt=NestedOuter)
self.assertEquals(r, value)
def test_setnested_nullobj(self):
@ -586,15 +585,15 @@ class ProtocolTestCase(unittest.TestCase):
def test_setbytesarray(self):
value = [b("1"), b("2"), b("three")]
r = self.call('argtypes/setbytesarray',
value=(value, [wsme.types.bytes]),
_rt=[wsme.types.bytes])
value=(value, [wsme.types.bytes]),
_rt=[wsme.types.bytes])
self.assertEquals(r, value)
def test_settextarray(self):
value = [u("1")]
r = self.call('argtypes/settextarray',
value=(value, [wsme.types.text]),
_rt=[wsme.types.text])
value=(value, [wsme.types.text]),
_rt=[wsme.types.text])
self.assertEquals(r, value)
def test_setdatetimearray(self):
@ -603,8 +602,8 @@ class ProtocolTestCase(unittest.TestCase):
datetime.datetime(2008, 4, 6, 2, 12, 15),
]
r = self.call('argtypes/setdatetimearray',
value=(value, [datetime.datetime]),
_rt=[datetime.datetime])
value=(value, [datetime.datetime]),
_rt=[datetime.datetime])
self.assertEquals(r, value)
def test_setnestedarray(self):
@ -613,8 +612,8 @@ class ProtocolTestCase(unittest.TestCase):
{'inner': {'aint': 55}},
]
r = self.call('argtypes/setnestedarray',
value=(value, [NestedOuter]),
_rt=[NestedOuter])
value=(value, [NestedOuter]),
_rt=[NestedOuter])
self.assertEquals(r, value)
def test_setnesteddict(self):
@ -623,8 +622,8 @@ class ProtocolTestCase(unittest.TestCase):
b('o2'): {'inner': {'aint': 55}},
}
r = self.call('argtypes/setnesteddict',
value=(value, {six.binary_type: NestedOuter}),
_rt={six.binary_type: NestedOuter})
value=(value, {six.binary_type: NestedOuter}),
_rt={six.binary_type: NestedOuter})
print(r)
self.assertEquals(r, value)
@ -637,8 +636,8 @@ class ProtocolTestCase(unittest.TestCase):
def test_setnamedattrsobj(self):
value = {'attr.1': 10, 'attr.2': 20}
r = self.call('argtypes/setnamedattrsobj',
value=(value, NamedAttrsObject),
_rt=NamedAttrsObject)
value=(value, NamedAttrsObject),
_rt=NamedAttrsObject)
self.assertEquals(r, value)
def test_nested_api(self):
@ -661,5 +660,5 @@ class ProtocolTestCase(unittest.TestCase):
def test_html_format(self):
res = self.call('argtypes/setdatetime', _accept="text/html",
_no_result_decode=True)
_no_result_decode=True)
self.assertEquals(res.content_type, 'text/html')

View File

@ -1,6 +1,7 @@
# encoding=utf8
from wsme.exc import *
from wsme.exc import (ClientSideError, InvalidInput, MissingArgument,
UnknownArgument)
from six import u
@ -19,9 +20,10 @@ def test_unicode_clientside_error():
def test_invalidinput():
e = InvalidInput('field', 'badvalue', "error message")
assert e.faultstring == \
u("Invalid input for field/attribute field. Value: 'badvalue'. " \
"error message"), e.faultstring
assert e.faultstring == u(
"Invalid input for field/attribute field. Value: 'badvalue'. "
"error message"
), e.faultstring
def test_missingargument():

View File

@ -68,4 +68,3 @@ class TestProtocols(unittest.TestCase):
assert p.encode_sample_value(None, None) == ('none', 'N/A')
assert p.encode_sample_params(None) == ('none', 'N/A')
assert p.encode_sample_result(None, None) == ('none', 'N/A')

View File

@ -42,8 +42,12 @@ class TestProtocolsCommons(unittest.TestCase):
assert from_params(ArrayType(int), {}, 'a', set()) is Unset
def test_from_params_dict(self):
value = from_params(DictType(int, str), {
'a[2]': 'a2', 'a[3]': 'a3'}, 'a', set())
value = from_params(
DictType(int, str),
{'a[2]': 'a2', 'a[3]': 'a3'},
'a',
set()
)
assert value == {2: 'a2', 3: 'a3'}, value
def test_from_params_dict_unset(self):

View File

@ -143,8 +143,8 @@ wsme.tests.protocol.WSTestRoot.crud = MiniCrud()
class TestRestJson(wsme.tests.protocol.ProtocolTestCase):
protocol = 'restjson'
def call(self, fpath, _rt=None, _accept=None,
_no_result_decode=False, **kw):
def call(self, fpath, _rt=None, _accept=None, _no_result_decode=False,
**kw):
for key in kw:
if isinstance(kw[key], tuple):
value, datatype = kw[key]
@ -175,14 +175,15 @@ class TestRestJson(wsme.tests.protocol.ProtocolTestCase):
return r
else:
raise wsme.tests.protocol.CallException(
r['faultcode'],
r['faultstring'],
r.get('debuginfo'))
r['faultcode'],
r['faultstring'],
r.get('debuginfo')
)
return json.loads(res.text)
def test_fromjson(self):
assert fromjson(str, None) == None
assert fromjson(str, None) is None
def test_keyargs(self):
r = self.app.get('/argtypes/setint.json?value=2')
@ -202,8 +203,11 @@ class TestRestJson(wsme.tests.protocol.ProtocolTestCase):
'value[1].inner.aint': 55
}
body = urlencode(params)
r = self.app.post('/argtypes/setnestedarray.json', body,
headers={'Content-Type': 'application/x-www-form-urlencoded'})
r = self.app.post(
'/argtypes/setnestedarray.json',
body,
headers={'Content-Type': 'application/x-www-form-urlencoded'}
)
print(r)
assert json.loads(r.text) == [
@ -211,10 +215,9 @@ class TestRestJson(wsme.tests.protocol.ProtocolTestCase):
{'inner': {'aint': 55}}]
def test_body_and_params(self):
r = self.app.post('/argtypes/setint.json?value=2',
'{"value": 2}',
headers={"Content-Type": "application/json"},
expect_errors=True)
r = self.app.post('/argtypes/setint.json?value=2', '{"value": 2}',
headers={"Content-Type": "application/json"},
expect_errors=True)
print(r)
assert r.status_int == 400
assert json.loads(r.text)['faultstring'] == \
@ -233,21 +236,21 @@ class TestRestJson(wsme.tests.protocol.ProtocolTestCase):
assert json.loads(r.text) == 2
def test_unknown_arg(self):
r = self.app.post('/returntypes/getint.json',
'{"a": 2}',
headers={"Content-Type": "application/json"},
expect_errors=True)
r = self.app.post('/returntypes/getint.json', '{"a": 2}',
headers={"Content-Type": "application/json"},
expect_errors=True)
print(r)
assert r.status_int == 400
assert json.loads(r.text)['faultstring'].startswith(
"Unknown argument:")
"Unknown argument:"
)
r = self.app.get('/returntypes/getint.json?a=2',
expect_errors=True)
r = self.app.get('/returntypes/getint.json?a=2', expect_errors=True)
print(r)
assert r.status_int == 400
assert json.loads(r.text)['faultstring'].startswith(
"Unknown argument:")
"Unknown argument:"
)
def test_unset_attrs(self):
class AType(object):
@ -269,14 +272,12 @@ class TestRestJson(wsme.tests.protocol.ProtocolTestCase):
def test_None_tojson(self):
for dt in (datetime.date, datetime.time, datetime.datetime,
decimal.Decimal):
decimal.Decimal):
assert tojson(dt, None) is None
def test_None_fromjson(self):
for dt in (str, int,
datetime.date, datetime.time, datetime.datetime,
decimal.Decimal,
[int], {int: int}):
for dt in (str, int, datetime.date, datetime.time, datetime.datetime,
decimal.Decimal, [int], {int: int}):
assert fromjson(dt, None) is None
def test_nest_result(self):
@ -299,8 +300,8 @@ class TestRestJson(wsme.tests.protocol.ProtocolTestCase):
r = wsme.rest.json.encode_sample_value(MyType, v, True)
print(r)
assert r[0] == ('javascript')
assert r[1] == json.dumps({'aint': 4, 'astr': 's'},
ensure_ascii=False, indent=4, sort_keys=True)
assert r[1] == json.dumps({'aint': 4, 'astr': 's'}, ensure_ascii=False,
indent=4, sort_keys=True)
def test_bytes_tojson(self):
assert tojson(wsme.types.bytes, None) is None

View File

@ -40,7 +40,7 @@ def dumpxml(key, obj, datatype=None):
el.text = six.text_type(obj)
elif type(obj) in (datetime.date, datetime.time, datetime.datetime):
el.text = obj.isoformat()
elif type(obj) == type(None):
elif isinstance(obj, type(None)):
el.set('nil', 'true')
elif hasattr(datatype, '_wsme_attributes'):
for attr in datatype._wsme_attributes:
@ -120,8 +120,8 @@ def loadxml(el, datatype):
class TestRestXML(wsme.tests.protocol.ProtocolTestCase):
protocol = 'restxml'
def call(self, fpath, _rt=None, _accept=None,
_no_result_decode=False, **kw):
def call(self, fpath, _rt=None, _accept=None, _no_result_decode=False,
**kw):
el = dumpxml('parameters', kw)
content = et.tostring(el)
headers = {
@ -142,10 +142,11 @@ class TestRestXML(wsme.tests.protocol.ProtocolTestCase):
el = et.fromstring(res.body)
if el.tag == 'error':
raise wsme.tests.protocol.CallException(
el.find('faultcode').text,
el.find('faultstring').text,
el.find('debuginfo') is not None and
el.find('debuginfo').text or None)
el.find('faultcode').text,
el.find('faultstring').text,
el.find('debuginfo') is not None and
el.find('debuginfo').text or None
)
else:
return loadxml(et.fromstring(res.body), _rt)

View File

@ -47,7 +47,7 @@ class TestTypes(unittest.TestCase):
assert attrs[0].name == 'aint'
assert isinstance(attrs[0], types.wsattr)
assert attrs[0].datatype == int
assert attrs[0].mandatory == False
assert attrs[0].mandatory is False
assert attrs[1].key == 'abytes'
assert attrs[1].name == 'abytes'
assert attrs[2].key == 'atext'
@ -322,9 +322,9 @@ class TestTypes(unittest.TestCase):
def test_register_invalid_dict(self):
self.assertRaises(ValueError, types.register_type, {})
self.assertRaises(ValueError, types.register_type,
{int: str, str: int})
{int: str, str: int})
self.assertRaises(ValueError, types.register_type,
{types.Unset: str})
{types.Unset: str})
def test_list_attribute_no_auto_register(self):
class MyType(object):
@ -454,6 +454,7 @@ class TestTypes(unittest.TestCase):
class buffer:
def read(self):
return 'from-file'
class fieldstorage:
filename = 'static.json'
file = buffer()
@ -465,6 +466,7 @@ class TestTypes(unittest.TestCase):
class buffer:
def read(self):
return 'from-file'
class fieldstorage:
filename = 'static.json'
file = None

View File

@ -87,7 +87,8 @@ def parse_isodatetime(value):
try:
from collections import OrderedDict
except ImportError:
# Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy.
# Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7
# and pypy.
# Passes Python2.7's test suite and incorporates all the latest updates.
try:
@ -103,14 +104,17 @@ except ImportError:
class OrderedDict(dict):
'Dictionary that remembers insertion order'
# An inherited dict maps keys to values.
# The inherited dict provides __getitem__, __len__, __contains__, and get.
# The remaining methods are order-aware.
# Big-O running times for all methods are the same as for regular dictionaries.
# The inherited dict provides __getitem__, __len__, __contains__, and
# get. The remaining methods are order-aware.
#
# Big-O running times for all methods are the same as for regular
# dictionaries.
# The internal self.__map dictionary maps keys to links in a doubly linked list.
# The circular doubly linked list starts and ends with a sentinel element.
# The sentinel element never gets deleted (this simplifies the algorithm).
# Each link is stored as a list of length three: [PREV, NEXT, KEY].
# The internal self.__map dictionary maps keys to links in a doubly
# linked list. The circular doubly linked list starts and ends with
# a sentinel element. The sentinel element never gets deleted (this
# simplifies the algorithm). Each link is stored as a list of length
# three: [PREV, NEXT, KEY].
def __init__(self, *args, **kwds):
'''Initialize an ordered dictionary. Signature is the same as for
@ -119,7 +123,9 @@ except ImportError:
'''
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
raise TypeError(
'expected at most 1 arguments, got %d' % len(args)
)
try:
self.__root
except AttributeError:
@ -130,8 +136,9 @@ except ImportError:
def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
'od.__setitem__(i, y) <==> od[i]=y'
# Setting a new item creates a new link which goes at the end of the linked
# list, and the inherited dictionary is updated with the new key/value pair.
# Setting a new item creates a new link which goes at the end of
# the linked list, and the inherited dictionary is updated with the
# new key/value pair.
if key not in self:
root = self.__root
last = root[0]
@ -140,8 +147,9 @@ except ImportError:
def __delitem__(self, key, dict_delitem=dict.__delitem__):
'od.__delitem__(y) <==> del od[y]'
# Deleting an existing item uses self.__map to find the link which is
# then removed by updating the links in the predecessor and successor nodes.
# Deleting an existing item uses self.__map to find the link which
# is then removed by updating the links in the predecessor and
# successor nodes.
dict_delitem(self, key)
link_prev, link_next, key = self.__map.pop(key)
link_prev[1] = link_next
@ -177,7 +185,8 @@ except ImportError:
def popitem(self, last=True):
'''od.popitem() -> (k, v), return and remove a (key, value) pair.
Pairs are returned in LIFO order if last is true or FIFO order if false.
Pairs are returned in LIFO order if last is true or FIFO order if
false.
'''
if not self:
@ -227,12 +236,12 @@ except ImportError:
yield (k, self[k])
def update(*args, **kwds):
'''od.update(E, **F) -> None. Update od from dict/iterable E and F.
'''od.update(E, **F) -> None. Update od from dict/iterable E and F
If E is a dict instance, does: for k in E: od[k] = E[k]
If E has a .keys() method, does: for k in E.keys(): od[k] = E[k]
If E has a .keys() method, does: for k in E.keys(): od[k] = E[k] # noqa
Or if E is an iterable of items, does: for k, v in E: od[k] = v
In either case, this is followed by: for k, v in F.items(): od[k] = v
In either case, this is followed by: for k, v in F.items(): od[k] = v # noqa
'''
if len(args) > 2:
@ -257,14 +266,15 @@ except ImportError:
for key, value in kwds.items():
self[key] = value
__update = update # let subclasses override update without breaking __init__
# let subclasses override update without breaking __init__
__update = update
__marker = object()
def pop(self, key, default=__marker):
'''od.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised.
'''od.pop(k[,d]) -> v, remove specified key and return the
corresponding value. If key is not found, d is returned if given,
otherwise KeyError is raised.
'''
if key in self:
result = self[key]
@ -275,7 +285,8 @@ except ImportError:
return default
def setdefault(self, key, default=None):
'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
'''od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not
in od'''
if key in self:
return self[key]
self[key] = default
@ -320,12 +331,15 @@ except ImportError:
return d
def __eq__(self, other):
'''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
while comparison to a regular mapping is order-insensitive.
'''od.__eq__(y) <==> od==y. Comparison to another OD is
order-sensitive while comparison to a regular mapping is
order-insensitive.
'''
if isinstance(other, OrderedDict):
return len(self)==len(other) and self.items() == other.items()
return (
len(self) == len(other) and
self.items() == other.items()
)
return dict.__eq__(self, other)
def __ne__(self, other):
@ -342,5 +356,6 @@ except ImportError:
return ValuesView(self)
def viewitems(self):
"od.viewitems() -> a set-like object providing a view on od's items"
"""od.viewitems() -> a set-like object providing a view on od's
items"""
return ItemsView(self)

View File

@ -1 +1 @@
from wsmeext.extdirect.protocol import ExtDirectProtocol
from wsmeext.extdirect.protocol import ExtDirectProtocol # noqa

View File

@ -60,8 +60,7 @@ class DataStoreControllerMixin(object):
def create(self, obj):
pass
def read(self, query=None, sort=None,
page=None, start=None, limit=None):
def read(self, query=None, sort=None, page=None, start=None, limit=None):
pass
def update(self, obj):
@ -116,5 +115,7 @@ Ext.define('%(appns)s.store.%(classname)s', {
return tpl % d
DataStoreController = DataStoreControllerMeta('DataStoreController',
(DataStoreControllerMixin,), {})
DataStoreController = DataStoreControllerMeta(
'DataStoreController',
(DataStoreControllerMixin,), {}
)

View File

@ -269,8 +269,7 @@ class ExtDirectProtocol(Protocol):
displayname = 'ExtDirect'
content_types = ['application/json', 'text/javascript']
def __init__(self, namespace='', params_notation='named',
nsfolder=None):
def __init__(self, namespace='', params_notation='named', nsfolder=None):
self.namespace = namespace
self.appns, self.apins = namespace.rsplit('.', 2) \
if '.' in namespace else (namespace, '')
@ -290,9 +289,11 @@ class ExtDirectProtocol(Protocol):
assert path.startswith(self.root._webpath)
path = path[len(self.root._webpath):]
return path == self.api_alias or \
path == "/extdirect/api" or \
path.startswith("/extdirect/router")
return (
path == self.api_alias or
path == "/extdirect/api" or
path.startswith("/extdirect/router")
)
def iter_calls(self, req):
path = req.path
@ -333,12 +334,14 @@ class ExtDirectProtocol(Protocol):
def read_std_arguments(self, context):
funcdef = context.funcdef
notation = funcdef.extra_options.get(
'extdirect_params_notation', self.default_params_notation)
notation = funcdef.extra_options.get('extdirect_params_notation',
self.default_params_notation)
args = context.params
if notation == 'positional':
kw = dict((argdef.name, fromjson(argdef.datatype, arg))
for argdef, arg in zip(funcdef.arguments, args))
kw = dict(
(argdef.name, fromjson(argdef.datatype, arg))
for argdef, arg in zip(funcdef.arguments, args)
)
elif notation == 'named':
if len(args) == 0:
args = [{}]
@ -357,8 +360,8 @@ class ExtDirectProtocol(Protocol):
def read_form_arguments(self, context):
kw = {}
for argdef in context.funcdef.arguments:
value = from_params(argdef.datatype,
context.request.params, argdef.name, set())
value = from_params(argdef.datatype, context.request.params,
argdef.name, set())
if value is not Unset:
kw[argdef.name] = value
return kw
@ -421,14 +424,14 @@ class ExtDirectProtocol(Protocol):
if action not in namespaces[namespace]:
namespaces[namespace][action] = []
notation = funcdef.extra_options.get('extdirect_params_notation',
self.default_params_notation)
self.default_params_notation)
method = {
'name': funcdef.name}
if funcdef.extra_options.get('extdirect_formhandler', False):
method['formHandler'] = True
method['len'] = 1 if notation == 'named' \
else len(funcdef.arguments)
else len(funcdef.arguments)
namespaces[namespace][action].append(method)
webpath = self.root._webpath
if webpath and not webpath.endswith('/'):
@ -442,7 +445,6 @@ class ExtDirectProtocol(Protocol):
def encode_sample_value(self, datatype, value, format=False):
r = tojson(datatype, value)
content = json.dumps(r, ensure_ascii=False,
indent=4 if format else 0,
sort_keys=format)
content = json.dumps(r, ensure_ascii=False, indent=4 if format else 0,
sort_keys=format)
return ('javascript', content)

View File

@ -5,8 +5,7 @@ class SADataStoreController(datastore.DataStoreController):
__dbsession__ = None
__datatype__ = None
def read(self, query=None, sort=None,
page=None, start=None, limit=None):
def read(self, query=None, sort=None, page=None, start=None, limit=None):
q = self.__dbsession__.query(self.__datatype__.__saclass__)
total = q.count()
if start is not None and limit is not None:

View File

@ -125,9 +125,8 @@ class SoapEncoder(object):
el.set(type_qn, xsitype)
el.text = value
elif wsme.types.isusertype(datatype):
return self.tosoap(
datatype.basetype, tag,
datatype.tobasetype(value))
return self.tosoap(datatype.basetype, tag,
datatype.tobasetype(value))
elif wsme.types.iscomplex(datatype):
el.set(type_qn, 'types:%s' % (datatype.__name__))
for attrdef in wsme.types.list_attributes(datatype):
@ -182,8 +181,11 @@ class SoapEncoder(object):
@tosoap.when_object(bool)
def bool_tosoap(self, datatype, tag, value):
return self.make_soap_element(datatype, tag,
'true' if value is True else 'false' if value is False else None)
return self.make_soap_element(
datatype,
tag,
'true' if value is True else 'false' if value is False else None
)
@tosoap.when_object(wsme.types.bytes)
def bytes_tosoap(self, datatype, tag, value):
@ -194,8 +196,11 @@ class SoapEncoder(object):
@tosoap.when_object(datetime.datetime)
def datetime_tosoap(self, datatype, tag, value):
return self.make_soap_element(datatype, tag,
value is not None and value.isoformat() or None)
return self.make_soap_element(
datatype,
tag,
value is not None and value.isoformat() or None
)
@tosoap.when_object(wsme.types.binary)
def binary_tosoap(self, datatype, tag, value):
@ -326,10 +331,8 @@ class SoapProtocol(Protocol):
"soapenc": "http://schemas.xmlsoap.org/soap/encoding/",
}
def __init__(self, tns=None,
typenamespace=None,
baseURL=None,
servicename='MyApp'):
def __init__(self, tns=None, typenamespace=None, baseURL=None,
servicename='MyApp'):
self.tns = tns
self.typenamespace = typenamespace
self.servicename = servicename
@ -343,7 +346,8 @@ class SoapProtocol(Protocol):
self._name_mapping[service] = dict(
(soap_fname(path, f), path)
for path, f in self.root.getapi()
if service is None or (path and path[0] == service))
if service is None or (path and path[0] == service)
)
return self._name_mapping[service]
def accept(self, req):

View File

@ -8,6 +8,7 @@ except ImportError:
classtypes = type
InstanceType = None
def generic(func, argpos=None):
"""Create a simple generic function"""
@ -25,7 +26,7 @@ def generic(func, argpos=None):
def _by_class(*args, **kw):
cls = args[argpos].__class__
for t in type(cls.__name__, (cls,object), {}).__mro__:
for t in type(cls.__name__, (cls, object), {}).__mro__:
f = _gbt(t, _sentinel)
if f is not _sentinel:
return f(*args, **kw)
@ -42,9 +43,10 @@ def generic(func, argpos=None):
raise TypeError(
"%r is not a type or class" % (t,)
)
def decorate(f):
for t in types:
if _by_type.setdefault(t,f) is not f:
if _by_type.setdefault(t, f) is not f:
raise TypeError(
"%r already has method for type %r" % (func, t)
)
@ -58,14 +60,13 @@ def generic(func, argpos=None):
"""Decorator to add a method to be called for the given object(s)"""
def decorate(f):
for o in obs:
if _by_object.setdefault(id(o), (o,f))[1] is not f:
if _by_object.setdefault(id(o), (o, f))[1] is not f:
raise TypeError(
"%r already has method for object %r" % (func, o)
)
return f
return decorate
def dispatch(*args, **kw):
f = _gbo(id(args[argpos]), _sentinel)
if f is _sentinel:
@ -78,59 +79,29 @@ def generic(func, argpos=None):
else:
return f[1](*args, **kw)
dispatch.__name__ = func.__name__
dispatch.__dict__ = func.__dict__.copy()
dispatch.__doc__ = func.__doc__
dispatch.__module__ = func.__module__
dispatch.__name__ = func.__name__
dispatch.__dict__ = func.__dict__.copy()
dispatch.__doc__ = func.__doc__
dispatch.__module__ = func.__module__
dispatch.when_type = when_type
dispatch.when_object = when_object
dispatch.default = func
dispatch.has_object = lambda o: id(o) in _by_object
dispatch.has_type = lambda t: t in _by_type
dispatch.has_type = lambda t: t in _by_type
dispatch.argpos = argpos
return dispatch
def test_suite():
import doctest
return doctest.DocFileSuite(
'README.txt',
optionflags=doctest.ELLIPSIS|doctest.REPORT_ONLY_FIRST_FAILURE,
optionflags=doctest.ELLIPSIS | doctest.REPORT_ONLY_FIRST_FAILURE,
)
if __name__=='__main__':
if __name__ == '__main__':
import unittest
r = unittest.TextTestRunner()
r.run(test_suite())

View File

@ -158,7 +158,7 @@ class TypeDirective(PyClasslike):
class AttributeDirective(PyClassmember):
doc_field_types = [
Field('datatype', label=l_('Type'), has_arg=False,
names=('type', 'datatype'))
names=('type', 'datatype'))
]
@ -429,8 +429,11 @@ def document_function(funcdef, docstrings=None, protocols=['restjson']):
if protocols:
params = []
for arg in funcdef.arguments:
params.append((arg.name, arg.datatype,
make_sample_object(arg.datatype)))
params.append((
arg.name,
arg.datatype,
make_sample_object(arg.datatype)
))
codesamples.extend([
u':%s:' % l_(u'Parameters samples'),
u' .. cssclass:: toggle',
@ -494,8 +497,10 @@ class FunctionDocumenter(autodoc.MethodDocumenter):
def format_args(self):
args = [arg.name for arg in self.wsme_fd.arguments]
defaults = [arg.default
for arg in self.wsme_fd.arguments if not arg.mandatory]
defaults = [
arg.default
for arg in self.wsme_fd.arguments if not arg.mandatory
]
return inspect.formatargspec(args, defaults=defaults)
def get_doc(self, encoding=None):

View File

@ -92,4 +92,5 @@ class CRUDControllerBase(object):
return None
CRUDController = CRUDControllerMeta(
'CRUDController', (CRUDControllerBase,), {})
'CRUDController', (CRUDControllerBase,), {}
)

View File

@ -72,8 +72,7 @@ def make_wsattr(registry, saproperty):
saproperty.columns[0].type)
elif isinstance(saproperty, RelationProperty):
other_saclass = saproperty.mapper.class_
datatype = SQLAlchemyRegistry.get(registry).getdatatype(
other_saclass)
datatype = SQLAlchemyRegistry.get(registry).getdatatype(other_saclass)
if saproperty.uselist:
datatype = [datatype]
else:

View File

@ -98,8 +98,8 @@ class TestExtDirectProtocol(wsme.tests.protocol.ProtocolTestCase):
'nsfolder': 'app'
}
def call(self, fname, _rt=None, _no_result_decode=False,
_accept=None, **kw):
def call(self, fname, _rt=None, _no_result_decode=False, _accept=None,
**kw):
path = fname.split('/')
try:
func, funcdef, args = self.root._lookup_function(path)
@ -132,8 +132,8 @@ class TestExtDirectProtocol(wsme.tests.protocol.ProtocolTestCase):
headers = {'Content-Type': 'application/json'}
if _accept:
headers['Accept'] = _accept
res = self.app.post('/extdirect/router/%s' % ns, data,
headers=headers, expect_errors=True)
res = self.app.post('/extdirect/router/%s' % ns, data, headers=headers,
expect_errors=True)
print(res.body)
@ -170,8 +170,7 @@ class TestExtDirectProtocol(wsme.tests.protocol.ProtocolTestCase):
'data': [2, 5],
})
headers = {'Content-Type': 'application/json'}
res = self.app.post('/extdirect/router', data,
headers=headers)
res = self.app.post('/extdirect/router', data, headers=headers)
print(res.body)
@ -220,8 +219,11 @@ class TestExtDirectProtocol(wsme.tests.protocol.ProtocolTestCase):
}
body = urlencode(params)
r = self.app.post('/extdirect/router', body,
headers={'Content-Type': 'application/x-www-form-urlencoded'})
r = self.app.post(
'/extdirect/router',
body,
headers={'Content-Type': 'application/x-www-form-urlencoded'}
)
print (r)
assert json.loads(r.text) == {

View File

@ -114,9 +114,7 @@ soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
</soap:Body>
</soap:Envelope>
""" % dict(method=method,
params=params,
typenamespace=typenamespace)
""" % dict(method=method, params=params, typenamespace=typenamespace)
return message
@ -124,11 +122,15 @@ python_types = {
int: ('xs:int', str),
float: ('xs:float', str),
bool: ('xs:boolean', str),
wsme.types.bytes: ('xs:string',
lambda x: x.decode('ascii') if isinstance(x, wsme.types.bytes) else x),
wsme.types.bytes: (
'xs:string',
lambda x: x.decode('ascii') if isinstance(x, wsme.types.bytes) else x
),
wsme.types.text: ('xs:string', wsme.types.text),
wsme.types.binary: ('xs:base64Binary',
lambda x: base64.encodestring(x).decode('ascii')),
wsme.types.binary: (
'xs:base64Binary',
lambda x: base64.encodestring(x).decode('ascii')
),
decimal.Decimal: ('xs:decimal', str),
datetime.date: ('xs:date', datetime.date.isoformat),
datetime.time: ('xs:time', datetime.time.isoformat),
@ -278,9 +280,7 @@ def fromsuds(dt, value):
class TestSOAP(wsme.tests.protocol.ProtocolTestCase):
protocol = 'soap'
protocol_options = dict(
tns=tns,
typenamespace=typenamespace)
protocol_options = dict(tns=tns, typenamespace=typenamespace)
ws_path = '/'
_sudsclient = None
@ -290,19 +290,22 @@ class TestSOAP(wsme.tests.protocol.ProtocolTestCase):
def test_simple_call(self):
message = build_soap_message('touch')
print(message)
res = self.app.post(self.ws_path, message,
res = self.app.post(
self.ws_path,
message,
headers={"Content-Type": "application/soap+xml; charset=utf-8"},
expect_errors=True)
expect_errors=True
)
print(res.body)
assert res.status.startswith('200')
def call(self, fpath, _rt=None, _accept=None,
_no_result_decode=False, **kw):
def call(self, fpath, _rt=None, _accept=None, _no_result_decode=False,
**kw):
if _no_result_decode or _accept or self._testMethodName in (
'test_missing_argument', 'test_invalid_path',
'test_settext_empty', 'test_settext_none'
):
'test_missing_argument', 'test_invalid_path', 'test_settext_empty',
'test_settext_none'
):
return self.raw_call(fpath, _rt, _accept, _no_result_decode, **kw)
path = fpath.strip('/').split('/')
@ -318,13 +321,13 @@ class TestSOAP(wsme.tests.protocol.ProtocolTestCase):
except suds.WebFault:
exc = sys.exc_info()[1]
raise wsme.tests.protocol.CallException(
exc.fault.faultcode,
exc.fault.faultstring,
getattr(exc.fault, 'detail', None) or None
exc.fault.faultcode,
exc.fault.faultstring,
getattr(exc.fault, 'detail', None) or None
)
def raw_call(self, fpath, _rt=None, _accept=None,
_no_result_decode=False, **kw):
def raw_call(self, fpath, _rt=None, _accept=None, _no_result_decode=False,
**kw):
path = fpath.strip('/').split('/')
methodname = ''.join([path[0]] + [i.capitalize() for i in path[1:]])
# get the actual definition so we can build the adequate request
@ -366,17 +369,17 @@ class TestSOAP(wsme.tests.protocol.ProtocolTestCase):
elif res.status_int == 400:
fault = body.find(fault_qn)
raise wsme.tests.protocol.CallException(
fault.find(faultcode_qn).text,
fault.find(faultstring_qn).text,
"")
fault.find(faultcode_qn).text,
fault.find(faultstring_qn).text,
"")
elif res.status_int == 500:
fault = body.find(fault_qn)
raise wsme.tests.protocol.CallException(
fault.find(faultcode_qn).text,
fault.find(faultstring_qn).text,
fault.find(faultdetail_qn) is not None and
fault.find(faultdetail_qn).text or None)
fault.find(faultcode_qn).text,
fault.find(faultstring_qn).text,
fault.find(faultdetail_qn) is not None and
fault.find(faultdetail_qn).text or None)
@property
def sudsclient(self):

View File

@ -23,9 +23,8 @@ from wsmeext.sqlalchemy.controllers import CRUDController
from six import u
engine = create_engine('sqlite:///')
DBSession = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
DBSession = scoped_session(sessionmaker(autocommit=False, autoflush=False,
bind=engine))
DBBase = declarative_base()
registry = wsme.types.Registry()
@ -55,8 +54,8 @@ class DBAddress(DBBase):
globals().update(
generate_types(DBPerson, DBAddress,
makename=lambda s: s[2:], registry=registry))
generate_types(DBPerson, DBAddress, makename=lambda s: s[2:],
registry=registry))
class PersonController(CRUDController):
@ -97,9 +96,7 @@ class TestCRUDController():
birthdate=u('1809-01-15')
))
r = self.app.post('/person/create', json.dumps(data),
headers={
'Content-Type': 'application/json'
})
headers={'Content-Type': 'application/json'})
r = json.loads(r.text)
print(r)
assert r['name'] == u('Pierre-Joseph')
@ -111,9 +108,7 @@ class TestCRUDController():
birthdate=u('1809-01-15')
))
r = self.app.put('/person', json.dumps(data),
headers={
'Content-Type': 'application/json'
})
headers={'Content-Type': 'application/json'})
r = json.loads(r.text)
print(r)
assert r['name'] == u('Pierre-Joseph')
@ -127,9 +122,7 @@ class TestCRUDController():
DBSession.flush()
pid = p.id
r = self.app.post('/person/read', '{"ref": {"id": %s}}' % pid,
headers={
'Content-Type': 'application/json'
})
headers={'Content-Type': 'application/json'})
r = json.loads(r.text)
print(r)
assert r['name'] == u('Pierre-Joseph')
@ -143,9 +136,7 @@ class TestCRUDController():
DBSession.flush()
pid = p.id
r = self.app.get('/person?ref.id=%s' % pid,
headers={
'Content-Type': 'application/json'
})
headers={'Content-Type': 'application/json'})
r = json.loads(r.text)
print(r)
assert r['name'] == u('Pierre-Joseph')
@ -163,9 +154,7 @@ class TestCRUDController():
"name": u('Pierre-Joseph Proudon')
}
r = self.app.post('/person/update', json.dumps(dict(data=data)),
headers={
'Content-Type': 'application/json'
})
headers={'Content-Type': 'application/json'})
r = json.loads(r.text)
print(r)
assert r['name'] == u('Pierre-Joseph Proudon')
@ -183,9 +172,7 @@ class TestCRUDController():
"name": u('Pierre-Joseph Proudon')
}
r = self.app.post('/person', json.dumps(dict(data=data)),
headers={
'Content-Type': 'application/json'
})
headers={'Content-Type': 'application/json'})
r = json.loads(r.text)
print(r)
assert r['name'] == u('Pierre-Joseph Proudon')
@ -214,9 +201,7 @@ class TestCRUDController():
DBSession.flush()
pid = p.id
r = self.app.delete('/person?ref.id=%s' % pid,
headers={
'Content-Type': 'application/json'
})
headers={'Content-Type': 'application/json'})
print(r)
assert DBSession.query(DBPerson).get(pid) is None

View File

@ -9,8 +9,14 @@ class TestUtils():
def test_validator_with_invalid_int_code(self):
invalid_int_code = 648
assert not is_valid_code(invalid_int_code), "Invalid status code not detected"
assert (
not is_valid_code(invalid_int_code),
"Invalid status code not detected"
)
def test_validator_with_invalid_str_code(self):
invalid_str_code = '404'
assert not is_valid_code(invalid_str_code), "Invalid status code not detected"
assert (
not is_valid_code(invalid_str_code),
"Invalid status code not detected"
)