def test_validator_map(json_validation_spec_dir, spec):
    def validate_type(validator, types, instance, schema):
        types = _utils.ensure_list(types)
        errors = Draft4RequestValidator.VALIDATORS['type'](validator, types, instance, schema)
        yield from errors

        if 'string' in types and 'minLength' not in schema:
            errors = Draft4RequestValidator.VALIDATORS['minLength'](validator, 1, instance, schema)
            yield from errors

    MinLengthRequestValidator = extend(Draft4RequestValidator, {'type': validate_type})

    class MyRequestBodyValidator(RequestBodyValidator):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, validator=MinLengthRequestValidator, **kwargs)

    validator_map = {'body': MyRequestBodyValidator}

    app = App(__name__, specification_dir=json_validation_spec_dir)
    app.add_api(spec, validate_responses=True, validator_map=validator_map)
    app_client = app.app.test_client()

    res = app_client.post('/v1.0/minlength', data=json.dumps({'foo': 'bar'}), content_type='application/json') # type: flask.Response
    assert res.status_code == 200

    res = app_client.post('/v1.0/minlength', data=json.dumps({'foo': ''}), content_type='application/json') # type: flask.Response
    assert res.status_code == 400
def test_validator_map(json_validation_spec_dir, spec):
    def validate_type(validator, types, instance, schema):
        types = _utils.ensure_list(types)
        errors = Draft4RequestValidator.VALIDATORS['type'](validator, types, instance, schema)
        for e in errors:
            yield e

        if 'string' in types and 'minLength' not in schema:
            errors = Draft4RequestValidator.VALIDATORS['minLength'](validator, 1, instance, schema)
            for e in errors:
                yield e

    MinLengthRequestValidator = extend(Draft4RequestValidator, {'type': validate_type})

    class MyRequestBodyValidator(RequestBodyValidator):
        def __init__(self, *args, **kwargs):
            super(MyRequestBodyValidator, self).__init__(*args, validator=MinLengthRequestValidator, **kwargs)

    validator_map = {'body': MyRequestBodyValidator}

    app = App(__name__, specification_dir=json_validation_spec_dir)
    app.add_api(spec, validate_responses=True, validator_map=validator_map)
    app_client = app.app.test_client()

    res = app_client.post('/v1.0/minlength', data=json.dumps({'foo': 'bar'}), content_type='application/json') # type: flask.Response
    assert res.status_code == 200

    res = app_client.post('/v1.0/minlength', data=json.dumps({'foo': ''}), content_type='application/json') # type: flask.Response
    assert res.status_code == 400
Exemple #3
0
def get_app():
    app = App(__name__, specification_dir="./openapi/")
    app.app.json_encoder = JSONEncoder
    app.add_api("openapi.yaml",
                arguments={"title": "Ibutsu"},
                base_path="/api",
                pythonic_params=True)
    CORS(app.app)
    FlaskDynaconf(app.app)

    @app.route("/")
    def index():
        return redirect("/api/ui/", code=302)

    @app.route("/admin/run-task", methods=["POST"])
    def run_task():
        params = request.get_json(force=True, silent=True)
        if not params:
            return "Bad request", 400
        task_path = params.get("task")
        task_params = params.get("params", {})
        if not task_path:
            return "Bad request", 400
        task_module, task_name = task_path.split(".", 2)
        try:
            mod = import_module(f"ibutsu_server.tasks.{task_module}")
        except ImportError:
            return "Not found", 404
        if not hasattr(mod, task_name):
            return "Not found", 404
        task = getattr(mod, task_name)
        task.delay(**task_params)
        return "Accepted", 202

    return app
Exemple #4
0
def __add_config_to_connexion_app(
    app: App,
    config: Mapping
) -> App:
    """Adds configuration to Flask app and replaces default Connexion and Flask
    settings."""
    # Replace Connexion app settings
    app.host = get_conf(config, 'server', 'host')
    app.port = get_conf(config, 'server', 'port')
    app.debug = get_conf(config, 'server', 'debug')

    # Replace Flask app settings
    app.app.config['DEBUG'] = app.debug
    app.app.config['ENV'] = get_conf(config, 'server', 'environment')
    app.app.config['TESTING'] = get_conf(config, 'server', 'testing')

    # Log Flask config
    logger.debug('Flask app settings:')
    for (key, value) in app.app.config.items():
        logger.debug('* {}: {}'.format(key, value))

    # Add user configuration to Flask app config
    app.app.config.update(config)

    logger.info('Connexion app configured.')
    return app
