Example #1
0
def test_shared_schema_override():
    docs = """
    Hello World

    $shared:
        x: int&min=0
    """
    app = Flask(__name__)
    api = Api(app, docs=docs)

    class Hello:
        """
        $shared:
            x: int&max=0
        """

        def get(self, x):
            """
            $input:
                x@x: x
            """
            return {'x': x}

    api.add_resource(Hello)
    with app.test_client() as c:
        resp = c.get("/hello?x=1")
        assert resp.status_code == 400
        resp = c.get("/hello?x=-1")
        assert resp.status_code == 200
        assert resp_json(resp) == {"x": -1}
Example #2
0
def test_validators():

    @handle_default_optional_desc()
    def even_validator():
        def validator(value):
            try:
                i = int(value)
            except:
                raise Invalid("invalid int")
            if i % 2 == 0:
                return i
            else:
                raise Invalid("not even number")
        return validator

    app = Flask(__name__)
    api = Api(app, validators={"even": even_validator})

    class Test:

        def get(self, number):
            """
            $input:
                number?even: even number
            """
            return {
                "number": number
            }
    api.add_resource(Test)
    with app.test_client() as c:
        resp = c.get("/test?number=2")
        assert resp.status_code == 200
        resp = c.get("/test?number=3")
        assert resp.status_code == 400
        assert resp_json(resp)["error"] == "InvalidData"
Example #3
0
def test_input_output_schema():
    app = Flask(__name__)
    api = Api(app)

    class Welcome:

        def __init__(self, userid):
            self.userid = userid
            self.message = "Hi, %d" % userid

    class Hello:

        def get(self, userid):
            """Get hello

            $input:
                userid?int: UserID
            $output:
                message?str: Welcome message
            """
            return {"message": "Hi, %d" % userid}

        def post(self, userid):
            """Get hello

            $input:
                userid?int: UserID
            $output:
                message?str: Welcome message
            """
            return Welcome(userid)

    api.add_resource(Hello)

    with app.test_client() as c:
        resp = c.get("/hello?userid=123")
        assert resp.status_code == 200
        assert resp_json(resp) == {"message": "Hi, 123"}

        resp = c.post("/hello", data={"userid": 123})
        assert resp.status_code == 200
        assert resp_json(resp) == {"message": "Hi, 123"}

        headers = {"Content-Type": "application/json"}
        resp = c.post("/hello", data='{"userid": 123}', headers=headers)
        assert resp.status_code == 200
        assert resp_json(resp) == {"message": "Hi, 123"}
Example #4
0
def test_docs_and_shared_schema():
    docs = """
    Hello World

    $shared:
        userid: int&min=0
    """
    app = Flask(__name__)
    api = Api(app, docs=docs)
    assert api.meta["$desc"] == "Hello World"
    assert api.meta["$shared"] == {"userid": "int&min=0"}

    class Hello:
        """
        docstring for Hello

        $shared:
            name: str
        """

        def get(self, userid, name):
            """
            Test shared schema

            $input:
                userid@userid: UserID
                name@name: UserName
            """
            return {
                "userid": userid,
                "name": name
            }
    api.add_resource(Hello)

    with app.test_client() as c:
        resp = c.get("/hello?userid=123&name=kk")
        assert resp.status_code == 200
        assert resp_json(resp) == {
            "userid": 123,
            "name": "kk"
        }
        resp = c.get("/hello?userid=abc&name=kk")
        assert resp.status_code == 400
        assert resp_json(resp)["error"] == "InvalidData"
        assert "userid" in resp_json(resp)["message"]
Example #5
0
def test_abort():
    app = Flask(__name__)

    @app.route("/")
    def index():
        abort(400, "AbortTest")

    @app.route("/flask")
    def flask_abort():
        abort(400)

    @app.route("/response")
    def response():
        resp = jsonify({"reason": "error reason"})
        abort(403, resp)

    @app.route("/message")
    def message():
        abort(403, "AbortMessage", "message")

    with app.test_client() as c:
        resp = c.get("/")
        assert resp.status_code == 400
        assert resp_json(resp) == {
            "status": 400,
            "error": "AbortTest",
            "message": None
        }
        resp = c.get("/flask")
        assert resp.status_code == 400
        assert resp.mimetype == "text/html"
        resp = c.get("/response")
        assert resp.status_code == 403
        assert resp_json(resp) == {"reason": "error reason"}
        resp = c.get("/message")
        assert resp.status_code == 403
        assert resp_json(resp) == {
            "status": 403,
            "error": "AbortMessage",
            "message": "message"
        }
