How to test a Connexion/Flask app?
Using fixtures
test_api.py
import pytestimport connexionflask_app = connexion.FlaskApp(__name__)flask_app.add_api('swagger.yml')@pytest.fixture(scope='module')def client(): with flask_app.app.test_client() as c: yield cdef test_health(client): response = client.get('/health') assert response.status_code == 200
swagger.yml
swagger: '2.0'info: title: My API version: '1.0'consumes: - application/jsonproduces: - application/jsonschemes: - httpspaths: /health: get: tags: [Health] operationId: api.health summary: Health Check responses: '200': description: Status message from server describing current health
api.py
def health(): return {'msg': 'ok'}, 200
Using Swagger Tester
Another solution using swagger-tester:
test_api.py
from swagger_tester import swagger_testauthorize_error = { 'get': { '/health': [200], }}def test_swagger(): swagger_test('swagger.yml', authorize_error=authorize_error)
Cool thing about this library is that you can use the examples provided in your spec. But I don't think it works out of the box with connexion.RestyResolver
: you'll have to specify the OperationId at each endpoint.
import pytestfrom json import JSONEncoderimport pytestfrom connexion import AppSWAGGER_PATH = "path_to_directory_that_containes_swagger_file"@pytest.fixturedef app(): app = App(__name__, specification_dir=SWAGGER_PATH) app.app.json_encoder = JSONEncoder app.add_api("swagger.yaml") app_client = app.app.test_client() return app_clientdef test_health(app) -> None: """ :except: success """ response = app.get("/health", content_type='application/json') assert response.status_code == 200
For more info check this.