Exemple #5
0
def build_app(apis, host=_host, port=_port, server=_server, ui=_ui):
    app = App(__name__, host=host, port=port, server=server, swagger_ui=ui)

    for api in apis:
        app.add_api(api)

    return app
Exemple #6
0
def __add_config_to_connexion_app(
    app: App,
    config: Config,
) -> App:
    """Replace default Connexion and Flask app settings and add FOCA- and user-
    defined configuration parameters to Flask app.

    Args:
        app: Connexion app.
        config: App configuration.

    Returns:
        Connexion app.
    """
    conf = config.server

    # replace Connexion app settings
    app.host = conf.host
    app.port = conf.port
    app.debug = conf.debug

    # replace Flask app settings
    app.app.config['DEBUG'] = conf.debug
    app.app.config['ENV'] = conf.environment
    app.app.config['TESTING'] = conf.testing

    logger.debug('Flask app settings:')
    for (key, value) in app.app.config.items():
        logger.debug('* {}: {}'.format(key, value))

    # Add user configuration to Flask app config
    app.app.config['FOCA'] = config

    logger.debug('Connexion app configured.')
    return app
Exemple #7
0
def create_app() -> App:
    """:return: lazily created and initialized app"""

    new_app = App(__name__, specification_dir='swagger')
    setup_app(new_app.app)

    from ..flask_modules.connexion import SimpleResolver
    from .controller.ui import UI_BP, UI_NONAUTH_BP
    from .controller.landing import LANDING_BP
    from .controller.forwards import FORWARDS_BP
    from .controller import ui_api, twitter, eev

    new_app.app.register_blueprint(UI_NONAUTH_BP)
    new_app.app.register_blueprint(UI_BP)
    new_app.app.register_blueprint(FORWARDS_BP)
    new_app.app.register_blueprint(LANDING_BP)
    new_app.add_api('ui.yaml',
                    validate_responses=True,
                    resolver=SimpleResolver(ui_api))
    new_app.add_api('twitter.yaml',
                    validate_responses=True,
                    resolver=SimpleResolver(twitter))
    new_app.add_api('eev.yaml',
                    validate_responses=True,
                    resolver=SimpleResolver(eev))
    new_app.add_url_rule('/', 'health', lambda: 'ok', methods=['HEAD'])
    return new_app
def init_api_connexion(app: Flask) -> None:
    """Initialize Stable API"""
    base_path = '/api/v1'

    from airflow.www import views

    @app.errorhandler(404)
    @app.errorhandler(405)
    def _handle_api_error(ex):
        if request.path.startswith(base_path):
            # 404 errors are never handled on the blueprint level
            # unless raised from a view func so actual 404 errors,
            # i.e. "no route for it" defined, need to be handled
            # here on the application level
            return common_error_handler(ex)
        else:
            return views.not_found(ex)

    spec_dir = path.join(ROOT_APP_DIR, 'api_connexion', 'openapi')
    connexion_app = App(__name__,
                        specification_dir=spec_dir,
                        skip_error_handlers=True)
    connexion_app.app = app
    api_bp = connexion_app.add_api(specification='v1.yaml',
                                   base_path=base_path,
                                   validate_responses=True,
                                   strict_validation=True).blueprint
    # Like "api_bp.after_request", but the BP is already registered, so we have
    # to register it in the app directly.
    app.after_request_funcs.setdefault(api_bp.name,
                                       []).append(set_cors_headers_on_response)
    app.register_error_handler(ProblemException, common_error_handler)
    app.extensions['csrf'].exempt(api_bp)
Exemple #9
0
def test_handle_add_operation_error(simple_api_spec_dir):
    app = App(__name__, specification_dir=simple_api_spec_dir)
    app.api_cls = type('AppTest', (app.api_cls, ), {})
    app.api_cls.add_operation = mock.MagicMock(
        side_effect=Exception('operation error!'))
    with pytest.raises(Exception):
        app.add_api('swagger.yaml', resolver=lambda oid: (lambda foo: 'bar'))