Example #6
0
def test_metafile(tmpdir):
    metafile = tmpdir.join("meta.json")
    json.dump({"$xxx": "test", "$roles": {}}, metafile.open("w"))
    app = Flask(__name__)
    api = Api(app, metafile=metafile.strpath)

    class Hello:
        """docstring for Hello"""

        def get(self):
            """Get hello"""
    api.add_resource(Hello)
    app.route('/')(api.meta_view)

    with app.test_client() as c:
        resp = c.get("/", headers={'Accept': 'application/json'})
        assert resp.status_code == 200
        assert resp_json(resp)["$xxx"] == "test"
        assert resp_json(resp)["$roles"] == {}
        assert resp_json(resp)["hello"]["$desc"] == "docstring for Hello"
        assert resp_json(resp)["hello"]["get"]["$desc"] == "Get hello"
Example #7
0
def test_blueprint():
    class Hello:
        """Blueprint test"""

        def get(self, name):
            """
            Get Hello world message

            $input:
                name?str: Your name
            """
            return {'message': 'Hello %s' % name}

        def get_message(self):
            pass

    app = Flask(__name__)
    bp = Blueprint('blueprint', __name__)
    api = Api(bp)
    api.add_resource(Hello)
    app.register_blueprint(bp, url_prefix='/api')

    with app.test_request_context('/api/hello'):
        assert request.endpoint == 'blueprint.hello'
        assert url_for('blueprint.hello') == '/api/hello'

    with app.test_request_context('/api/hello/message'):
        assert request.endpoint == 'blueprint.hello@message'
        assert url_for('blueprint.hello@message') == '/api/hello/message'

    with app.test_client() as c:
        resp = c.get('/api/hello?name=kk')
        assert resp.status_code == 200
        assert resp_json(resp) == {
            "message": "Hello kk"
        }

        resp = c.get('/api/hello')
        assert resp.status_code == 400
        assert resp_json(resp)["error"] == "InvalidData"
Example #8
0
def test_auth(tmpdir):
    app = create_app(tmpdir)
    with app.test_client() as c:
        resp = c.get("/hello")
        assert resp.status_code == 403
        assert resp_json(resp)["error"] == "PermissionDeny"
        assert "guest" in resp_json(resp)["message"]

        resp = c.post("/hello", data={"name": "abc"})
        assert resp.status_code == 200
        headers = {AUTH_HEADER: resp.headers[AUTH_HEADER]}
        resp = c.get("/hello", headers=headers)
        assert resp.status_code == 403
        assert resp_json(resp)["error"] == "PermissionDeny"
        assert "normal" in resp_json(resp)["message"]

        resp = c.post("/hello", data={"name": "admin"})
        assert resp.status_code == 200
        headers = {AUTH_HEADER: resp.headers[AUTH_HEADER]}
        resp = c.get("/hello", headers=headers)
        assert resp.status_code == 200
        assert resp_json(resp) == {"name": "admin"}
Example #9
0
def test_auth(tmpdir):
    app = create_app(tmpdir)
    with app.test_client() as c:
        resp = c.get("/hello")
        assert resp.status_code == 403
        assert resp_json(resp)["error"] == "PermissionDeny"
        assert "guest" in resp_json(resp)["message"]

        resp = c.post("/hello", data={"name": "abc"})
        assert resp.status_code == 200
        headers = {AUTH_HEADER: resp.headers[AUTH_HEADER]}
        resp = c.get("/hello", headers=headers)
        assert resp.status_code == 403
        assert resp_json(resp)["error"] == "PermissionDeny"
        assert "normal" in resp_json(resp)["message"]

        resp = c.post("/hello", data={"name": "admin"})
        assert resp.status_code == 200
        headers = {AUTH_HEADER: resp.headers[AUTH_HEADER]}
        resp = c.get("/hello", headers=headers)
        assert resp.status_code == 200
        assert resp_json(resp) == {"name": "admin"}
