Skip to content

Commit

Permalink
improvement tests and coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
nycholas committed Aug 9, 2015
1 parent 8940fb3 commit 2294fbe
Show file tree
Hide file tree
Showing 18 changed files with 458 additions and 27 deletions.
28 changes: 28 additions & 0 deletions .coveragerc
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
[run]
branch = True
omit = flask_jsonrpc/_compat.py

[report]
exclude_lines =
# Have to re-enable the standard pragma
pragma: no cover

# Don't complain about missing debug-only code:
def __repr__
if self\.debug

# Don't complain if tests don't hit defensive assertion code:
raise AssertionError
raise NotImplementedError

# Don't complain if non-runnable code isn't run:
if 0:
if __name__ == .__main__.:
if current_app\.config\[.DEBUG.\]:
if app\.config\[.DEBUG.\]

# Classes tests
class FakePayload
class TestingServiceProxy

ignore_errors = True
2 changes: 1 addition & 1 deletion flask_jsonrpc/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@

try:
from flaskext.babel import gettext as _
_("You're lazy...") # this function lazy-loads settings
_("You're lazy...") # this function lazy-loads settings (pragma: no cover)
except (ImportError, NameError):
_ = lambda t, *a, **k: t

Expand Down
3 changes: 0 additions & 3 deletions flask_jsonrpc/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,3 @@ def _f(*args, **kwargs):
raise InvalidCredentialsError()
return f(*args, **kwargs)
return _f

def log_exception(sender, exception, **extra):
sender.logger.debug('Got exception during processing: %s', exception)
6 changes: 3 additions & 3 deletions flask_jsonrpc/proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,10 @@ def __getattr__(self, name):
return self.__class__(**params)

def __repr__(self):
return {
return json.dumps({
'jsonrpc': self.version,
'method': self.service_name
}
})

def send_payload(self, params):
"""Performs the actual sending action and returns the result
Expand Down Expand Up @@ -100,7 +100,7 @@ def __init__(self, content):
def read(self, num_bytes=None):
if num_bytes is None:
num_bytes = self.__len or 0
assert self.__len >= num_bytes, "Cannot read more than the available bytes from the HTTP incoming data."
assert self.__len >= num_bytes, 'Cannot read more than the available bytes from the HTTP incoming data.'
content = self.__content.read(num_bytes)
self.__len -= num_bytes
return content
Expand Down
17 changes: 13 additions & 4 deletions flask_jsonrpc/site.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
from flask import json, jsonify, current_app

from flask_jsonrpc.types import Object, Array, Any
from flask_jsonrpc.helpers import extract_raw_data_request, log_exception
from flask_jsonrpc.helpers import extract_raw_data_request
from flask_jsonrpc._compat import (text_type, string_types, integer_types,
iteritems, iterkeys)
from flask_jsonrpc.exceptions import (Error, ParseError, InvalidRequestError,
Expand Down Expand Up @@ -172,13 +172,22 @@ def validate_get(self, request, method):
return True, D
return False, {}

def apply_version_2_0(self, f, p):
return f(**encode_kw(p)) if type(p) is dict else f(*p)

def apply_version_1_1(self, f, p):
return f(*encode_arg11(p), **encode_kw(encode_kw11(p)))

def apply_version_1_0(self, f, p):
return f(*p)

def response_dict(self, request, D, version_hint=JSONRPC_VERSION_DEFAULT):
version = version_hint
response = self.empty_response(version=version)
apply_version = {
'2.0': lambda f, p: f(**encode_kw(p)) if type(p) is dict else f(*p),
'1.1': lambda f, p: f(*encode_arg11(p), **encode_kw(encode_kw11(p))),
'1.0': lambda f, p: f(*p)
'2.0': self.apply_version_2_0,
'1.1': self.apply_version_1_1,
'1.0': self.apply_version_1_0
}

try:
Expand Down
9 changes: 4 additions & 5 deletions flask_jsonrpc/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,11 @@ class Type(type):
"""

def __init__(self, *args, **kwargs):
type.__init__(self, *args, **kwargs)
super(Type, self).__init__(*args, **kwargs)

def __eq__(self, other):
for T in _types_gen(self):
if isinstance(other, Type) \
and T in other.t:
if isinstance(other, Type) and getattr(other, 't', False) and T in other.t:
return True
if type.__eq__(T, other) is True:
return True
Expand Down Expand Up @@ -93,8 +92,8 @@ def decode(self, n):
# JSON primatives and data types
Object = Type('Object', (object,), {}).I(dict).N('obj')
Number = Type('Number', (object,), {}).I(*(integer_types + (float, complex))).N('num')
Boolean = Type('Boolean', (object,), {}).I(bool).N('bit')
Boolean = Type('Boolean', (object,), {}).I(bool).N('bool')
String = Type('String', (object,), {}).I(*string_types).N('str')
Array = Type('Array', (object,), {}).I(list, set, tuple).N('arr')
Array = Type('Array', (object,), {}).I(list, set, frozenset, tuple).N('arr')
Nil = Type('Nil', (object,), {}).I(type(None)).N('nil')
Any = Type('Any', (object,), {}).I(Object, Number, Boolean, String, Array, Nil).N('any')
2 changes: 1 addition & 1 deletion run.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2013, Cenobit Technologies, Inc. http://cenobit.es/
# Copyright (c) 2012-2015, Cenobit Technologies, Inc. http://cenobit.es/
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2013, Cenobit Technologies, Inc. http://cenobit.es/
# Copyright (c) 2012-2015, Cenobit Technologies, Inc. http://cenobit.es/
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
Expand Down
2 changes: 1 addition & 1 deletion tests/apptest.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ def kill(self, process=None):
self.process = None