Exemple #10
0
def app():
    cnx_app = App(__name__,
                  port=5001,
                  specification_dir=SPEC_FOLDER,
                  debug=True)
    cnx_app.add_api('api.yaml', validate_responses=True)
    return cnx_app
Exemple #11
0
def test_handle_add_operation_error_debug(simple_api_spec_dir):
    app = App(__name__, specification_dir=simple_api_spec_dir, debug=True)
    app.api_cls = type('AppTest', (app.api_cls,), {})
    app.api_cls.add_operation = mock.MagicMock(side_effect=Exception('operation error!'))
    api = app.add_api('swagger.yaml', resolver=lambda oid: (lambda foo: 'bar'))
    assert app.api_cls.add_operation.called
    assert api.resolver.resolve_function_from_operation_id('faux')('bah') == 'bar'
Exemple #12
0
def test_swagger_json_api(simple_api_spec_dir):
    """ Verify the swagger.json file is returned for default setting passed to api. """
    app = App(__name__, port=5001, specification_dir=simple_api_spec_dir, debug=True)
    app.add_api('swagger.yaml')

    app_client = app.app.test_client()
    swagger_json = app_client.get('/v1.0/swagger.json')  # type: flask.Response
    assert swagger_json.status_code == 200
Exemple #13
0
def create_app():
    connexion_app = App(
        'demo', specification_dir='swagger/', options={"swagger_ui": False}
    )
    connexion_app.add_api(
        'api.spec.yaml', validate_responses=True, strict_validation=True
    )
    return connexion_app
Exemple #14
0
def test_no_swagger_json_api(simple_api_spec_dir):
    """ Verify the swagger.json file is not returned when set to False when adding api. """
    app = App(__name__, port=5001, specification_dir=simple_api_spec_dir, debug=True)
    app.add_api('swagger.yaml', swagger_json=False)

    app_client = app.app.test_client()
    swagger_json = app_client.get('/v1.0/swagger.json')  # type: flask.Response
    assert swagger_json.status_code == 404
Exemple #15
0
def test_app_with_resolver(simple_api_spec_dir, spec):
    from connexion.resolver import Resolver
    resolver = Resolver()
    app = App(__name__, port=5001,
              specification_dir='..' / simple_api_spec_dir.relative_to(TEST_FOLDER),
              resolver=resolver)
    api = app.add_api(spec)
    assert api.resolver is resolver
Exemple #16
0
def test_no_swagger_json_api(simple_api_spec_dir, spec):
    """ Verify the spec json file is not returned when set to False when adding api. """
    app = App(__name__, port=5001, specification_dir=simple_api_spec_dir, debug=True)
    app.add_api(spec, options={"serve_spec": False})

    app_client = app.app.test_client()
    url = '/v1.0/{spec}'.format(spec=spec.replace("yaml", "json"))
    swagger_json = app_client.get(url)  # type: flask.Response
    assert swagger_json.status_code == 404
Exemple #17
0
def test_swagger_json_app(simple_api_spec_dir, spec):
    """ Verify the spec json file is returned for default setting passed to app. """
    app = App(__name__, port=5001, specification_dir=simple_api_spec_dir, debug=True)
    app.add_api(spec)
    app_client = app.app.test_client()
    url = '/v1.0/{spec}'
    url = url.format(spec=spec.replace("yaml", "json"))
    spec_json = app_client.get(url)  # type: flask.Response
    assert spec_json.status_code == 200
Exemple #18
0
def test_handle_add_operation_error_debug(simple_api_spec_dir):
    app = App(__name__, specification_dir=simple_api_spec_dir, debug=True)
    app.api_cls = type('AppTest', (app.api_cls, ), {})
    app.api_cls.add_operation = mock.MagicMock(
        side_effect=Exception('operation error!'))
    api = app.add_api('swagger.yaml', resolver=lambda oid: (lambda foo: 'bar'))
    assert app.api_cls.add_operation.called
    assert api.resolver.resolve_function_from_operation_id('faux')(
        'bah') == 'bar'