Example #10
0
def test_no_output_schema():
    app = Flask(__name__)
    api = Api(app)

    class Hello:

        def get(self, userid):
            """Get hello

            $input:
                userid?int: UserID
            """
            return {"message": userid}
    api.add_resource(Hello)

    with app.test_client() as c:
        resp = c.get("/hello?userid=123")
        assert resp.status_code == 200
        assert resp_json(resp) == {
            "message": 123
        }
        resp = c.get("/hello?userid=kk")
        assert resp.status_code == 400
        assert resp_json(resp)["error"] == "InvalidData"
Example #11
0
def test_error_handler():
    app = Flask(__name__)
    api = Api(app)

    class Hello:

        def get(self):
            raise ValueError("bug")
    api.add_resource(Hello)

    @api.error_handler
    def error_handler(ex):
        return "error_handler %s" % ex.args[0]

    with app.test_client() as c:
        resp = c.get("/hello")
        assert resp.status_code == 200
        assert resp_json(resp) == "error_handler bug"
Example #12
0
def test_after_request():
    app = Flask(__name__)
    api = Api(app)

    class Hello:

        def get(self):
            return "Hello World"
    api.add_resource(Hello)

    @api.after_request
    def after_request(rv, code, headers):
        return "%s after_request" % rv, code, headers

    with app.test_client() as c:
        resp = c.get("/hello")
        assert resp.status_code == 200
        assert resp_json(resp) == "Hello World after_request"
Example #13
0
def test_before_request():
    app = Flask(__name__)
    api = Api(app)

    class Hello:

        def get(self):
            return "Hello World"
    api.add_resource(Hello)

    @api.before_request
    def before_request():
        return "before_request"

    with app.test_client() as c:
        resp = c.get("/hello")
        assert resp.status_code == 200
        assert resp_json(resp) == "before_request"
Example #14
0
def test_no_schema():
    app = Flask(__name__)
    api = Api(app)

    class Hello:

        def get(self):
            """
            Get hello

            Welcome
            """
            return {}
    api.add_resource(Hello)

    with app.test_client() as c:
        resp = c.get("/hello?name=kk")
        assert resp.status_code == 200
        assert resp_json(resp) == {}
Example #15
0
def test_export(rv, code, headers):
    app = Flask(__name__)
    with app.test_request_context("/"):

        resp = export(rv)
        assert resp.status_code == 200

        resp = export(rv, code)
        assert resp.mimetype == "application/json"
        assert resp.status_code == code
        assert resp_json(resp) == rv

        if headers is not None:
            resp = export(rv, None, headers)
            if isinstance(headers, dict):
                for k, v in headers.items():
                    assert resp.headers[k] == v
            else:
                for k, v in headers:
                    assert resp.headers[k] == v
Example #16
0
def test_no_input_schema():
    app = Flask(__name__)
    api = Api(app)

    class Hello:

        def get(self):
            """
            Get hello

            $output:
                message?str: welcome message
            """
            return {}
    api.add_resource(Hello)

    with app.test_client() as c:
        resp = c.get("/hello?name=kk")
        assert resp.status_code == 500
        assert resp_json(resp)["error"] == "ServerError"
Example #17
0
def test_shared_schema_order():
    docs = """
    Hello World

    $shared:
        a: int
        b: "@a"
    """
    app = Flask(__name__)
    api = Api(app, docs=docs)

    class Hello:
        """
        $shared:
            c: str
            d: "@c"
            e: "@b"
        """

        def get(self, x, y, z):
            """
            $input:
                x@b: x
                y@d: y
                z@e: z
            """
            return {'x': x, 'y': y, 'z': z}

    api.add_resource(Hello)
    with app.test_client() as c:
        resp = c.get("/hello?x=123&y=kk&z=321")
        assert resp.status_code == 200
        assert resp_json(resp) == {
            "x": 123,
            "y": "kk",
            "z": 321
        }