How To Test A Connexion/flask App?
I'm using the Connexion framework for Flask to build a microservice. I would like to write tests for my application using py.test. In the pytest-flask doc it says to create a fixtu
Solution 1:
Using fixtures
test_api.py
import pytest
import connexion
flask_app = connexion.FlaskApp(__name__)
flask_app.add_api('swagger.yml')
@pytest.fixture(scope='module')defclient():
with flask_app.app.test_client() as c:
yield c
deftest_health(client):
response = client.get('/health')
assert response.status_code == 200
swagger.yml
swagger:'2.0'info:title:MyAPIversion:'1.0'consumes:-application/jsonproduces:-application/jsonschemes:-httpspaths:/health:get:tags: [Health]
operationId:api.healthsummary:HealthCheckresponses:'200':description:Statusmessagefromserverdescribingcurrenthealth
api.py
def health():
return {'msg': 'ok'}, 200
Using Swagger Tester
Another solution using swagger-tester:
test_api.py
from swagger_tester importswagger_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.
Solution 2:
import pytest
from json import JSONEncoder
import pytest
from connexion import App
SWAGGER_PATH = "path_to_directory_that_containes_swagger_file"@pytest.fixturedefapp():
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_client
deftest_health(app) -> None:
"""
:except: success
"""
response = app.get("/health", content_type='application/json')
assert response.status_code == 200
For more info check this.
Post a Comment for "How To Test A Connexion/flask App?"