Exemple #19
0
def test_app_with_resolver(simple_api_spec_dir, spec):
    from connexion.resolver import Resolver
    resolver = Resolver()
    app = App(__name__,
              port=5001,
              specification_dir='..' /
              simple_api_spec_dir.relative_to(TEST_FOLDER),
              resolver=resolver)
    api = app.add_api(spec)
    assert api.resolver is resolver
def test_no_swagger_ui_config_json(simple_api_spec_dir, spec):
    """ Verify the swagger-ui-config.json file is not returned when the swagger_ui_config option not passed to app. """
    app = App(__name__,
              port=5001,
              specification_dir=simple_api_spec_dir,
              debug=True)
    app.add_api(spec)
    app_client = app.app.test_client()
    url = '/v1.0/ui/swagger-ui-config.json'
    swagger_ui_config_json = app_client.get(url)  # type: flask.Response
    assert swagger_ui_config_json.status_code == 404
Exemple #21
0
def test_app_with_relative_path(simple_api_spec_dir):
    # Create the app with a relative path and run the test_app testcase below.
    app = App(__name__, port=5001,
              specification_dir='..' / simple_api_spec_dir.relative_to(TEST_FOLDER),
              debug=True)
    app.add_api('swagger.yaml')

    app_client = app.app.test_client()
    get_bye = app_client.get('/v1.0/bye/jsantos')  # type: flask.Response
    assert get_bye.status_code == 200
    assert get_bye.data == b'Goodbye jsantos'
Exemple #22
0
def test_app_with_relative_path(simple_api_spec_dir, spec):
    # Create the app with a relative path and run the test_app testcase below.
    app = App(__name__, port=5001,
              specification_dir='..' / simple_api_spec_dir.relative_to(TEST_FOLDER),
              debug=True)
    app.add_api(spec)

    app_client = app.app.test_client()
    get_bye = app_client.get('/v1.0/bye/jsantos')  # type: flask.Response
    assert get_bye.status_code == 200
    assert get_bye.data == b'Goodbye jsantos'
Exemple #23
0
def build_app(apis, host=_host, port=_port, ui=_ui):
    app = App(__name__, host=host, port=port, server='flask', options={'swagger_ui': ui})

    for api in apis:
        app.add_api(api)

    app.app.config['APPINSIGHTS_INSTRUMENTATIONKEY'] = config.APPINSIGHTS_KEY
    app.app.config['APPINSIGHTS_ENDPOINT_URI'] = config.APPINSIGHTS_HOST
    app.app.config['APPINSIGHTS_DISABLE_TRACE_LOGGING'] = True
    AppInsights(app.app)

    return app
Exemple #24
0
def test_swagger_json_api(simple_api_spec_dir, spec):
    """ Verify the spec json file is returned for default setting passed to api. """
    app = App(__name__,
              port=5001,
              specification_dir=simple_api_spec_dir,
              debug=True)
    app.add_api(spec)

    app_client = app.app.test_client()
    url = '/v1.0/{spec}'.format(spec=spec.replace("yaml", "json"))
    swagger_json = app_client.get(url)  # type: flask.Response
    assert swagger_json.status_code == 200
Exemple #25
0
def build_app_from_fixture(api_spec_folder, **kwargs):
    debug = True
    if 'debug' in kwargs:
        debug = kwargs['debug']
        del (kwargs['debug'])

    cnx_app = App(__name__,
                  port=5001,
                  specification_dir=FIXTURES_FOLDER / api_spec_folder,
                  debug=debug)
    cnx_app.add_api('swagger.yaml', **kwargs)
    return cnx_app
Exemple #26
0
def create_app():
    connexion_app = App(
        'demo', specification_dir='swagger/', options={"swagger_ui": False}
    )
    connexion_app.add_api(
        'api.spec.yaml', validate_responses=True, strict_validation=True
    )

    prometheus_app = make_wsgi_app()
    dispatcher = DispatcherMiddleware(connexion_app, {"/metrics": prometheus_app})

    return dispatcher
