Add response schema validation (only when in TESTING mode) and add one schema. More will be added in a followup CL

This commit is contained in:
Joseph Schorr 2014-08-27 20:57:46 -04:00
parent 4fd249589d
commit 6f1a4030b6
3 changed files with 78 additions and 4 deletions

View file

@ -1,6 +1,7 @@
import logging
import json
from app import app
from flask import Blueprint, request, make_response, jsonify
from flask.ext.restful import Resource, abort, Api, reqparse
from flask.ext.restful.utils.cors import crossdomain
@ -52,6 +53,11 @@ class InvalidRequest(ApiException):
ApiException.__init__(self, 'invalid_request', 400, error_description, payload)
class InvalidResponse(ApiException):
def __init__(self, error_description, payload=None):
ApiException.__init__(self, 'invalid_response', 500, error_description, payload)
class InvalidToken(ApiException):
def __init__(self, error_description, payload=None):
ApiException.__init__(self, 'invalid_token', 401, error_description, payload)
@ -286,6 +292,25 @@ def validate_json_request(schema_name):
return wrapper
def define_json_response(schema_name):
def wrapper(func):
@add_method_metadata('response_schema', schema_name)
@wraps(func)
def wrapped(self, *args, **kwargs):
schema = self.schemas[schema_name]
try:
resp = func(self, *args, **kwargs)
if app.config['TESTING']:
validate(resp, schema)
return resp
except ValidationError as ex:
raise InvalidResponse(ex.message)
return wrapped
return wrapper
def request_error(exception=None, **kwargs):
data = kwargs.copy()
message = 'Request error.'