class ServerTestCase(unittest.TestCase):
class FlaskJSONRPCServerTestCase(unittest.TestCase):

@classmethod
def setUpClass(cls):
Expand Down
89 changes: 89 additions & 0 deletions tests/test_browse.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2015, Cenobit Technologies, Inc. http://cenobit.es/
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the Cenobit Technologies nor the names of
# its contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from __future__ import unicode_literals
import unittest

from flask import json

from flask_jsonrpc._compat import text_type

from apptest import FlaskJSONRPCServerTestCase


class JSONRPCBrowseTestCase(FlaskJSONRPCServerTestCase):

def test_index(self):
with self.app:
r = self.app.get('/api/browse/')
data = text_type(r.data)
self.assertEqual(200, r.status_code)
self.assertIn('Flask JSON-RPC', data)
self.assertIn('Web browsable API', data)
self.assertIn('https://github.com/cenobites/flask-jsonrpc', data)

def test_json_packages(self):
with self.app:
r = self.app.get('/api/browse/packages.json')
data = json.loads(r.data)
self.assertEqual(200, r.status_code)
self.assertIsNotNone(data['jsonrpc'])
self.assertIn({
'params': [{'type': 'any', 'name': 'name'}],
'return': {'type': 'any'},
'name': 'jsonrpc.echo',
'summary': None,
'idempotent': False
}, data['jsonrpc'])

def test_json_method(self):
with self.app:
r = self.app.get('/api/browse/jsonrpc.echo.json')
data = json.loads(r.data)
self.assertEqual(200, r.status_code)
self.assertIsNotNone(data)
self.assertEqual({
'params': [{'type': 'any', 'name': 'name'}],
'return': {'type': 'any'},
'name': 'jsonrpc.echo',
'summary': None,
'idempotent': False
}, data)

def test_partials_dashboard(self):
with self.app:
r = self.app.get('/api/browse/partials/dashboard.html')
data = text_type(r.data)
self.assertEqual(200, r.status_code)
self.assertIn('Welcome to web browsable API', data)

def test_response_object(self):
with self.app:
r = self.app.get('/api/browse/partials/response_object.html')
data = text_type(r.data)
self.assertEqual(200, r.status_code)
self.assertIn('HTTP', data)
39 changes: 39 additions & 0 deletions tests/test_exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2015, Cenobit Technologies, Inc. http://cenobit.es/
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the Cenobit Technologies nor the names of
# its contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from __future__ import unicode_literals
import unittest

from flask_jsonrpc.exceptions import Error


class JSONRPCExceptionsTestCase(unittest.TestCase):

def test_exceptions(self):
error = Error(message='Testing...', code=123)
#error_dict = error.json_rpc_format
#self.assertEqual('Error', error_dict['name'])
14 changes: 10 additions & 4 deletions tests/test_funcional.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,16 @@
from __future__ import unicode_literals
import unittest

from flask import json

from flask_jsonrpc._compat import b, u, text_type
from flask_jsonrpc.site import validate_params
from flask_jsonrpc import _parse_sig, OrderedDict
from flask_jsonrpc.exceptions import InvalidParamsError
from flask_jsonrpc.types import Any, Object, Number, Boolean, String, Array, Nil

from run import app, jsonrpc
from apptest import jsonrpc


class JSONRPCFunctionalTests(unittest.TestCase):
class JSONRPCFunctionalTestCase(unittest.TestCase):

def test_method_parser(self):
working_sigs = [
Expand Down Expand Up @@ -91,8 +89,16 @@ def test_validate_args_any(self):
self.assertTrue(validate_params(M, {'params': {'s1': 'omg', 's2': 'wtf'}}) is None)

def test_types(self):
self.assertEqual(type(1), Number)
self.assertEqual(type(1.0), Number)
self.assertEqual(type(1+3j), Number)
self.assertEqual(type(-34.54555), Number)
self.assertEqual(type(99999999999999999), Number)
self.assertEqual(type(u''), String)
self.assertEqual(type(''), String)
self.assertEqual(type({}), Object)
self.assertEqual(type(set()), Array)
self.assertEqual(type(frozenset()), Array)
self.assertNotEqual(type(''), Object)
self.assertNotEqual(type([]), Object)
self.assertEqual(type([]), Array)
Expand Down
35 changes: 35 additions & 0 deletions tests/test_helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2015, Cenobit Technologies, Inc. http://cenobit.es/
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the Cenobit Technologies nor the names of
# its contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from __future__ import unicode_literals
import unittest


class JSONRPCHelpersTestCase(unittest.TestCase):

def test_exceptions(self):
pass
35 changes: 35 additions & 0 deletions tests/test_jsonrpc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2015, Cenobit Technologies, Inc. http://cenobit.es/
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the Cenobit Technologies nor the names of
# its contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from __future__ import unicode_literals
import unittest


class FlaskJSONRPCTestCase(unittest.TestCase):

def test_positional_args(self):
pass
Loading

0 comments on commit 2294fbe

Please sign in to comment.