def test_swagger_yaml_app(simple_api_spec_dir, spec):
    """ Verify the spec yaml file is returned for default setting passed to app. """
    app = App(__name__,
              port=5001,
              specification_dir=simple_api_spec_dir,
              debug=True)
    app.add_api(spec)
    app_client = app.app.test_client()
    url = '/v1.0/{spec}'
    url = url.format(spec=spec)
    spec_response = app_client.get(url)  # type: flask.Response
    assert spec_response.status_code == 200
Exemple #28
0
def test_no_swagger_json_api(simple_api_spec_dir, spec):
    """ Verify the spec json file is not returned when set to False when adding api. """
    app = App(__name__,
              port=5001,
              specification_dir=simple_api_spec_dir,
              debug=True)
    app.add_api(spec, options={"serve_spec": False})

    app_client = app.app.test_client()
    url = '/v1.0/{spec}'.format(spec=spec.replace("yaml", "json"))
    swagger_json = app_client.get(url)  # type: flask.Response
    assert swagger_json.status_code == 404
Exemple #29
0
def register_openapi(
    app: App,
    specs: List[Dict] = [],
    add_security_definitions: bool = True
) -> App:
    """Registers OpenAPI specs with Connexion app."""
    # Iterate over list of API specs
    for spec in specs:

        # Get _this_ directory
        path = os.path.join(
            os.path.abspath(
                os.path.dirname(
                    os.path.realpath(__file__)
                )
            ),
            get_conf(spec, 'path')
        )

        # Add security definitions to copy of specs
        if add_security_definitions:
            path = __add_security_definitions(in_file=path)

        # Generate API endpoints from OpenAPI spec
        try:
            app.add_api(
                path,
                strict_validation=get_conf(spec, 'strict_validation'),
                validate_responses=get_conf(spec, 'validate_responses'),
                swagger_ui=get_conf(spec, 'swagger_ui'),
                swagger_json=get_conf(spec, 'swagger_json'),
            )

            logger.info("API endpoints specified in '{path}' added.".format(
                path=path,
            ))

        except (FileNotFoundError, PermissionError) as e:
            logger.critical(
                (
                    "API specification file not found or accessible at "
                    "'{path}'. Execution aborted. Original error message: "
                    "{type}: {msg}"
                ).format(
                    path=path,
                    type=type(e).__name__,
                    msg=e,
                )
            )
            raise SystemExit(1)

    return(app)
Exemple #30
0
def build_app(apis, host=_host, port=_port, ui=_ui):
    app = App(__name__,
              host=host,
              port=port,
              server='flask',
              options={'swagger_ui': ui})

    for api in apis:
        app.add_api(api)

    _configure_flask(app.app)

    return app
Exemple #31
0
def test_register_openapi_spec_cannot_serialize():
    """Registering OpenAPI specs fails because the modified specs cannot be
    serialized."""
    app = App(__name__)
    app = App(__name__)
    spec_configs = [
        SpecConfig(
            path=PATH_SPECS_2_YAML_MODIFIED,
            add_operation_fields=OPERATION_FIELDS_NOT_SERIALIZABLE,
        )
    ]
    with pytest.raises(YAMLError):
        register_openapi(app=app, specs=spec_configs)
Exemple #32
0
def build_app_inject_from_fixture(api_spec_folder, **kwargs):
    debug = True
    if 'debug' in kwargs:
        debug = kwargs['debug']
        del (kwargs['debug'])

    cnx_app = App(__name__,
                  port=5001,
                  specification_dir=FIXTURES_FOLDER / api_spec_folder,
                  debug=debug)
    cnx_app.add_api('swagger.yaml', resolver=RestyResolver('api'), **kwargs)
    FlaskInjector(app=cnx_app.app, modules=[configure])
    return cnx_app
def test_swagger_ui(simple_api_spec_dir, spec):
    app = App(__name__,
              port=5001,
              specification_dir=simple_api_spec_dir,
              debug=True)
    app.add_api(spec)
    app_client = app.app.test_client()
    swagger_ui = app_client.get('/v1.0/ui/')  # type: flask.Response
    assert swagger_ui.status_code == 200
    spec_json_filename = '/v1.0/{spec}'.format(
        spec=spec.replace("yaml", "json"))
    assert spec_json_filename.encode() in swagger_ui.data
    if "openapi" in spec:
        assert b'swagger-ui-config.json' not in swagger_ui.data
