How to test a Connexion/Flask app?

import pytest
from json import JSONEncoder
import pytest
from connexion import App

SWAGGER_PATH = "path_to_directory_that_containes_swagger_file"

@pytest.fixture
def 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_client


def test_health(app) -> None:
    """
    :except: success
    """
    response = app.get("/health", content_type='application/json')
    assert response.status_code == 200

For more info check this.


Using fixtures

test_api.py

import pytest
import connexion

flask_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 c


def 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/json
produces:
  - application/json
schemes:
  - https
paths:
  /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_test

authorize_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.