|
| 1 | +from json import dumps |
| 2 | + |
| 3 | +import pytest |
| 4 | +from flask import Flask |
| 5 | +from flask.testing import FlaskClient |
| 6 | +from flask.wrappers import Response |
| 7 | + |
| 8 | +from openapi_core.contrib.flask import FlaskOpenAPIRequest |
| 9 | +from openapi_core.validation.request import openapi_request_validator |
| 10 | + |
| 11 | + |
| 12 | +class TestWerkzeugOpenAPIValidation: |
| 13 | + @pytest.fixture |
| 14 | + def spec(self, factory): |
| 15 | + specfile = "contrib/requests/data/v3.0/requests_factory.yaml" |
| 16 | + return factory.spec_from_file(specfile) |
| 17 | + |
| 18 | + @pytest.fixture |
| 19 | + def app(self): |
| 20 | + app = Flask("__main__", root_path="/browse") |
| 21 | + app.config["DEBUG"] = True |
| 22 | + app.config["TESTING"] = True |
| 23 | + return app |
| 24 | + |
| 25 | + @pytest.fixture |
| 26 | + def details_view_func(self, spec): |
| 27 | + def datails_browse(id): |
| 28 | + from flask import request |
| 29 | + |
| 30 | + openapi_request = FlaskOpenAPIRequest(request) |
| 31 | + result = openapi_request_validator.validate(spec, openapi_request) |
| 32 | + assert not result.errors |
| 33 | + |
| 34 | + if request.args.get("q") == "string": |
| 35 | + return Response( |
| 36 | + dumps({"data": "data"}), |
| 37 | + headers={"X-Rate-Limit": "12"}, |
| 38 | + mimetype="application/json", |
| 39 | + status=200, |
| 40 | + ) |
| 41 | + else: |
| 42 | + return Response("Not Found", status=404) |
| 43 | + |
| 44 | + return datails_browse |
| 45 | + |
| 46 | + @pytest.fixture(autouse=True) |
| 47 | + def view(self, app, details_view_func): |
| 48 | + app.add_url_rule( |
| 49 | + "/<id>/", |
| 50 | + view_func=details_view_func, |
| 51 | + methods=["POST"], |
| 52 | + ) |
| 53 | + |
| 54 | + @pytest.fixture |
| 55 | + def client(self, app): |
| 56 | + return FlaskClient(app) |
| 57 | + |
| 58 | + def test_request_validator_root_path(self, client): |
| 59 | + query_string = { |
| 60 | + "q": "string", |
| 61 | + } |
| 62 | + headers = {"content-type": "application/json"} |
| 63 | + data = {"param1": 1} |
| 64 | + result = client.post( |
| 65 | + "/12/", |
| 66 | + base_url="http://localhost/browse", |
| 67 | + query_string=query_string, |
| 68 | + json=data, |
| 69 | + headers=headers, |
| 70 | + ) |
| 71 | + |
| 72 | + assert result.status_code == 200 |
| 73 | + assert result.json == {"data": "data"} |
0 commit comments