def test_swagger_ui_with_config(simple_api_spec_dir, spec):
    swagger_ui_config = {"displayOperationId": True}
    options = {"swagger_ui_config": swagger_ui_config}
    app = App(__name__,
              port=5001,
              specification_dir=simple_api_spec_dir,
              options=options,
              debug=True)
    app.add_api(spec)
    app_client = app.app.test_client()
    swagger_ui = app_client.get('/v1.0/ui/')  # type: flask.Response
    assert swagger_ui.status_code == 200
    if "openapi" in spec:
        assert b'configUrl: "swagger-ui-config.json"' in swagger_ui.data
Exemple #35
0
def test_using_all_fields_in_path_item(simple_api_spec_dir):
    """Test that connexion will try to add an endpoint only on http methods.

    test also that each http methods has its own endpoint.
    """
    app = App(__name__, specification_dir=simple_api_spec_dir)
    app.add_api('openapi.yaml')

    test_methods = set()
    for rule in app.app.url_map.iter_rules():
        if rule.rule != "/v1.0/add_operation_on_http_methods_only":
            continue
        test_methods.update({method.lower() for method in rule.methods})
    assert set(test_methods) == METHODS
Exemple #36
0
def test_using_all_fields_in_path_item(simple_api_spec_dir):
    """Test that connexion will try to add an endpoint only on http methods.

    test also that each http methods has its own endpoint.
    """
    app = App(__name__, specification_dir=simple_api_spec_dir)
    app.add_api('openapi.yaml')

    test_methods = set()
    for rule in app.app.url_map.iter_rules():
        if rule.rule != "/v1.0/add_operation_on_http_methods_only":
            continue
        test_methods.update({method.lower() for method in rule.methods})
    assert set(test_methods) == METHODS
Exemple #37
0
def test_app_with_different_uri_parser(simple_api_spec_dir):
    from connexion.decorators.uri_parsing import FirstValueURIParser
    app = App(__name__, port=5001,
              specification_dir='..' / simple_api_spec_dir.relative_to(TEST_FOLDER),
              options={"uri_parser_class": FirstValueURIParser},
              debug=True)
    app.add_api('swagger.yaml')

    app_client = app.app.test_client()
    resp = app_client.get(
        '/v1.0/test_array_csv_query_param?items=a,b,c&items=d,e,f'
    )  # type: flask.Response
    assert resp.status_code == 200
    j = json.loads(resp.get_data(as_text=True))
    assert j == ['a', 'b', 'c']
Exemple #38
0
def test_register_openapi_spec_file_not_found():
    """Registering OpenAPI specs fails because the spec file is not available.
    """
    app = App(__name__)
    spec_configs = [SpecConfig(path=PATH_SPECS_NOT_EXIST)]
    with pytest.raises(OSError):
        register_openapi(app=app, specs=spec_configs)
Exemple #39
0
def test_dict_as_yaml_path(simple_api_spec_dir):
    swagger_yaml_path = simple_api_spec_dir / 'swagger.yaml'

    with swagger_yaml_path.open(mode='rb') as swagger_yaml:
        contents = swagger_yaml.read()
        try:
            swagger_template = contents.decode()
        except UnicodeDecodeError:
            swagger_template = contents.decode('utf-8', 'replace')

        swagger_string = jinja2.Template(swagger_template).render({})
        specification = yaml.safe_load(swagger_string)  # type: dict

    app = App(__name__, port=5001, specification_dir=simple_api_spec_dir, debug=True)
    app.add_api(specification)

    app_client = app.app.test_client()
    swagger_json = app_client.get('/v1.0/swagger.json')  # type: flask.Response
    assert swagger_json.status_code == 200
