From 9d69029f8555bbd130a68c2dc6f58e818b5cf432 Mon Sep 17 00:00:00 2001 From: Doug Black Date: Wed, 16 Apr 2014 18:10:36 -0700 Subject: [PATCH] whitespace fixes. one space in classes, else two --- flask_restful/__init__.py | 23 ++++--- flask_restful/fields.py | 2 +- flask_restful/representations/json.py | 1 + flask_restful/reqparse.py | 5 +- flask_restful/utils/__init__.py | 2 + flask_restful/utils/cors.py | 1 + flask_restful/utils/crypto.py | 6 ++ flask_restful/utils/ordereddict.py | 3 +- tests/test_api.py | 95 +++++++++------------------ tests/test_api_with_blueprint.py | 20 ++---- tests/test_fields.py | 38 +++-------- tests/test_reqparse.py | 55 +--------------- tests/test_types.py | 23 ++++--- 13 files changed, 85 insertions(+), 189 deletions(-) diff --git a/flask_restful/__init__.py b/flask_restful/__init__.py index 4debd438..b1bd2b4b 100644 --- a/flask_restful/__init__.py +++ b/flask_restful/__init__.py @@ -120,10 +120,11 @@ def _complete_url(self, url_part, registration_prefix): :param registration_prefix: The part of the url contributed by the blueprint. Generally speaking, BlueprintSetupState.url_prefix """ - - parts = {'b' : registration_prefix, - 'a' : self.prefix, - 'e' : url_part} + parts = { + 'b': registration_prefix, + 'a': self.prefix, + 'e': url_part + } return ''.join(parts[key] for key in self.url_part_order if parts[key]) @staticmethod @@ -230,7 +231,6 @@ def _should_use_fr_error_handler(self): # Werkzeug throws other kinds of exceptions, such as Redirect pass - def _has_fr_route(self): """Encapsulating the rules for whether the request was to a Flask endpoint""" # 404's, 405's, which might not have a url_rule @@ -300,9 +300,10 @@ def handle_error(self, e): data["message"] = "" data['message'] += 'You have requested this URI [' + request.path + \ - '] but did you mean ' + \ - ' or '.join((rules[match] - for match in close_matches)) + ' ?' + '] but did you mean ' + \ + ' or '.join(( + rules[match] for match in close_matches) + ) + ' ?' resp = self.make_response(data, code) @@ -345,7 +346,6 @@ def add_resource(self, resource, *urls, **kwargs): else: self.resources.append((resource, urls, kwargs)) - def _register_view(self, app, resource, *urls, **kwargs): endpoint = kwargs.pop('endpoint', None) or resource.__name__.lower() self.endpoints.add(endpoint) @@ -364,7 +364,6 @@ def _register_view(self, app, resource, *urls, **kwargs): for decorator in self.decorators: resource_func = decorator(resource_func) - for url in urls: # If this Api has a blueprint if self.blueprint: @@ -528,8 +527,8 @@ def make(cls): return [marshal(d, fields) for d in data] items = ((k, marshal(data, v) if isinstance(v, dict) - else make(v).output(k, data)) - for k, v in fields.items()) + else make(v).output(k, data)) + for k, v in fields.items()) return OrderedDict(items) diff --git a/flask_restful/fields.py b/flask_restful/fields.py index 93978b73..0c2e51b2 100644 --- a/flask_restful/fields.py +++ b/flask_restful/fields.py @@ -229,7 +229,7 @@ def __init__(self, endpoint, absolute=False, scheme=None): def output(self, key, obj): try: data = to_marshallable_type(obj) - o = urlparse(url_for(self.endpoint, _external = self.absolute, **data)) + o = urlparse(url_for(self.endpoint, _external=self.absolute, **data)) if self.absolute: scheme = self.scheme if self.scheme is not None else o.scheme return urlunparse((scheme, o.netloc, o.path, "", "", "")) diff --git a/flask_restful/representations/json.py b/flask_restful/representations/json.py index 9f5b1db5..ce6a77a8 100644 --- a/flask_restful/representations/json.py +++ b/flask_restful/representations/json.py @@ -7,6 +7,7 @@ # function, used below. settings = {} + def output_json(data, code, headers=None): """Makes a Flask response with a JSON encoded body""" diff --git a/flask_restful/reqparse.py b/flask_restful/reqparse.py index 3e12e979..564b5f80 100644 --- a/flask_restful/reqparse.py +++ b/flask_restful/reqparse.py @@ -4,12 +4,14 @@ import inspect import six + class Namespace(dict): def __getattr__(self, name): try: return self[name] except KeyError: raise AttributeError(name) + def __setattr__(self, name, value): self[name] = value @@ -24,6 +26,7 @@ def __setattr__(self, name, value): text_type = lambda x: six.text_type(x) + class Argument(object): def __init__(self, name, default=None, dest=None, required=False, @@ -155,7 +158,7 @@ def parse(self, request): _friendly_location.get(self.location, self.location) ) else: - friendly_locations = [_friendly_location.get(loc, loc) \ + friendly_locations = [_friendly_location.get(loc, loc) for loc in self.location] error_msg = u"Missing required parameter {0} in {1}".format( self.name, diff --git a/flask_restful/utils/__init__.py b/flask_restful/utils/__init__.py index ec32cd28..9ac29f6b 100644 --- a/flask_restful/utils/__init__.py +++ b/flask_restful/utils/__init__.py @@ -1,9 +1,11 @@ from werkzeug.http import HTTP_STATUS_CODES + def http_status_message(code): """Maps an HTTP status code to the textual status""" return HTTP_STATUS_CODES.get(code, '') + def error_data(code): """Constructs a dictionary with status and message for returning in an error response""" diff --git a/flask_restful/utils/cors.py b/flask_restful/utils/cors.py index 381d1c94..94692863 100644 --- a/flask_restful/utils/cors.py +++ b/flask_restful/utils/cors.py @@ -2,6 +2,7 @@ from flask import make_response, request, current_app from functools import update_wrapper + def crossdomain(origin=None, methods=None, headers=None, max_age=21600, attach_to_all=True, automatic_options=True): diff --git a/flask_restful/utils/crypto.py b/flask_restful/utils/crypto.py index 9c5a5b4b..972e289a 100644 --- a/flask_restful/utils/crypto.py +++ b/flask_restful/utils/crypto.py @@ -2,18 +2,22 @@ from Crypto.Cipher import AES from base64 import b64encode, b64decode + __all__ = "encrypt", "decrypt" BLOCK_SIZE = 16 INTERRUPT = b'\0' # something impossible to put in a string PADDING = b'\1' + def pad(data): return data + INTERRUPT + PADDING * (BLOCK_SIZE - (len(data) + 1) % BLOCK_SIZE) + def strip(data): return data.rstrip(PADDING).rstrip(INTERRUPT) + def create_cipher(key, seed): if len(seed) != 16: raise ValueError("Choose a seed of 16 bytes") @@ -21,9 +25,11 @@ def create_cipher(key, seed): raise ValueError("Choose a key of 32 bytes") return AES.new(key, AES.MODE_CBC, seed) + def encrypt(plaintext_data, key, seed): plaintext_data = pickle.dumps(plaintext_data, pickle.HIGHEST_PROTOCOL) # whatever you give me I need to be able to restitute it return b64encode(create_cipher(key, seed).encrypt(pad(plaintext_data))) + def decrypt(encrypted_data, key, seed): return pickle.loads(strip(create_cipher(key, seed).decrypt(b64decode(encrypted_data)))) diff --git a/flask_restful/utils/ordereddict.py b/flask_restful/utils/ordereddict.py index 4331b94b..71da1381 100644 --- a/flask_restful/utils/ordereddict.py +++ b/flask_restful/utils/ordereddict.py @@ -23,6 +23,7 @@ from UserDict import DictMixin import six + class OrderedDict(dict, DictMixin): #noinspection PyMissingConstructor @@ -120,7 +121,7 @@ def __eq__(self, other): if isinstance(other, OrderedDict): if len(self) != len(other): return False - for p, q in zip(self.items(), other.items()): + for p, q in zip(self.items(), other.items()): if p != q: return False return True diff --git a/tests/test_api.py b/tests/test_api.py index f80f20ba..4647adab 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -14,12 +14,14 @@ from flask_restful import OrderedDict from json import dumps, loads #noinspection PyUnresolvedReferences -from nose.tools import assert_equals, assert_true # you need it for tests in form of continuations +from nose.tools import assert_equals, assert_true # you need it for tests in form of continuations import six + def check_unpack(expected, value): assert_equals(expected, value) + def test_unpack(): yield check_unpack, ("hey", 200, {}), unpack("hey") yield check_unpack, (("hey",), 200, {}), unpack(("hey",)) @@ -27,18 +29,19 @@ def test_unpack(): yield check_unpack, ("hey", 201, "foo"), unpack(("hey", 201, "foo")) yield check_unpack, (["hey", 201], 200, {}), unpack(["hey", 201]) + # Add a dummy Resource to verify that the app is properly set. class HelloWorld(flask_restful.Resource): def get(self): return {} + class APITestCase(unittest.TestCase): def test_http_code(self): self.assertEquals(http_status_message(200), 'OK') self.assertEquals(http_status_message(404), 'Not Found') - def test_unauthorized(self): app = Flask(__name__) api = flask_restful.Api(app) @@ -47,8 +50,7 @@ def test_unauthorized(self): with app.test_request_context('/foo'): response = api.unauthorized(response) self.assertEquals(response.headers['WWW-Authenticate'], - 'Basic realm="flask-restful"') - + 'Basic realm="flask-restful"') def test_unauthorized_custom_realm(self): app = Flask(__name__) @@ -60,7 +62,6 @@ def test_unauthorized_custom_realm(self): response = api.unauthorized(response) self.assertEquals(response.headers['WWW-Authenticate'], 'Basic realm="Foo"') - def test_handle_error_401_sends_challege_default_realm(self): app = Flask(__name__) api = flask_restful.Api(app) @@ -72,8 +73,7 @@ def test_handle_error_401_sends_challege_default_realm(self): resp = api.handle_error(exception) self.assertEquals(resp.status_code, 401) self.assertEquals(resp.headers['WWW-Authenticate'], - 'Basic realm="flask-restful"') - + 'Basic realm="flask-restful"') def test_handle_error_401_sends_challege_configured_realm(self): app = Flask(__name__) @@ -87,15 +87,13 @@ def test_handle_error_401_sends_challege_configured_realm(self): resp = api.handle_error(exception) self.assertEquals(resp.status_code, 401) self.assertEquals(resp.headers['WWW-Authenticate'], - 'Basic realm="test-realm"') - + 'Basic realm="test-realm"') def test_error_data(self): self.assertEquals(error_data(400), { 'status': 400, 'message': 'Bad Request', - }) - + }) def test_marshal(self): fields = OrderedDict([('foo', flask_restful.fields.Raw)]) @@ -125,14 +123,12 @@ def test_marshal_field(self): output = flask_restful.marshal(marshal_fields, fields) self.assertEquals(output, {'foo': 'bar'}) - def test_marshal_tuple(self): fields = OrderedDict({'foo': flask_restful.fields.Raw}) marshal_fields = OrderedDict([('foo', 'bar'), ('bat', 'baz')]) output = flask_restful.marshal((marshal_fields,), fields) self.assertEquals(output, [{'foo': 'bar'}]) - def test_marshal_nested(self): fields = OrderedDict([ ('foo', flask_restful.fields.Raw), @@ -174,7 +170,6 @@ def test_marshal_nested_with_null(self): expected = OrderedDict([('foo', 'bar'), ('fee', None)]) self.assertEquals(output, expected) - def test_allow_null_presents_data(self): fields = OrderedDict([ ('foo', flask_restful.fields.Raw), @@ -219,7 +214,6 @@ def test_marshal_list(self): expected = OrderedDict([('foo', 'bar'), ('fee', (['fye', 'fum']))]) self.assertEquals(output, expected) - def test_marshal_list_of_nesteds(self): fields = OrderedDict([ ('foo', flask_restful.fields.Raw), @@ -232,7 +226,6 @@ def test_marshal_list_of_nesteds(self): expected = OrderedDict([('foo', 'bar'), ('fee', [OrderedDict([('fye', 'fum')])])]) self.assertEquals(output, expected) - def test_marshal_list_of_lists(self): fields = OrderedDict([ ('foo', flask_restful.fields.Raw), @@ -244,7 +237,6 @@ def test_marshal_list_of_lists(self): expected = OrderedDict([('foo', 'bar'), ('fee', [['fye'], ['fum']])]) self.assertEquals(output, expected) - def test_marshal_nested_dict(self): fields = OrderedDict([ ('foo', flask_restful.fields.Raw), @@ -259,7 +251,6 @@ def test_marshal_nested_dict(self): expected = OrderedDict([('foo', 'foo-val'), ('bar', OrderedDict([('a', 1), ('b', 2)]))]) self.assertEquals(output, expected) - def test_api_representation(self): app = Mock() api = flask_restful.Api(app) @@ -270,16 +261,14 @@ def foo(): self.assertEquals(api.representations['foo'], foo) - def test_api_base(self): app = Mock() - app.configure_mock(**{'record.side_effect' : AttributeError}) + app.configure_mock(**{'record.side_effect': AttributeError}) api = flask_restful.Api(app) self.assertEquals(api.urls, {}) self.assertEquals(api.prefix, '') self.assertEquals(api.default_mediatype, 'application/json') - def test_api_delayed_initialization(self): app = Flask(__name__) api = flask_restful.Api() @@ -288,14 +277,12 @@ def test_api_delayed_initialization(self): with app.test_client() as client: self.assertEquals(client.get('/').status_code, 200) - def test_api_prefix(self): app = Mock() - app.configure_mock(**{'record.side_effect' : AttributeError}) + app.configure_mock(**{'record.side_effect': AttributeError}) api = flask_restful.Api(app, prefix='/foo') self.assertEquals(api.prefix, '/foo') - def test_handle_server_error(self): app = Flask(__name__) api = flask_restful.Api(app) @@ -311,7 +298,6 @@ def test_handle_server_error(self): 'foo': 'bar', })) - def test_handle_auth(self): app = Flask(__name__) api = flask_restful.Api(app) @@ -323,17 +309,18 @@ def test_handle_auth(self): with app.test_request_context("/foo"): resp = api.handle_error(exception) self.assertEquals(resp.status_code, 401) - self.assertEquals(resp.data.decode(), dumps({'foo': 'bar',})) + self.assertEquals(resp.data.decode(), dumps({'foo': 'bar'})) self.assertTrue('WWW-Authenticate' in resp.headers) - def test_handle_api_error(self): app = Flask(__name__) api = flask_restful.Api(app) + class Test(flask_restful.Resource): def get(self): flask.abort(404) + api.add_resource(Test(), '/api', endpoint='api') app = app.test_client() @@ -344,7 +331,6 @@ def get(self): assert_equals(data.get('status'), 404) assert_true('message' in data) - def test_handle_non_api_error(self): app = Flask(__name__) flask_restful.Api(app) @@ -362,7 +348,6 @@ def test_non_api_error_404_catchall(self): resp = app.get("/foo") self.assertEquals(api.default_mediatype, resp.headers['Content-Type']) - def test_handle_error_signal(self): if not signals_available: # This test requires the blinker lib to run. @@ -376,6 +361,7 @@ def test_handle_error_signal(self): exception.data = {'foo': 'bar'} recorded = [] + def record(sender, exception): recorded.append(exception) @@ -415,7 +401,6 @@ def test_handle_smart_errors(self): api.add_resource(view, '/fee', endpoint='bir') api.add_resource(view, '/fii', endpoint='ber') - with app.test_request_context("/faaaaa"): resp = api.handle_error(exception) self.assertEquals(resp.status_code, 404) @@ -448,35 +433,34 @@ def test_handle_smart_errors(self): "status": 404 })) - def test_media_types(self): app = Flask(__name__) api = flask_restful.Api(app) - with app.test_request_context("/foo", - headers={'Accept': 'application/json'}): + with app.test_request_context("/foo", headers={ + 'Accept': 'application/json' + }): self.assertEquals(api.mediatypes(), ['application/json']) - def test_media_types_method(self): app = Flask(__name__) api = flask_restful.Api(app) - with app.test_request_context("/foo", - headers={'Accept': 'application/xml; q=.5'}): + with app.test_request_context("/foo", headers={ + 'Accept': 'application/xml; q=.5' + }): self.assertEquals(api.mediatypes_method()(Mock()), - ['application/xml', 'application/json']) - + ['application/xml', 'application/json']) def test_media_types_q(self): app = Flask(__name__) api = flask_restful.Api(app) - with app.test_request_context("/foo", - headers={'Accept': 'application/json; q=1; application/xml; q=.5'}): + with app.test_request_context("/foo", headers={ + 'Accept': 'application/json; q=1; application/xml; q=.5' + }): self.assertEquals(api.mediatypes(), - ['application/json', 'application/xml']) - + ['application/json', 'application/xml']) def test_decorator(self): def return_zero(func): @@ -492,7 +476,6 @@ def return_zero(func): app.add_url_rule.assert_called_with('/foo', view_func=0) - def test_add_resource_endpoint(self): app = Mock() app.view_functions = {} @@ -536,7 +519,6 @@ def get(self): foo2 = client.get('/foo/toto') self.assertEquals(foo2.data, b'"foo1"') - def test_add_resource(self): app = Mock(flask.Flask) app.view_functions = {} @@ -545,7 +527,7 @@ def test_add_resource(self): api.add_resource(views.MethodView, '/foo') app.add_url_rule.assert_called_with('/foo', - view_func=api.output()) + view_func=api.output()) def test_add_resource_kwargs(self): app = Mock(flask.Flask) @@ -555,8 +537,8 @@ def test_add_resource_kwargs(self): api.add_resource(views.MethodView, '/foo', defaults={"bar": "baz"}) app.add_url_rule.assert_called_with('/foo', - view_func=api.output(), defaults={"bar": "baz"}) - + view_func=api.output(), + defaults={"bar": "baz"}) def test_output_unpack(self): @@ -572,7 +554,6 @@ def make_empty_response(): self.assertEquals(resp.status_code, 200) self.assertEquals(resp.data.decode(), '{"foo": "bar"}') - def test_output_func(self): def make_empty_resposne(): @@ -587,7 +568,6 @@ def make_empty_resposne(): self.assertEquals(resp.status_code, 200) self.assertEquals(resp.data.decode(), '') - def test_resource(self): app = Flask(__name__) resource = flask_restful.Resource() @@ -595,7 +575,6 @@ def test_resource(self): with app.test_request_context("/foo"): resource.dispatch_request() - def test_resource_resp(self): app = Flask(__name__) resource = flask_restful.Resource() @@ -604,7 +583,6 @@ def test_resource_resp(self): resource.get.return_value = flask.make_response('') resource.dispatch_request() - def test_resource_text_plain(self): app = Flask(__name__) @@ -615,7 +593,7 @@ class Foo(flask_restful.Resource): representations = { 'text/plain': text, - } + } def get(self): return 'hello' @@ -625,21 +603,18 @@ def get(self): resp = resource.dispatch_request() self.assertEquals(resp.data.decode(), 'hello') - def test_resource_error(self): app = Flask(__name__) resource = flask_restful.Resource() with app.test_request_context("/foo"): self.assertRaises(AssertionError, lambda: resource.dispatch_request()) - def test_resource_head(self): app = Flask(__name__) resource = flask_restful.Resource() with app.test_request_context("/foo", method="HEAD"): self.assertRaises(AssertionError, lambda: resource.dispatch_request()) - def test_abort_data(self): try: flask_restful.abort(404, foo='bar') @@ -647,7 +622,6 @@ def test_abort_data(self): except Exception as e: self.assertEquals(e.data, {'foo': 'bar'}) - def test_abort_no_data(self): try: flask_restful.abort(404) @@ -655,7 +629,6 @@ def test_abort_no_data(self): except Exception as e: self.assertEquals(False, hasattr(e, "data")) - def test_abort_custom_message(self): try: flask_restful.abort(404, message="no user") @@ -663,11 +636,9 @@ def test_abort_custom_message(self): except Exception as e: assert_equals(e.data['message'], "no user") - def test_abort_type(self): self.assertRaises(werkzeug.exceptions.HTTPException, lambda: flask_restful.abort(404)) - def test_endpoints(self): app = Flask(__name__) api = flask_restful.Api(app) @@ -678,14 +649,12 @@ def test_endpoints(self): with app.test_request_context('/ids/3'): self.assertTrue(api._has_fr_route()) - def test_url_for(self): app = Flask(__name__) api = flask_restful.Api(app) api.add_resource(HelloWorld, '/ids/') with app.test_request_context('/foo'): - self.assertEqual(api.url_for(HelloWorld, id = 123), '/ids/123') - + self.assertEqual(api.url_for(HelloWorld, id=123), '/ids/123') def test_fr_405(self): app = Flask(__name__) @@ -745,7 +714,7 @@ def get(self): with patch.multiple(json_rep, dumps=json_dumps_mock, settings=new_settings): with app.test_client() as client: - foo = client.get('/foo') + client.get('/foo') # Assert that the function was called with the above settings. data, kwargs = json_dumps_mock.call_args diff --git a/tests/test_api_with_blueprint.py b/tests/test_api_with_blueprint.py index b15ecd22..ff7059bb 100644 --- a/tests/test_api_with_blueprint.py +++ b/tests/test_api_with_blueprint.py @@ -21,13 +21,13 @@ def get(self): class GoodbyeWorld(flask_restful.Resource): def __init__(self, err): self.err = err + def get(self): flask.abort(self.err) class APIWithBlueprintTestCase(unittest.TestCase): - def test_api_base(self): blueprint = Blueprint('test', __name__) api = flask_restful.Api(blueprint) @@ -37,7 +37,6 @@ def test_api_base(self): self.assertEquals(api.prefix, '') self.assertEquals(api.default_mediatype, 'application/json') - def test_api_delayed_initialization(self): blueprint = Blueprint('test', __name__) api = flask_restful.Api() @@ -46,27 +45,24 @@ def test_api_delayed_initialization(self): app.register_blueprint(blueprint) api.add_resource(HelloWorld, '/', endpoint="hello") - def test_add_resource_endpoint(self): blueprint = Blueprint('test', __name__) api = flask_restful.Api(blueprint) - view = Mock(**{'as_view.return_value' : Mock(__name__='test_view')}) + view = Mock(**{'as_view.return_value': Mock(__name__='test_view')}) api.add_resource(view, '/foo', endpoint='bar') app = Flask(__name__) app.register_blueprint(blueprint) view.as_view.assert_called_with('bar') - def test_add_resource_endpoint_after_registration(self): blueprint = Blueprint('test', __name__) api = flask_restful.Api(blueprint) app = Flask(__name__) app.register_blueprint(blueprint) - view = Mock(**{'as_view.return_value' : Mock(__name__='test_view')}) + view = Mock(**{'as_view.return_value': Mock(__name__='test_view')}) api.add_resource(view, '/foo', endpoint='bar') view.as_view.assert_called_with('bar') - def test_url_with_api_prefix(self): blueprint = Blueprint('test', __name__) api = flask_restful.Api(blueprint, prefix='/api') @@ -76,7 +72,6 @@ def test_url_with_api_prefix(self): with app.test_request_context('/api/hi'): self.assertEquals(request.endpoint, 'test.hello') - def test_url_with_blueprint_prefix(self): blueprint = Blueprint('test', __name__, url_prefix='/bp') api = flask_restful.Api(blueprint) @@ -86,7 +81,6 @@ def test_url_with_blueprint_prefix(self): with app.test_request_context('/bp/hi'): self.assertEquals(request.endpoint, 'test.hello') - def test_url_with_registration_prefix(self): blueprint = Blueprint('test', __name__) api = flask_restful.Api(blueprint) @@ -96,7 +90,6 @@ def test_url_with_registration_prefix(self): with app.test_request_context('/reg/hi'): self.assertEquals(request.endpoint, 'test.hello') - def test_registration_prefix_overrides_blueprint_prefix(self): blueprint = Blueprint('test', __name__, url_prefix='/bp') api = flask_restful.Api(blueprint) @@ -106,7 +99,6 @@ def test_registration_prefix_overrides_blueprint_prefix(self): with app.test_request_context('/reg/hi'): self.assertEquals(request.endpoint, 'test.hello') - def test_url_with_api_and_blueprint_prefix(self): blueprint = Blueprint('test', __name__, url_prefix='/bp') api = flask_restful.Api(blueprint, prefix='/api') @@ -116,7 +108,6 @@ def test_url_with_api_and_blueprint_prefix(self): with app.test_request_context('/bp/api/hi'): self.assertEquals(request.endpoint, 'test.hello') - def test_url_part_order_aeb(self): blueprint = Blueprint('test', __name__, url_prefix='/bp') api = flask_restful.Api(blueprint, prefix='/api', url_part_order='aeb') @@ -126,7 +117,6 @@ def test_url_part_order_aeb(self): with app.test_request_context('/api/hi/bp'): self.assertEquals(request.endpoint, 'test.hello') - def test_error_routing(self): blueprint = Blueprint('test', __name__) api = flask_restful.Api(blueprint) @@ -141,7 +131,6 @@ def test_error_routing(self): api._should_use_fr_error_handler = Mock(return_value=False) assert_true(api._has_fr_route()) - def test_non_blueprint_rest_error_routing(self): blueprint = Blueprint('test', __name__) api = flask_restful.Api(blueprint) @@ -171,7 +160,6 @@ def test_non_blueprint_rest_error_routing(self): assert_true(api._has_fr_route()) assert_false(api2._has_fr_route()) - def test_non_blueprint_non_rest_error_routing(self): blueprint = Blueprint('test', __name__) api = flask_restful.Api(blueprint) @@ -179,9 +167,11 @@ def test_non_blueprint_non_rest_error_routing(self): api.add_resource(GoodbyeWorld(404), '/bye', endpoint="bye") app = Flask(__name__) app.register_blueprint(blueprint, url_prefix='/blueprint') + @app.route('/hi') def hi(): return 'hi' + @app.route('/bye') def bye(): flask.abort(404) diff --git a/tests/test_fields.py b/tests/test_fields.py index 33627a0a..f5cd7822 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -7,19 +7,23 @@ from datetime import datetime from flask import Flask #noinspection PyUnresolvedReferences -from nose.tools import assert_equals # you need it for tests in form of continuations +from nose.tools import assert_equals # you need it for tests in form of continuations class Foo(object): def __init__(self): self.hey = 3 + + class Bar(object): def __marshallable__(self): return {"hey": 3} + def check_field(expected, field, value): assert_equals(expected, field.output('a', {'a': value})) + def test_float(): values = [ ("-3.13", "-3.13"), @@ -37,7 +41,7 @@ def test_boolean(): ({}, False), ("false", True), # These are different from php ("0", True), # Will this be a problem? - ] + ] for value, expected in values: yield check_field, expected, fields.Boolean(), value @@ -52,46 +56,39 @@ def test_basic_dictionary(self): field = fields.String() self.assertEquals(field.output("foo", obj), "3") - def test_no_attribute(self): obj = {"bar": 3} field = fields.String() self.assertEquals(field.output("foo", obj), None) - def test_date_field_invalid(self): obj = {"bar": 3} field = fields.DateTime() self.assertRaises(MarshallingException, lambda: field.output("bar", obj)) - def test_attribute(self): obj = {"bar": 3} field = fields.String(attribute="bar") self.assertEquals(field.output("foo", obj), "3") - def test_formatting_field_none(self): obj = {} field = fields.FormattedString("/foo/{0[account_sid]}/{0[sid]}/") self.assertRaises(MarshallingException, lambda: field.output("foo", obj)) - def test_formatting_field_tuple(self): obj = (3, 4) field = fields.FormattedString("/foo/{0[account_sid]}/{0[sid]}/") self.assertRaises(MarshallingException, lambda: field.output("foo", obj)) - def test_formatting_field_dict(self): obj = { "sid": 3, "account_sid": 4, - } + } field = fields.FormattedString("/foo/{account_sid}/{sid}/") self.assertEquals(field.output("foo", obj), "/foo/4/3/") - def test_formatting_field(self): obj = Mock() obj.sid = 3 @@ -99,21 +96,18 @@ def test_formatting_field(self): field = fields.FormattedString("/foo/{account_sid}/{sid}/") self.assertEquals(field.output("foo", obj), "/foo/4/3/") - def test_basic_field(self): obj = Mock() obj.foo = 3 field = fields.Raw() self.assertEquals(field.output("foo", obj), 3) - def test_raw_field(self): obj = Mock() obj.foo = 3 field = fields.Raw() self.assertEquals(field.output("foo", obj), 3) - def test_nested_raw_field(self): foo = Mock() bar = Mock() @@ -122,22 +116,18 @@ def test_nested_raw_field(self): field = fields.Raw() self.assertEquals(field.output("bar.value", foo), 3) - def test_formatted_string_invalid_obj(self): field = fields.FormattedString("{hey}") self.assertRaises(MarshallingException, lambda: field.output("hey", None)) - def test_formatted_string(self): field = fields.FormattedString("{hey}") self.assertEquals("3", field.output("hey", Foo())) - def test_string_with_attribute(self): field = fields.String(attribute="hey") self.assertEquals("3", field.output("foo", Foo())) - def test_url_invalid_object(self): app = Flask(__name__) app.add_url_rule("/", "foobar", view_func=lambda x: x) @@ -146,7 +136,6 @@ def test_url_invalid_object(self): with app.test_request_context("/"): self.assertRaises(MarshallingException, lambda: field.output("hey", None)) - def test_url(self): app = Flask(__name__) app.add_url_rule("/", "foobar", view_func=lambda x: x) @@ -155,7 +144,6 @@ def test_url(self): with app.test_request_context("/"): self.assertEquals("/3", field.output("hey", Foo())) - def test_url_absolute(self): app = Flask(__name__) app.add_url_rule("/", "foobar", view_func=lambda x: x) @@ -177,12 +165,10 @@ def test_int(self): field = fields.Integer() self.assertEquals(3, field.output("hey", {'hey': 3})) - def test_int_default(self): field = fields.Integer(default=1) self.assertEquals(1, field.output("hey", {'hey': None})) - def test_no_int(self): field = fields.Integer() self.assertEquals(0, field.output("hey", {'hey': None})) @@ -225,7 +211,6 @@ def test_infinite_fixed(self): self.assertRaises(MarshallingException, lambda: field.output("hey", {'hey': '+inf'})) self.assertRaises(MarshallingException, lambda: field.output("hey", {'hey': '-inf'})) - def test_advanced_fixed(self): field = fields.Fixed() self.assertRaises(MarshallingException, lambda: field.output("hey", {'hey': 'NaN'})) @@ -234,33 +219,27 @@ def test_fixed_with_attribute(self): field = fields.Fixed(4, attribute="bar") self.assertEquals('3.0000', field.output("foo", {'bar': '3'})) - def test_string(self): field = fields.String() self.assertEquals("3", field.output("hey", Foo())) - def test_string_no_value(self): field = fields.String() self.assertEquals(None, field.output("bar", Foo())) - def test_string_none(self): field = fields.String() self.assertEquals(None, field.output("empty", {'empty': None})) - def test_date_field_with_offset(self): obj = {"bar": datetime(2011, 8, 22, 20, 58, 45)} field = fields.DateTime() self.assertEquals("Mon, 22 Aug 2011 20:58:45 -0000", field.output("bar", obj)) - def test_to_dict(self): obj = {"hey": 3} self.assertEquals(obj, fields.to_marshallable_type(obj)) - def test_to_dict_obj(self): obj = {"hey": 3} self.assertEquals(obj, fields.to_marshallable_type(Foo())) @@ -272,11 +251,9 @@ def test_to_dict_custom_marshal(self): def test_get_value(self): self.assertEquals(3, fields.get_value("hey", {"hey": 3})) - def test_get_value_no_value(self): self.assertEquals(None, fields.get_value("foo", {"hey": 3})) - def test_get_value_obj(self): self.assertEquals(3, fields.get_value("hey", Foo())) @@ -318,6 +295,7 @@ def test_indexable_object(self): class TestObject(object): def __init__(self, foo): self.foo = foo + def __getitem__(self, n): if type(n) is int: if n < 3: diff --git a/tests/test_reqparse.py b/tests/test_reqparse.py index dd265655..a73b7ca3 100644 --- a/tests/test_reqparse.py +++ b/tests/test_reqparse.py @@ -10,12 +10,12 @@ import json + class ReqParseTestCase(unittest.TestCase): def test_default_help(self): arg = Argument("foo") self.assertEquals(arg.help, None) - @patch('flask_restful.abort') def test_help(self, abort): from werkzeug.datastructures import MultiDict @@ -37,29 +37,24 @@ def bad_choice(): parser.parse_args(req) abort.assert_called_with(400, message='three is not a valid choice') - self.assertRaises(exceptions.BadRequest, bad_choice) def test_name(self): arg = Argument("foo") self.assertEquals(arg.name, "foo") - def test_dest(self): arg = Argument("foo", dest="foobar") self.assertEquals(arg.dest, "foobar") - def test_location_url(self): arg = Argument("foo", location="url") self.assertEquals(arg.location, "url") - def test_location_url_list(self): arg = Argument("foo", location=["url"]) self.assertEquals(arg.location, ["url"]) - def test_location_header(self): arg = Argument("foo", location="headers") self.assertEquals(arg.location, "headers") @@ -76,52 +71,42 @@ def test_location_header_list(self): arg = Argument("foo", location=["headers"]) self.assertEquals(arg.location, ["headers"]) - def test_type(self): arg = Argument("foo", type=int) self.assertEquals(arg.type, int) - def test_default(self): arg = Argument("foo", default=True) self.assertEquals(arg.default, True) - def test_required(self): arg = Argument("foo", required=True) self.assertEquals(arg.required, True) - def test_ignore(self): arg = Argument("foo", ignore=True) self.assertEquals(arg.ignore, True) - def test_operator(self): arg = Argument("foo", operators=[">=", "<=", "="]) self.assertEquals(arg.operators, [">=", "<=", "="]) - def test_action_filter(self): arg = Argument("foo", action="filter") self.assertEquals(arg.action, u"filter") - def test_action(self): arg = Argument("foo", action="append") self.assertEquals(arg.action, u"append") - def test_choices(self): arg = Argument("foo", choices=[1, 2]) self.assertEquals(arg.choices, [1, 2]) - def test_default_dest(self): arg = Argument("foo") self.assertEquals(arg.dest, None) - def test_default_operators(self): arg = Argument("foo") self.assertEquals(arg.operators[0], "=") @@ -134,32 +119,26 @@ def test_default_type(self, mock_six): arg.type(sentinel) mock_six.text_type.assert_called_with(sentinel) - def test_default_default(self): arg = Argument("foo") self.assertEquals(arg.default, None) - def test_required_default(self): arg = Argument("foo") self.assertEquals(arg.required, False) - def test_ignore_default(self): arg = Argument("foo") self.assertEquals(arg.ignore, False) - def test_action_default(self): arg = Argument("foo") self.assertEquals(arg.action, u"store") - def test_choices_default(self): arg = Argument("foo") self.assertEquals(len(arg.choices), 0) - def test_source(self): req = Mock(['args', 'headers', 'values']) req.args = {'foo': 'bar'} @@ -170,20 +149,17 @@ def test_source(self): arg = Argument('foo', location=['headers']) self.assertEquals(arg.source(req), req.headers) - def test_source_bad_location(self): req = Mock(['values']) arg = Argument('foo', location=['foo']) self.assertTrue(len(arg.source(req)) == 0) # yes, basically you don't find it - def test_source_default_location(self): req = Mock(['values']) req._get_child_mock = lambda **kwargs: NonCallableMock(**kwargs) arg = Argument('foo') self.assertEquals(arg.source(req), req.values) - def test_option_case_sensitive(self): arg = Argument("foo", choices=["bar", "baz"], case_sensitive=True) self.assertEquals(True, arg.case_sensitive) @@ -196,7 +172,6 @@ def test_option_case_sensitive(self): arg = Argument("foo", choices=["bar", "baz"]) self.assertEquals(True, arg.case_sensitive) - def test_viewargs(self): req = Mock() req.view_args = {"foo": "bar"} @@ -214,7 +189,6 @@ def test_viewargs(self): args = parser.parse_args(req) self.assertEquals(args["foo"], None) - def test_parse_unicode(self): req = Request.from_values("/bubble?foo=barß") parser = RequestParser() @@ -223,7 +197,6 @@ def test_parse_unicode(self): args = parser.parse_args(req) self.assertEquals(args['foo'], u"barß") - def test_parse_unicode_app(self): app = Flask(__name__) @@ -234,7 +207,6 @@ def test_parse_unicode_app(self): args = parser.parse_args() self.assertEquals(args['foo'], u"barß") - def test_json_location(self): app = Flask(__name__) @@ -245,7 +217,6 @@ def test_json_location(self): args = parser.parse_args() self.assertEquals(args['foo'], None) - def test_get_json_location(self): app = Flask(__name__) @@ -258,7 +229,6 @@ def test_get_json_location(self): args = parser.parse_args() self.assertEquals(args['foo'], 'bar') - def test_parse_append_ignore(self): req = Request.from_values("/bubble?foo=bar") @@ -268,7 +238,6 @@ def test_parse_append_ignore(self): args = parser.parse_args(req) self.assertEquals(args['foo'], None) - def test_parse_append_default(self): req = Request.from_values("/bubble?") @@ -278,7 +247,6 @@ def test_parse_append_default(self): args = parser.parse_args(req) self.assertEquals(args['foo'], None) - def test_parse_append(self): req = Request.from_values("/bubble?foo=bar&foo=bat") @@ -297,7 +265,6 @@ def test_parse_append_single(self): args = parser.parse_args(req) self.assertEquals(args['foo'], ["bar"]) - def test_parse_dest(self): req = Request.from_values("/bubble?foo=bar") @@ -307,7 +274,6 @@ def test_parse_dest(self): args = parser.parse_args(req) self.assertEquals(args['bat'], "bar") - def test_parse_gte_lte_eq(self): req = Request.from_values("/bubble?foo>=bar&foo<=bat&foo=foo") @@ -317,7 +283,6 @@ def test_parse_gte_lte_eq(self): args = parser.parse_args(req) self.assertEquals(args['foo'], ["bar", "bat", "foo"]) - def test_parse_gte(self): req = Request.from_values("/bubble?foo>=bar") @@ -327,14 +292,12 @@ def test_parse_gte(self): args = parser.parse_args(req) self.assertEquals(args['foo'], "bar") - def test_parse_foo_operators_four_hunderd(self): parser = RequestParser() parser.add_argument("foo", type=int), self.assertRaises(exceptions.BadRequest, lambda: parser.parse_args(Request.from_values("/bubble?foo=bar"))) - def test_parse_foo_operators_ignore(self): parser = RequestParser() parser.add_argument("foo", ignore=True) @@ -342,7 +305,6 @@ def test_parse_foo_operators_ignore(self): args = parser.parse_args(Request.from_values("/bubble")) self.assertEquals(args['foo'], None) - def test_parse_lte_gte_mock(self): mock_type = Mock() req = Request.from_values("/bubble?foo<=bar") @@ -353,7 +315,6 @@ def test_parse_lte_gte_mock(self): parser.parse_args(req) mock_type.assert_called_with("bar", "foo", "<=") - def test_parse_lte_gte_append(self): parser = RequestParser() parser.add_argument("foo", operators=["<=", "="], action="append") @@ -361,21 +322,18 @@ def test_parse_lte_gte_append(self): args = parser.parse_args(Request.from_values("/bubble?foo<=bar")) self.assertEquals(args['foo'], ["bar"]) - def test_parse_lte_gte_missing(self): parser = RequestParser() parser.add_argument("foo", operators=["<=", "="]) args = parser.parse_args(Request.from_values("/bubble?foo<=bar")) self.assertEquals(args['foo'], "bar") - def test_parse_eq_other(self): parser = RequestParser() parser.add_argument("foo"), args = parser.parse_args(Request.from_values("/bubble?foo=bar&foo=bat")) self.assertEquals(args['foo'], "bar") - def test_parse_eq(self): req = Request.from_values("/bubble?foo=bar") parser = RequestParser() @@ -383,7 +341,6 @@ def test_parse_eq(self): args = parser.parse_args(req) self.assertEquals(args['foo'], "bar") - def test_parse_lte(self): req = Request.from_values("/bubble?foo<=bar") parser = RequestParser() @@ -392,7 +349,6 @@ def test_parse_lte(self): args = parser.parse_args(req) self.assertEquals(args['foo'], "bar") - def test_parse_required(self): req = Request.from_values("/bubble") @@ -420,7 +376,6 @@ def test_parse_required(self): "post body or the query string or the " "request's cookies")) - def test_parse_default_append(self): req = Request.from_values("/bubble") parser = RequestParser() @@ -430,7 +385,6 @@ def test_parse_default_append(self): self.assertEquals(args['foo'], "bar") - def test_parse_default(self): req = Request.from_values("/bubble") @@ -440,7 +394,6 @@ def test_parse_default(self): args = parser.parse_args(req) self.assertEquals(args['foo'], "bar") - def test_parse_callable_default(self): req = Request.from_values("/bubble") @@ -450,7 +403,6 @@ def test_parse_callable_default(self): args = parser.parse_args(req) self.assertEquals(args['foo'], "bar") - def test_parse(self): req = Request.from_values("/bubble?foo=bar") @@ -460,7 +412,6 @@ def test_parse(self): args = parser.parse_args(req) self.assertEquals(args['foo'], "bar") - def test_parse_none(self): req = Request.from_values("/bubble") @@ -470,7 +421,6 @@ def test_parse_none(self): args = parser.parse_args(req) self.assertEquals(args['foo'], None) - def test_parse_choices_correct(self): req = Request.from_values("/bubble?foo=bat") @@ -480,7 +430,6 @@ def test_parse_choices_correct(self): args = parser.parse_args(req) self.assertEquals(args['foo'], "bat") - def test_parse_choices(self): req = Request.from_values("/bubble?foo=bar") @@ -497,7 +446,6 @@ def test_parse_choices_sensitive(self): self.assertRaises(exceptions.BadRequest, lambda: parser.parse_args(req)) - def test_parse_choices_insensitive(self): req = Request.from_values("/bubble?foo=BAT") @@ -507,7 +455,6 @@ def test_parse_choices_insensitive(self): args = parser.parse_args(req) self.assertEquals('bat', args.get('foo')) - def test_parse_ignore(self): req = Request.from_values("/bubble?foo=bar") diff --git a/tests/test_types.py b/tests/test_types.py index 277e71d9..930758a2 100644 --- a/tests/test_types.py +++ b/tests/test_types.py @@ -2,7 +2,7 @@ import unittest #noinspection PyUnresolvedReferences -from nose.tools import assert_equal, assert_raises # you need it for tests in form of continuations +from nose.tools import assert_equal, assert_raises # you need it for tests in form of continuations import pytz import six @@ -25,17 +25,19 @@ def tzname(self, dt): def dst(self, dt): return ZERO + def test_datetime_formatters(): dates = [ (datetime(2011, 1, 1), "Sat, 01 Jan 2011 00:00:00 -0000"), (datetime(2011, 1, 1, 23, 59, 59), "Sat, 01 Jan 2011 23:59:59 -0000"), (datetime(2011, 1, 1, 23, 59, 59, tzinfo=UTC()), - "Sat, 01 Jan 2011 23:59:59 -0000"), - ] + "Sat, 01 Jan 2011 23:59:59 -0000"), + ] for date_obj, expected in dates: yield assert_equal, types.rfc822(date_obj), expected + def test_urls(): urls = [ 'http://www.djangoproject.com/', @@ -54,11 +56,12 @@ def test_urls(): 'http://foo:@example.com', 'http://foo:@2001:db8:85a3::8a2e:370:7334', 'http://foo2:qd1%r@example.com', - ] + ] for value in urls: yield assert_equal, types.url(value), value + def check_bad_url_raises(value): try: types.url(value) @@ -66,6 +69,7 @@ def check_bad_url_raises(value): except ValueError as e: assert_equal(six.text_type(e), u"{0} is not a valid URL".format(value)) + def test_bad_urls(): values = [ 'foo', @@ -87,6 +91,7 @@ def test_bad_urls(): for value in values: yield check_bad_url_raises, value + def test_bad_url_error_message(): values = [ 'google.com', @@ -98,13 +103,14 @@ def test_bad_url_error_message(): for value in values: yield check_url_error_message, value + def check_url_error_message(value): try: types.url(value) assert False, u"types.url({0}) should raise an exception".format(value) except ValueError as e: assert_equal(six.text_type(e), - (u"{0} is not a valid URL. Did you mean: http://{0}".format(value))) + (u"{0} is not a valid URL. Did you mean: http://{0}".format(value))) class TypesTestCase(unittest.TestCase): @@ -112,31 +118,24 @@ class TypesTestCase(unittest.TestCase): def test_boolean_false(self): assert_equal(types.boolean("False"), False) - def test_boolean_true(self): assert_equal(types.boolean("true"), True) - def test_boolean_upper_case(self): assert_equal(types.boolean("FaLSE"), False) - def test_boolean(self): assert_equal(types.boolean("FaLSE"), False) - def test_bad_boolean(self): assert_raises(ValueError, lambda: types.boolean("blah")) - def test_date_later_than_1900(self): assert_equal(types.date("1900-01-01"), datetime(1900, 1, 1)) - def test_date_too_early(self): assert_raises(ValueError, lambda: types.date("0001-01-01")) - def test_date_input_error(self): assert_raises(ValueError, lambda: types.date("2008-13-13"))