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 # content of: tox.ini , put in same dir as setup.py
[tox] [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] [common]
testtools= testtools=
@ -209,3 +209,7 @@ changedir=
commands= commands=
make clean ziphtml make clean ziphtml
[testenv:pep8]
deps = flake8
commands = flake8 wsme wsmeext setup.py

View File

@ -1,5 +1,5 @@
[tox] [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] [common]
testtools = testtools =
@ -130,6 +130,10 @@ changedir =
commands = commands =
make clean ziphtml make clean ziphtml
[testenv:pep8]
deps = flake8
commands = flake8 wsme wsmeext setup.py
[testenv:py26-sa5-lxml-json] [testenv:py26-sa5-lxml-json]
commands = commands =
{envbindir}/coverage run {envbindir}/nosetests --nologcapture --with-xunit --xunit-file nosetests-{envname}.xml wsme/tests wsmeext/tests --verbose {posargs} {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: if objfound:
r = datatype() r = datatype()
for attrdef in list_attributes(datatype): for attrdef in list_attributes(datatype):
value = from_params(attrdef.datatype, value = from_params(
params, '%s.%s' % (path, attrdef.key), hit_paths) attrdef.datatype,
params, '%s.%s' % (path, attrdef.key), hit_paths
)
if value is not Unset: if value is not Unset:
setattr(r, attrdef.key, value) setattr(r, attrdef.key, value)
return r return r

View File

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

View File

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

View File

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

View File

@ -1,6 +1,7 @@
# encoding=utf8 # encoding=utf8
from wsme.exc import * from wsme.exc import (ClientSideError, InvalidInput, MissingArgument,
UnknownArgument)
from six import u from six import u
@ -19,9 +20,10 @@ def test_unicode_clientside_error():
def test_invalidinput(): def test_invalidinput():
e = InvalidInput('field', 'badvalue', "error message") e = InvalidInput('field', 'badvalue', "error message")
assert e.faultstring == \ assert e.faultstring == u(
u("Invalid input for field/attribute field. Value: 'badvalue'. " \ "Invalid input for field/attribute field. Value: 'badvalue'. "
"error message"), e.faultstring "error message"
), e.faultstring
def test_missingargument(): 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_value(None, None) == ('none', 'N/A')
assert p.encode_sample_params(None) == ('none', 'N/A') assert p.encode_sample_params(None) == ('none', 'N/A')
assert p.encode_sample_result(None, 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 assert from_params(ArrayType(int), {}, 'a', set()) is Unset
def test_from_params_dict(self): def test_from_params_dict(self):
value = from_params(DictType(int, str), { value = from_params(
'a[2]': 'a2', 'a[3]': 'a3'}, 'a', set()) DictType(int, str),
{'a[2]': 'a2', 'a[3]': 'a3'},
'a',
set()
)
assert value == {2: 'a2', 3: 'a3'}, value assert value == {2: 'a2', 3: 'a3'}, value
def test_from_params_dict_unset(self): 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): class TestRestJson(wsme.tests.protocol.ProtocolTestCase):
protocol = 'restjson' protocol = 'restjson'
def call(self, fpath, _rt=None, _accept=None, def call(self, fpath, _rt=None, _accept=None, _no_result_decode=False,
_no_result_decode=False, **kw): **kw):
for key in kw: for key in kw:
if isinstance(kw[key], tuple): if isinstance(kw[key], tuple):
value, datatype = kw[key] value, datatype = kw[key]
@ -175,14 +175,15 @@ class TestRestJson(wsme.tests.protocol.ProtocolTestCase):
return r return r
else: else:
raise wsme.tests.protocol.CallException( raise wsme.tests.protocol.CallException(
r['faultcode'], r['faultcode'],
r['faultstring'], r['faultstring'],
r.get('debuginfo')) r.get('debuginfo')
)
return json.loads(res.text) return json.loads(res.text)
def test_fromjson(self): def test_fromjson(self):
assert fromjson(str, None) == None assert fromjson(str, None) is None
def test_keyargs(self): def test_keyargs(self):
r = self.app.get('/argtypes/setint.json?value=2') r = self.app.get('/argtypes/setint.json?value=2')
@ -202,8 +203,11 @@ class TestRestJson(wsme.tests.protocol.ProtocolTestCase):
'value[1].inner.aint': 55 'value[1].inner.aint': 55
} }
body = urlencode(params) body = urlencode(params)
r = self.app.post('/argtypes/setnestedarray.json', body, r = self.app.post(
headers={'Content-Type': 'application/x-www-form-urlencoded'}) '/argtypes/setnestedarray.json',
body,
headers={'Content-Type': 'application/x-www-form-urlencoded'}
)
print(r) print(r)
assert json.loads(r.text) == [ assert json.loads(r.text) == [
@ -211,10 +215,9 @@ class TestRestJson(wsme.tests.protocol.ProtocolTestCase):
{'inner': {'aint': 55}}] {'inner': {'aint': 55}}]
def test_body_and_params(self): def test_body_and_params(self):
r = self.app.post('/argtypes/setint.json?value=2', r = self.app.post('/argtypes/setint.json?value=2', '{"value": 2}',
'{"value": 2}', headers={"Content-Type": "application/json"},
headers={"Content-Type": "application/json"}, expect_errors=True)
expect_errors=True)
print(r) print(r)
assert r.status_int == 400 assert r.status_int == 400
assert json.loads(r.text)['faultstring'] == \ assert json.loads(r.text)['faultstring'] == \
@ -233,21 +236,21 @@ class TestRestJson(wsme.tests.protocol.ProtocolTestCase):
assert json.loads(r.text) == 2 assert json.loads(r.text) == 2
def test_unknown_arg(self): def test_unknown_arg(self):
r = self.app.post('/returntypes/getint.json', r = self.app.post('/returntypes/getint.json', '{"a": 2}',
'{"a": 2}', headers={"Content-Type": "application/json"},
headers={"Content-Type": "application/json"}, expect_errors=True)
expect_errors=True)
print(r) print(r)
assert r.status_int == 400 assert r.status_int == 400
assert json.loads(r.text)['faultstring'].startswith( assert json.loads(r.text)['faultstring'].startswith(
"Unknown argument:") "Unknown argument:"
)
r = self.app.get('/returntypes/getint.json?a=2', r = self.app.get('/returntypes/getint.json?a=2', expect_errors=True)
expect_errors=True)
print(r) print(r)
assert r.status_int == 400 assert r.status_int == 400
assert json.loads(r.text)['faultstring'].startswith( assert json.loads(r.text)['faultstring'].startswith(
"Unknown argument:") "Unknown argument:"
)
def test_unset_attrs(self): def test_unset_attrs(self):
class AType(object): class AType(object):
@ -269,14 +272,12 @@ class TestRestJson(wsme.tests.protocol.ProtocolTestCase):
def test_None_tojson(self): def test_None_tojson(self):
for dt in (datetime.date, datetime.time, datetime.datetime, for dt in (datetime.date, datetime.time, datetime.datetime,
decimal.Decimal): decimal.Decimal):
assert tojson(dt, None) is None assert tojson(dt, None) is None
def test_None_fromjson(self): def test_None_fromjson(self):
for dt in (str, int, for dt in (str, int, datetime.date, datetime.time, datetime.datetime,
datetime.date, datetime.time, datetime.datetime, decimal.Decimal, [int], {int: int}):
decimal.Decimal,
[int], {int: int}):
assert fromjson(dt, None) is None assert fromjson(dt, None) is None
def test_nest_result(self): 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) r = wsme.rest.json.encode_sample_value(MyType, v, True)
print(r) print(r)
assert r[0] == ('javascript') assert r[0] == ('javascript')
assert r[1] == json.dumps({'aint': 4, 'astr': 's'}, assert r[1] == json.dumps({'aint': 4, 'astr': 's'}, ensure_ascii=False,
ensure_ascii=False, indent=4, sort_keys=True) indent=4, sort_keys=True)
def test_bytes_tojson(self): def test_bytes_tojson(self):
assert tojson(wsme.types.bytes, None) is None 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) el.text = six.text_type(obj)
elif type(obj) in (datetime.date, datetime.time, datetime.datetime): elif type(obj) in (datetime.date, datetime.time, datetime.datetime):
el.text = obj.isoformat() el.text = obj.isoformat()
elif type(obj) == type(None): elif isinstance(obj, type(None)):
el.set('nil', 'true') el.set('nil', 'true')
elif hasattr(datatype, '_wsme_attributes'): elif hasattr(datatype, '_wsme_attributes'):
for attr in datatype._wsme_attributes: for attr in datatype._wsme_attributes:
@ -120,8 +120,8 @@ def loadxml(el, datatype):
class TestRestXML(wsme.tests.protocol.ProtocolTestCase): class TestRestXML(wsme.tests.protocol.ProtocolTestCase):
protocol = 'restxml' protocol = 'restxml'
def call(self, fpath, _rt=None, _accept=None, def call(self, fpath, _rt=None, _accept=None, _no_result_decode=False,
_no_result_decode=False, **kw): **kw):
el = dumpxml('parameters', kw) el = dumpxml('parameters', kw)
content = et.tostring(el) content = et.tostring(el)
headers = { headers = {
@ -142,10 +142,11 @@ class TestRestXML(wsme.tests.protocol.ProtocolTestCase):
el = et.fromstring(res.body) el = et.fromstring(res.body)
if el.tag == 'error': if el.tag == 'error':
raise wsme.tests.protocol.CallException( raise wsme.tests.protocol.CallException(
el.find('faultcode').text, el.find('faultcode').text,
el.find('faultstring').text, el.find('faultstring').text,
el.find('debuginfo') is not None and el.find('debuginfo') is not None and
el.find('debuginfo').text or None) el.find('debuginfo').text or None
)
else: else:
return loadxml(et.fromstring(res.body), _rt) return loadxml(et.fromstring(res.body), _rt)

View File

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

View File

@ -87,7 +87,8 @@ def parse_isodatetime(value):
try: try:
from collections import OrderedDict from collections import OrderedDict
except ImportError: 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. # Passes Python2.7's test suite and incorporates all the latest updates.
try: try:
@ -103,14 +104,17 @@ except ImportError:
class OrderedDict(dict): class OrderedDict(dict):
'Dictionary that remembers insertion order' 'Dictionary that remembers insertion order'
# An inherited dict maps keys to values. # An inherited dict maps keys to values.
# The inherited dict provides __getitem__, __len__, __contains__, and get. # The inherited dict provides __getitem__, __len__, __contains__, and
# The remaining methods are order-aware. # get. The remaining methods are order-aware.
# Big-O running times for all methods are the same as for regular dictionaries. #
# 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 internal self.__map dictionary maps keys to links in a doubly
# The circular doubly linked list starts and ends with a sentinel element. # linked list. The circular doubly linked list starts and ends with
# The sentinel element never gets deleted (this simplifies the algorithm). # a sentinel element. The sentinel element never gets deleted (this
# Each link is stored as a list of length three: [PREV, NEXT, KEY]. # simplifies the algorithm). Each link is stored as a list of length
# three: [PREV, NEXT, KEY].
def __init__(self, *args, **kwds): def __init__(self, *args, **kwds):
'''Initialize an ordered dictionary. Signature is the same as for '''Initialize an ordered dictionary. Signature is the same as for
@ -119,7 +123,9 @@ except ImportError:
''' '''
if len(args) > 1: 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: try:
self.__root self.__root
except AttributeError: except AttributeError:
@ -130,8 +136,9 @@ except ImportError:
def __setitem__(self, key, value, dict_setitem=dict.__setitem__): def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
'od.__setitem__(i, y) <==> od[i]=y' 'od.__setitem__(i, y) <==> od[i]=y'
# Setting a new item creates a new link which goes at the end of the linked # Setting a new item creates a new link which goes at the end of
# list, and the inherited dictionary is updated with the new key/value pair. # the linked list, and the inherited dictionary is updated with the
# new key/value pair.
if key not in self: if key not in self:
root = self.__root root = self.__root
last = root[0] last = root[0]
@ -140,8 +147,9 @@ except ImportError:
def __delitem__(self, key, dict_delitem=dict.__delitem__): def __delitem__(self, key, dict_delitem=dict.__delitem__):
'od.__delitem__(y) <==> del od[y]' 'od.__delitem__(y) <==> del od[y]'
# Deleting an existing item uses self.__map to find the link which is # Deleting an existing item uses self.__map to find the link which
# then removed by updating the links in the predecessor and successor nodes. # is then removed by updating the links in the predecessor and
# successor nodes.
dict_delitem(self, key) dict_delitem(self, key)
link_prev, link_next, key = self.__map.pop(key) link_prev, link_next, key = self.__map.pop(key)
link_prev[1] = link_next link_prev[1] = link_next
@ -177,7 +185,8 @@ except ImportError:
def popitem(self, last=True): def popitem(self, last=True):
'''od.popitem() -> (k, v), return and remove a (key, value) pair. '''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: if not self:
@ -227,12 +236,12 @@ except ImportError:
yield (k, self[k]) yield (k, self[k])
def update(*args, **kwds): 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 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 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: if len(args) > 2:
@ -257,14 +266,15 @@ except ImportError:
for key, value in kwds.items(): for key, value in kwds.items():
self[key] = value self[key] = value
__update = update # let subclasses override update without breaking __init__ # let subclasses override update without breaking __init__
__update = update
__marker = object() __marker = object()
def pop(self, key, default=__marker): def pop(self, key, default=__marker):
'''od.pop(k[,d]) -> v, remove specified key and return the corresponding value. '''od.pop(k[,d]) -> v, remove specified key and return the
If key is not found, d is returned if given, otherwise KeyError is raised. corresponding value. If key is not found, d is returned if given,
otherwise KeyError is raised.
''' '''
if key in self: if key in self:
result = self[key] result = self[key]
@ -275,7 +285,8 @@ except ImportError:
return default return default
def setdefault(self, key, default=None): 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: if key in self:
return self[key] return self[key]
self[key] = default self[key] = default
@ -320,12 +331,15 @@ except ImportError:
return d return d
def __eq__(self, other): def __eq__(self, other):
'''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive '''od.__eq__(y) <==> od==y. Comparison to another OD is
while comparison to a regular mapping is order-insensitive. order-sensitive while comparison to a regular mapping is
order-insensitive.
''' '''
if isinstance(other, OrderedDict): 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) return dict.__eq__(self, other)
def __ne__(self, other): def __ne__(self, other):
@ -342,5 +356,6 @@ except ImportError:
return ValuesView(self) return ValuesView(self)
def viewitems(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) 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): def create(self, obj):
pass pass
def read(self, query=None, sort=None, def read(self, query=None, sort=None, page=None, start=None, limit=None):
page=None, start=None, limit=None):
pass pass
def update(self, obj): def update(self, obj):
@ -116,5 +115,7 @@ Ext.define('%(appns)s.store.%(classname)s', {
return tpl % d return tpl % d
DataStoreController = DataStoreControllerMeta('DataStoreController', DataStoreController = DataStoreControllerMeta(
(DataStoreControllerMixin,), {}) 'DataStoreController',
(DataStoreControllerMixin,), {}
)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -9,8 +9,14 @@ class TestUtils():
def test_validator_with_invalid_int_code(self): def test_validator_with_invalid_int_code(self):
invalid_int_code = 648 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): def test_validator_with_invalid_str_code(self):
invalid_str_code = '404' 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"
)