Exemple #40
0
def test_dict_as_yaml_path(simple_api_spec_dir, spec):
    openapi_yaml_path = simple_api_spec_dir / spec

    with openapi_yaml_path.open(mode='rb') as openapi_yaml:
        contents = openapi_yaml.read()
        try:
            openapi_template = contents.decode()
        except UnicodeDecodeError:
            openapi_template = contents.decode('utf-8', 'replace')

        openapi_string = jinja2.Template(openapi_template).render({})
        specification = yaml.load(openapi_string, ExtendedSafeLoader)  # type: dict

    app = App(__name__, port=5001, specification_dir=simple_api_spec_dir, debug=True)
    app.add_api(specification)

    app_client = app.app.test_client()
    url = '/v1.0/{spec}'.format(spec=spec.replace("yaml", "json"))
    swagger_json = app_client.get(url)  # type: flask.Response
    assert swagger_json.status_code == 200
Exemple #41
0
def test_no_swagger_ui(simple_api_spec_dir):
    app = App(__name__, port=5001, specification_dir=simple_api_spec_dir,
              swagger_ui=False, debug=True)
    app.add_api('swagger.yaml')

    app_client = app.app.test_client()
    swagger_ui = app_client.get('/v1.0/ui/')  # type: flask.Response
    assert swagger_ui.status_code == 404

    app2 = App(__name__, port=5001, specification_dir=simple_api_spec_dir, debug=True)
    app2.add_api('swagger.yaml', swagger_ui=False)
    app2_client = app2.app.test_client()
    swagger_ui2 = app2_client.get('/v1.0/ui/')  # type: flask.Response
    assert swagger_ui2.status_code == 404
Exemple #42
0
def test_no_swagger_ui(simple_api_spec_dir, spec):
    options = {"swagger_ui": False}
    app = App(__name__, port=5001, specification_dir=simple_api_spec_dir,
              options=options, debug=True)
    app.add_api(spec)

    app_client = app.app.test_client()
    swagger_ui = app_client.get('/v1.0/ui/')  # type: flask.Response
    assert swagger_ui.status_code == 404

    app2 = App(__name__, port=5001, specification_dir=simple_api_spec_dir, debug=True)
    app2.add_api(spec, options={"swagger_ui": False})
    app2_client = app2.app.test_client()
    swagger_ui2 = app2_client.get('/v1.0/ui/')  # type: flask.Response
    assert swagger_ui2.status_code == 404
Exemple #43
0
def test_handle_add_operation_error(simple_api_spec_dir):
    app = App(__name__, specification_dir=simple_api_spec_dir)
    app.api_cls = type('AppTest', (app.api_cls,), {})
    app.api_cls.add_operation = mock.MagicMock(side_effect=Exception('operation error!'))
    with pytest.raises(Exception):
        app.add_api('swagger.yaml', resolver=lambda oid: (lambda foo: 'bar'))
Exemple #44
0
def app():
    cnx_app = App(__name__, port=5001, specification_dir=SPEC_FOLDER, debug=True)
    cnx_app.add_api('api.yaml', validate_responses=True)
    return cnx_app
Exemple #45
0
def get_timestamp():
    return datetime.now().strftime(("%Y-%m-%d %H:%M:%S"))

out_home={
    "Farrell": {
        "fname": "Doug",
        "lname": "Farrell",
        "timestamp": get_timestamp(),
    },
    "Brockman": {
        "fname": "Kent",
        "lname": "Brockman",
        "timestamp": get_timestamp(),
    },
    "Easter": {
        "fname": "Bunny",
        "lname": "Easter",
        "timestamp": get_timestamp(),
    },
}

app=App(__name__)

@app.route('/')
def home():
    return jsonify(out_home)

if __name__=='__main__':
    app.run(debug=True,port=6969,host='0.0.0.0')
Exemple #46
0
from connexion import App
import logging


logging.basicConfig(level=logging.INFO)
app = App(__name__)
app.add_api('swagger.yaml')
# set the WSGI application callable to allow using uWSGI
application = app.app

if __name__ == '__main__':
    app.run(port=8080, server='gevent')
Exemple #47
0
def test_add_api_with_function_resolver_function_is_wrapped(simple_api_spec_dir, spec):
    app = App(__name__, specification_dir=simple_api_spec_dir)
    api = app.add_api(spec, resolver=lambda oid: (lambda foo: 'bar'))
    assert api.resolver.resolve_function_from_operation_id('faux')('bah') == 'bar'