Ejemplo n.º 1
0
def before_scenario(context, step):

    context.account_ids = {}
    context.player_ids = {}
    config = {
        'also_return_response': True,
        'validate_responses': True,
        'validate_requests': True,
        'validate_swagger_spec': True,
        'use_models': True,
        'formats': []
    }

    env = context.config.userdata.get('env')
    context.env_urls = get_environment_variables(env)
    context.clients = Dict()
    context.clients.game_service = SwaggerClient.from_spec(
        load_file('specs/dukedoms_game_service_api.yaml', ),
        origin_url=context.env_urls.game_service,
        config=config)

    context.clients.account_service = SwaggerClient.from_spec(
        load_file('specs/dukedoms_account_service_api.yaml', ),
        origin_url=context.env_urls.account_service,
        config=config)
Ejemplo n.º 2
0
def bitmex(test=True, config=None, api_key=None, api_secret=None):
    # config options at http://bravado.readthedocs.io/en/latest/configuration.html
    if not config:
        config = {
            # Don't use models (Python classes) instead of dicts for #/definitions/{models}
            'use_models': False,
            # bravado has some issues with nullable fields
            'validate_responses': False,
            # Returns response in 2-tuple of (body, response); if False, will only return body
            'also_return_response': True,

            # 'validate_swagger_spec': True,
            # 'validate_requests': True,
            # 'formats': [],
        }

    host = 'https://www.bitmex.com'
    if test:
        host = 'https://testnet.bitmex.com'

    spec_uri = host + '/api/explorer/swagger.json'
    spec_dict = get_swagger_json(spec_uri, exclude_formats=EXCLUDE_SWG_FORMATS)

    if api_key and api_secret:
        request_client = RequestsClient()
        request_client.authenticator = APIKeyAuthenticator(host, api_key, api_secret)
        return SwaggerClient.from_spec(spec_dict, origin_url=spec_uri, http_client=request_client, config=config)
    else:
        return SwaggerClient.from_spec(spec_dict, origin_url=spec_uri, http_client=None, config=config)
Ejemplo n.º 3
0
def get_client(token=None):
    if token == None:
        return SwaggerClient.from_spec(load_file(swagger_json_file))

    # Set up client
    http_client = RequestsClient()

    return SwaggerClient.from_spec(load_file(swagger_json_file),
                                   http_client=http_client)
Ejemplo n.º 4
0
def test_also_return_response(mock_spec):
    with mock.patch('bravado.client.SwaggerClient.__init__') as mock_init:
        mock_init.return_value = None
        SwaggerClient.from_spec({}, config={'also_return_response': True})

    mock_init.assert_called_once_with(
        mock_spec.from_dict.return_value,
        also_return_response=True,
    )
Ejemplo n.º 5
0
def test_also_return_response(mock_spec):
    with mock.patch('bravado.client.SwaggerClient.__init__') as mock_init:
        mock_init.return_value = None
        SwaggerClient.from_spec({}, config={'also_return_response': True})

    mock_init.assert_called_once_with(
        mock_spec.from_dict.return_value,
        also_return_response=True,
    )
Ejemplo n.º 6
0
def test_dereferenced_swagger_schema_bravado_client(
        schema_format,
        test_app_deref,
):
    from bravado.client import SwaggerClient

    response = test_app_deref.get('/swagger.{0}'.format(schema_format))
    deserializer = DESERIALIZERS[schema_format]
    specs = deserializer(response)

    SwaggerClient.from_spec(specs)
def test_dereferenced_swagger_schema_bravado_client(
    schema_format,
    test_app_deref,
):
    from bravado.client import SwaggerClient

    response = test_app_deref.get('/swagger.{0}'.format(schema_format))
    deserializer = DESERIALIZERS[schema_format]
    specs = deserializer(response)

    SwaggerClient.from_spec(specs)
def get_paasta_api_client(
    cluster: str = None,
    system_paasta_config: SystemPaastaConfig = None,
    http_res: bool = False,
) -> Any:
    if not system_paasta_config:
        system_paasta_config = load_system_paasta_config()

    if not cluster:
        cluster = system_paasta_config.get_cluster()

    api_endpoints = system_paasta_config.get_api_endpoints()
    if cluster not in api_endpoints:
        log.error("Cluster %s not in paasta-api endpoints config", cluster)
        return None

    url = str(api_endpoints[cluster])
    parsed = urlparse(url)
    if not parsed:
        log.error("Unsupported paasta-api url %s", url)
        return None
    api_server = parsed.netloc

    # Get swagger spec from file system instead of the api server
    paasta_api_path = os.path.dirname(paasta_tools.api.__file__)
    swagger_file = os.path.join(paasta_api_path, "api_docs/swagger.json")
    if not os.path.isfile(swagger_file):
        log.error("paasta-api swagger spec %s does not exist", swagger_file)
        return None

    with open(swagger_file) as f:
        spec_dict = json.load(f)
    # replace localhost in swagger.json with actual api server
    spec_dict["host"] = api_server
    spec_dict["schemes"] = [parsed.scheme]

    # sometimes we want the status code
    requests_client = PaastaRequestsClient(
        scheme=parsed.scheme,
        cluster=cluster,
        system_paasta_config=system_paasta_config)
    if http_res:
        config = {"also_return_response": True}
        c = SwaggerClient.from_spec(spec_dict=spec_dict,
                                    config=config,
                                    http_client=requests_client)
    else:
        c = SwaggerClient.from_spec(spec_dict=spec_dict,
                                    http_client=requests_client)
    return paasta_tools.api.auth_decorator.AuthClientDecorator(
        c, cluster_name=cluster)
Ejemplo n.º 9
0
def test_remove_bravado_configs(mock_spec, processed_default_config):
    config = CONFIG_DEFAULTS.copy()
    config['validate_swagger_spec'] = False  # bravado_core config

    SwaggerClient.from_spec({}, config=config)

    mock_spec.from_dict.assert_called_once_with(
        {},  # spec_dict
        None,  # spec_url
        mock.ANY,  # http_client
        {
            'bravado': processed_default_config,
            'validate_swagger_spec': False,
        },  # config
    )
Ejemplo n.º 10
0
def test_remove_bravado_configs(mock_spec, processed_default_config):
    config = CONFIG_DEFAULTS.copy()
    config['validate_swagger_spec'] = False  # bravado_core config

    SwaggerClient.from_spec({}, config=config)

    mock_spec.from_dict.assert_called_once_with(
        {},  # spec_dict
        None,  # spec_url
        mock.ANY,  # http_client
        {
            'bravado': processed_default_config,
            'validate_swagger_spec': False,
        },  # config
    )
def load_spec_from_spec_dict(spec_dict):
    # type: (typing.Mapping[typing.Text, typing.Any]) -> Spec
    return SwaggerClient.from_spec(spec_dict,
                                   origin_url='',
                                   config={
                                       'internally_dereference_refs': True
                                   }).swagger_spec
Ejemplo n.º 12
0
def load_client(apikey=None, headers=None, host=HOST):
    global client
    force = False

    if client is not None:
        http_client = client.swagger_spec.http_client
        force = bool(headers is not None and http_client.headers != headers)

    if force or client is None:
        # - Kong forwards consumer headers when api-key used for auth
        # - forward consumer headers when connecting through localhost
        headers = {"x-api-key": apikey} if apikey else headers
        http_client = FidoClientGlobalHeaders(headers=headers)
        loader = Loader(http_client)
        protocol = "https" if apikey else "http"
        spec_url = f"{protocol}://{host}/apispec.json"
        spec_dict = loader.load_spec(spec_url)
        spec_dict["host"] = host
        spec_dict["schemes"] = [protocol]
        client = SwaggerClient.from_spec(
            spec_dict,
            spec_url,
            http_client,
            {
                "validate_responses": False,
                "use_models": False,
                "include_missing_properties": False,
                "formats": [email_format],
            },
        )

    return client
Ejemplo n.º 13
0
def before_scenario(context, step):

    config = {
        'also_return_response': True,
        'validate_responses': True,
        'validate_requests': True,
        'validate_swagger_spec': True,
        'use_models': True,
        'formats': []
    }

    context.env_urls = Dict()
    context.env_urls.card_service = 'http://127.0.0.1:5005'
    context.env_urls.card_service_db = (
        'postgresql+psycopg2://postgres:[email protected]:5432/card_service'
    )

    context.clients = Dict()
    context.clients.card_service = SwaggerClient.from_spec(
        load_file(
            'specs/dukedoms_card_service_api.yaml',
        ),
        origin_url=context.env_urls.card_service,
        config=config
    )
Ejemplo n.º 14
0
def load_wes_client(service_id, http_client=None, client_library=None):
    """
    Return an API client for the selected workflow execution service.
    """
    if http_client is None:
        http_client = _init_http_client(service_id=service_id)

    if client_library is not None:
        from wes_client.util import WESClient
        wes_client = WESClient(service=_get_wes_opts(service_id))
        return WESAdapter(wes_client)

    spec_path = os.path.join(os.path.dirname(os.path.dirname(__file__)),
                             'workflow_execution_service.swagger.yaml')
    spec_path = os.path.abspath(spec_path)

    opts = _get_wes_opts(service_id)
    api_url = '{}://{}'.format(opts['proto'], opts['host'])

    loader = Loader(http_client, request_headers=None)
    spec_dict = loader.load_spec('file:///{}'.format(spec_path),
                                 base_url=api_url)
    spec_client = SwaggerClient.from_spec(spec_dict,
                                          origin_url=api_url,
                                          http_client=http_client,
                                          config={'use_models': False})

    return spec_client.WorkflowExecutionService
Ejemplo n.º 15
0
def get_swagger_client():
    """Shortcut function to init swagger client.

    Takes file path from django setting and initialize swagger client with
    custom DjangoClient
    """
    path = settings.TEST_SWAGGER_SPEC_FILE

    # check is path URL or path to local file
    if os.path.exists(path):
        conf_loader = load_file
    else:
        conf_loader = load_url

    try:
        swagger_data = conf_loader(path)
    except Exception:
        msg = 'Cannot load swagger file from "{}"'.format(path)
        raise AssertionError(msg) from None
    config = {
        'also_return_response': True,
    }
    return SwaggerClient.from_spec(
        swagger_data,
        config=config,
        http_client=DjangoClient(),
    )
Ejemplo n.º 16
0
def loop_handler(request):
    spec_dict = {
        "swagger": "2.0",
        "info": {
            "version": "0.1",
            "title": "Hawkular APM zipkin pyramid API"
        },
        "host": "127.0.0.1:" + str(PORT),
        "schemes": ["http"],
        "basePath": "/" + BASE_PATH,
        "tags": [{
            "name": "hello"
        }],
        "paths": {
            "/hello": {
                "get": {
                    "tags": ["hello"],
                    "operationId": "get",
                    "responses": {
                        "200": {
                            "description": "OK"
                        },
                    }
                }
            }
        }
    }

    client = SwaggerClient.from_spec(spec_dict=spec_dict)
    zipkin_wrapped_client = ZipkinClientDecorator(client)
    zipkin_wrapped_client.hello.get().result()

    return Response('loop -> hello')
Ejemplo n.º 17
0
def get_paasta_api_client(cluster=None, system_paasta_config=None):
    if not system_paasta_config:
        system_paasta_config = load_system_paasta_config()

    if not cluster:
        cluster = system_paasta_config.get_cluster()

    api_endpoints = system_paasta_config.get_api_endpoints()
    if cluster not in api_endpoints:
        log.error('Cluster %s not in paasta-api endpoints config', cluster)
        return None

    url = str(api_endpoints[cluster])
    parsed = urlparse(url)
    if not parsed:
        log.error('Unsupported paasta-api url %s', url)
        return None
    api_server = parsed.netloc

    # Get swagger spec from file system instead of the api server
    paasta_api_path = os.path.dirname(sys.modules['paasta_tools.api'].__file__)
    swagger_file = os.path.join(paasta_api_path, 'api_docs/swagger.json')
    if not os.path.isfile(swagger_file):
        log.error('paasta-api swagger spec %s does not exist', swagger_file)
        return None

    with open(swagger_file) as f:
        spec_dict = json.load(f)
    # replace localhost in swagger.json with actual api server
    spec_dict['host'] = api_server
    return SwaggerClient.from_spec(spec_dict=spec_dict)
Ejemplo n.º 18
0
    def from_spec(cls, spec_dict, origin_url=None, http_client=None,
                  privkey=None, **kwargs):
        """
        Build a :class:`SwaggerClient` from swagger api docs

        :param spec_dict: a dict with a Swagger spec in json-like form
        :param origin_url: the url used to retrieve the spec_dict
        :type  origin_url: str
        :param http_client: an HTTP client used to perform requests
        :type  http_client: :class:`bravado.http_client.HttpClient`
        :param str privkey: The WIF private key to use for bitjws signing
        """
        if privkey is None:
            privkey = bitjws.PrivateKey()
        elif isinstance(privkey, str):
            privkey = bitjws.PrivateKey(bitjws.wif_to_privkey(privkey))

        if http_client is None:
            host = urlparse.urlsplit(origin_url).hostname
            http_client = BitJWSRequestsClient()
            private_key = bitjws.privkey_to_wif(privkey.private_key)
            http_client.set_bitjws_key(host, private_key)

        return SwaggerClient.from_spec(spec_dict, http_client=http_client,
                                       **kwargs)
Ejemplo n.º 19
0
    def __init__(self, swagger_spec: Spec):
        """
        :param swagger_spec: Complete swagger specification for the API to test.
        """
        self.host = "localhost"

        self.swagger_spec = swagger_spec
        self.base_path = swagger_spec.client_spec_dict.get("basePath", "")

        self.swagger_spec.spec_dict['host'] = f'{self.host}:{TEST_PORT}'

        # setting validate requests to false since we only care about
        # responses
        config = {
            "also_return_response": True,
            "use_models": False,
            "validate_requests": False,
            "formats": swagger_spec.config.get("formats", [])
        }
        self.config = config

        # Bravado provides an async client, but it doesnt run on ioloop? from docs:
        # Fido is a simple, asynchronous HTTP client built on top of Crochet and Twisted with an implementation
        # inspired by the book "Twisted Network Programming Essentials". It is intended to be used in environments
        # where there is no event loop, and where you cannot afford to spin up lots of threads (otherwise you
        # could just use a ThreadPoolExecutor).

        self.swagger_client = SwaggerClient.from_spec(
            self.swagger_spec.spec_dict,
            http_client=RequestsClient(),
            config=config)
Ejemplo n.º 20
0
 def __init__(self, server_url):
     """Create a OpenAPI client for REANA Server."""
     json_spec = self._get_spec('reana_server.json')
     self._client = SwaggerClient.from_spec(
         json_spec, config={'also_return_response': True})
     self._client.swagger_spec.api_url = server_url
     self.server_url = server_url
Ejemplo n.º 21
0
def setup_client(
    url: str,
    schema: Optional[Dict[str, Any]] = None,
) -> Optional[str]:
    """
    :returns: error message, if appropriate.
    """
    if get_abstraction().client:
        return None

    try:
        config = {'internally_dereference_refs': True}
        if not schema:
            client = SwaggerClient.from_url(url, config=config)
        else:
            client = SwaggerClient.from_spec(schema,
                                             origin_url=url,
                                             config=config)
    except requests.exceptions.ConnectionError:
        return 'Unable to connect to server.'
    except (
            simplejson.errors.JSONDecodeError,  # type: ignore
            yaml.YAMLError,
            HTTPError,
    ):
        return ('Invalid swagger file. Please check to make sure the '
                'swagger file can be found at: {}.'.format(url))
    except SwaggerValidationError:
        return 'Invalid swagger format.'

    get_abstraction().client = client
    return None
Ejemplo n.º 22
0
def get_api_client(config, validation=False):
    if config.has_key('client'):
        return config['client']

    url = "https://%s/api/v1/spec/openapi/nsx_api.json" % config['nsxManager'][
        'ip']
    base64string = base64.encodestring(
        ('%s:%s' % (config['nsxManager']['username'],
                    config['nsxManager']['password'])).encode("utf-8"))[:-1]
    headers = {"Authorization": "Basic %s" % base64string.decode("utf-8")}
    context = ssl.create_default_context()
    context.check_hostname = False
    context.verify_mode = ssl.CERT_NONE
    req = urllib2.Request(url=url, headers=headers)
    response = urllib2.urlopen(req, context=context)
    raw_spec = json.loads(response.read())
    raw_spec['host'] = config['nsxManager']['ip']
    http_client = RequestsClient()
    http_client.session.verify = False
    http_client.set_basic_auth(config['nsxManager']['ip'],
                               config['nsxManager']['username'],
                               config['nsxManager']['password'])
    config = {
        'also_return_response': True,
        'validate_swagger_spec': validation,
        'validate_responses': False,
        'validate_requests': False,
        'use_models': False
    }
    client = SwaggerClient.from_spec(raw_spec,
                                     http_client=http_client,
                                     config=config)
    config['client'] = client
    return client
Ejemplo n.º 23
0
 def __init__(self, service, http_client=None):
     """Create an OpenAPI client."""
     server_url, spec_file = OPENAPI_SPECS[service]
     json_spec = self._get_spec(spec_file)
     current_instance = BaseAPIClient._bravado_client_instance
     # We reinstantiate the bravado client instance if
     # 1. The current instance doesn't exist, or
     # 2. We're passing an http client (likely a mock), or
     # 3. The current instance is a Mock, meaning that either we want to
     #    use the `RequestClient` or we're passing a different mock.
     if (
         current_instance is None
         or http_client
         or isinstance(current_instance.swagger_spec.http_client, Mock)
     ):
         BaseAPIClient._bravado_client_instance = SwaggerClient.from_spec(
             json_spec,
             http_client=http_client or RequestsClient(ssl_verify=False),
             config={"also_return_response": True},
         )
     self._load_config_from_env()
     self._client = BaseAPIClient._bravado_client_instance
     if server_url is None:
         raise MissingAPIClientConfiguration(
             "Configuration to connect to {} is missing.".format(service)
         )
     self._client.swagger_spec.api_url = server_url
     self.server_url = server_url
Ejemplo n.º 24
0
def get_paasta_api_client(cluster=None, system_paasta_config=None):
    if not system_paasta_config:
        system_paasta_config = load_system_paasta_config()

    if not cluster:
        cluster = system_paasta_config.get_cluster()

    api_endpoints = system_paasta_config.get_api_endpoints()
    if cluster not in api_endpoints:
        log.error('Cluster %s not in paasta-api endpoints config', cluster)
        return None

    url = str(api_endpoints[cluster])
    parsed = urlparse(url)
    if not parsed:
        log.error('Unsupported paasta-api url %s', url)
        return None
    api_server = parsed.netloc

    # Get swagger spec from file system instead of the api server
    paasta_api_path = os.path.dirname(sys.modules['paasta_tools.api'].__file__)
    swagger_file = os.path.join(paasta_api_path, 'api_docs/swagger.json')
    if not os.path.isfile(swagger_file):
        log.error('paasta-api swagger spec %s does not exist', swagger_file)
        return None

    with open(swagger_file) as f:
        spec_dict = json.load(f)
    # replace localhost in swagger.json with actual api server
    spec_dict['host'] = api_server
    return SwaggerClient.from_spec(spec_dict=spec_dict)
Ejemplo n.º 25
0
    def __init__(self):
        self.client = SwaggerClient.from_spec(fiware_nsgiv2_openapi_spec)
        self.options = {'headers': {}}

        self.id = ''
        self.type = ''
        self.temperature = ''
        self.pressure = ''
Ejemplo n.º 26
0
    def setup_swagger(self):
        self.http_client = RequestsClient()
        self.http_client.session.verify = False

        self.client = SwaggerClient.from_spec(load_file(self.spec),
                                              config=self.config,
                                              http_client=self.http_client)
        self.client.swagger_spec.api_url = self.api_url
Ejemplo n.º 27
0
    def setup_swagger(self):
        self.http_client = RequestsClient()
        self.http_client.session.verify = False

        spec = pytest.config.getoption(self.spec_option)
        self.client = SwaggerClient.from_spec(load_file(spec),
                                              config=self.config,
                                              http_client=self.http_client)
        self.client.swagger_spec.api_url = self.make_api_url()
Ejemplo n.º 28
0
    def setup(self):
        self.http_client = RequestsClient()
        self.http_client.session.verify = False

        self.client = SwaggerClient.from_spec(load_file('management_api.yml'),
                                              config=self.config,
                                              http_client=self.http_client)
        self.client.swagger_spec.api_url = "http://%s/api/%s/" % (
            pytest.config.getoption("host"), pytest.config.getoption("api"))
Ejemplo n.º 29
0
    def test_headers(self):
        self.uut = SwaggerClient.from_spec(self.resource_listing)
        httpretty.register_uri(
            httpretty.GET, "http://swagger.py/swagger-test/pet",
            body='[]')

        self.uut.pet.listPets(
            _request_options={'headers': {'foo': 'bar'}}).result()
        self.assertEqual('bar', httpretty.last_request().headers['foo'])
Ejemplo n.º 30
0
def get_client(url):
    with open(
            os.getenv("SWAGGER_SCHEMA",
                      os.path.join(os.path.dirname(__file__),
                                   "swagger.yml"))) as f:
        spec = yaml.load(f)
    client = SwaggerClient.from_spec(spec)
    client.swagger_spec.api_url = url
    return client
Ejemplo n.º 31
0
    def __init__(self,
                 url=None,
                 config=DEFAULT_CONFIG,
                 http_client=None,
                 request_headers=None,
                 local=False):
        """
        Instantiates :class:`~bravado.client.SwaggerClient`.

        For further documentation, refer to the documentation
        for :meth:`bravado.client.SwaggerClient.from_url` and
        :meth:`bravado.client.SwaggerClient.from_spec`.

        :param str url: the URL of a Swagger specification. If ``local``
                        is True, this should be the base URL of a DOS
                        implementation (see ``local``).
        :param dict config: see :meth:`bravado.client.SwaggerClient`
        :param http_client: see :meth:`bravado.client.SwaggerClient`
        :param request_headers: see :meth:`beravado.client.SwaggerClient`
        :param bool local: set this to True to load the local schema.
                           If this is True, the ``url`` parameter should
                           point to the host and base path of the
                           implementation under test::

                              Client(url='https://example.com/ga4gh/dos/v1/', local=True)

                           If False, the ``url`` parameter should point to a
                           Swagger specification (``swagger.json``).
        """
        self._config = config
        config['formats'] = [int64_format]
        if local:
            # :meth:`bravado.client.SwaggerClient.from_spec` takes a schema
            # as a Python dictionary, which we can conveniently expose
            # via :func:`ga4gh.dos.schema.present_schema`.
            schema = ga4gh.dos.schema.present_schema()

            # Set schema['host'] and schema['basePath'] to the provided
            # values if specified, otherwise leave them as they are
            url = urlparse.urlparse(url)
            schema['host'] = url.netloc or schema['host']
            schema['basePath'] = url.path or schema['basePath']

            self.models = SwaggerClient.from_spec(spec_dict=schema,
                                                  config=config,
                                                  http_client=http_client)
        else:
            # If ``local=False``, ``url`` is expected to be a ``swagger.json``
            swagger_path = '{}/swagger.json'.format(url.rstrip("/"))
            self.models = SwaggerClient.from_url(
                swagger_path,
                config=config,
                http_client=http_client,
                request_headers=request_headers)
        self.client = self.models.DataObjectService
def before_scenario(context, step):

    config = {
        'also_return_response': True,
        'validate_responses': True,
        'validate_requests': True,
        'validate_swagger_spec': True,
        'use_models': True,
        'formats': []
    }

    context.urls = get_env_urls(context.config.userdata.get('env'))

    context.clients = Dict()
    context.clients.action_broker = SwaggerClient.from_spec(
        load_file(
            'swagger/action_broker_api.yaml',
        ),
        origin_url=context.urls.action_broker,
        config=config
    )
    context.clients.card_broker = SwaggerClient.from_spec(
        load_file(
            'swagger/card_broker_api.yaml',
        ),
        origin_url=context.urls.card_broker,
        config=config
    )
    context.clients.card_service = SwaggerClient.from_spec(
        load_file(
            'swagger/card_service_api.yaml',
        ),
        origin_url=context.urls.card_service,
        config=config
    )
    context.clients.player_service = SwaggerClient.from_spec(
        load_file(
            'swagger/player_service_api.yaml',
        ),
        origin_url=context.urls.player_service,
        config=config
    )
Ejemplo n.º 33
0
def create_openapi_client(component):
    """Create a OpenAPI client for a given spec."""
    try:
        address, spec_file = COMPONENTS_DATA[component]
        json_spec = get_spec(spec_file)
        client = SwaggerClient.from_spec(json_spec,
                                         config={'also_return_response': True})
        client.swagger_spec.api_url = address
        return client
    except KeyError:
        raise Exception('Unkown component {}'.format(component))
Ejemplo n.º 34
0
    def get_client_from_spec(self, origin_url, spec_dict):
        """It fetches teh swagger clint object from dict()

        :param origin_url: the url used to retrieve the resource schema
        :param spec_dict: holds the swagger dict
        :return: swagger client object
        """
        spec = SwaggerClient.from_spec(spec_dict,
                                       origin_url,
                                       config={'also_return_response': True})
        return spec
Ejemplo n.º 35
0
    def setup(self):
        self.log = logging.getLogger("client.Client")
        self.api_url = API_URL
        self.http_client = RequestsClient()
        self.http_client.session.verify = False

        spec = pytest.config.getoption("spec")
        self.client = SwaggerClient.from_spec(load_file(spec),
                                              config=self.config,
                                              http_client=self.http_client)
        self.client.swagger_spec.api_url = self.api_url
Ejemplo n.º 36
0
    def setup_swagger(self):
        self.http_client = RequestsClient()
        self.http_client.session.verify = False

        spec = pytest.config.getoption(self.spec_option)
        self.client = SwaggerClient.from_spec(load_file(spec),
                                              config=self.config,
                                              http_client=self.http_client)

        self.client.swagger_spec.api_url = "http://{}/api/{}/".format(pytest.config.getoption("host"),
                                                                      pytest.config.getoption("api"))
Ejemplo n.º 37
0
def load_client(apikey=None):
    host = 'api.mpcontribs.org' if apikey else 'localhost:5000'
    protocol = 'https' if apikey else 'http'
    spec_url = f'{protocol}://{host}/apispec.json'
    http_client = RequestsClient()
    if apikey:
        http_client.set_api_key(
            host, apikey, param_in='header', param_name='x-api-key'
        )
    loader = Loader(http_client)
    spec_dict = loader.load_spec(spec_url)
    spec_dict['host'] = host
    spec_dict['schemes'] = [protocol]
    return SwaggerClient.from_spec(spec_dict, spec_url, http_client,
                                   {'validate_responses': False})
Ejemplo n.º 38
0
def loop_handler(request):
    spec_dict = {
        "swagger": "2.0",
        "info": {
            "version": "0.1",
            "title": "Hawkular APM zipkin pyramid API"
        },
        "host": "127.0.0.1:" + str(PORT),
        "schemes": [
            "http"
        ],
        "basePath": "/" + BASE_PATH,
        "tags": [
            {
                "name": "hello"
            }
        ],
        "paths": {
            "/hello": {
                "get": {
                    "tags": [
                        "hello"
                    ],
                    "operationId": "get",
                    "responses": {
                        "200": {
                            "description": "OK"
                        },
                    }
                }
            }
        }
    }

    client = SwaggerClient.from_spec(spec_dict=spec_dict)
    zipkin_wrapped_client = ZipkinClientDecorator(client)
    zipkin_wrapped_client.hello.get().result()

    return Response('loop -> hello')
Ejemplo n.º 39
0
def client_tags_with_spaces():
    return SwaggerClient.from_spec({
        'swagger': '2.0',
        'info': {
            'version': '',
            'title': 'API'
        },
        'paths': {
            '/ping': {
                'get': {
                    'operationId': 'ping',
                    'responses': {
                        '200': {
                            'description': 'ping'
                        }
                    },
                    'tags': [
                        'my tag'
                    ]
                }
            }
        }
    })
Ejemplo n.º 40
0
def das_client(das, swagger_spec):
    return SwaggerClient.from_spec(swagger_spec, origin_url=das.url)
Ejemplo n.º 41
0
from bravado.requests_client import RequestsClient
import json

# appneta login credentials
email = '*****@*****.**'
password = '******'

# appneta PVC shard instance
instance = 'demo'
instance_host = '%s.pathviewcloud.com' % (instance,)

http_client = RequestsClient()
http_client.set_basic_auth(instance_host, email, password)

with open('swagger.json') as f:
    spec = json.load(f)
client = SwaggerClient.from_spec(spec, 'https://%s' % (instance_host,), http_client=http_client)

# per https://demo.pathviewcloud.com/pvc-data/swagger/
print client.organization.all().result()



# note that some client generators can access the .json file directly from a URL
# however, bravado (and perhaps others) enforce presence of info=>title attribute,
# which is not present in AppNeta-hosted swagger.json and has been added to the
# version in this respository

#swagger_spec_url = 'https://%s/pvc-data/swagger.json' % (instance_host,)
#client = SwaggerClient.from_url(swagger_spec_url, http_client=http_client)
Ejemplo n.º 42
0
def petstore_client(petstore_dict):
    return SwaggerClient.from_spec(petstore_dict)
Ejemplo n.º 43
0
 def setUp(self):
     # Default handlers for all swagger.py access
     self.resource_listing = {
         u"swaggerVersion": u"1.2",
         u"basePath": u"http://swagger.py/swagger-test",
         u"apis": [
             {
                 u"path": u"/api-docs/pet.json",
                 u"description": u"Test loader when missing a file",
                 u"api_declaration": {
                     u"swaggerVersion": u"1.2",
                     u"basePath": u"http://swagger.py/swagger-test",
                     u"resourcePath": u"/pet.json",
                     u"apis": [
                         {
                             u"path": u"/pet",
                             u"operations": [
                                 {
                                     u"method": u"GET",
                                     u"nickname": u"listPets",
                                     u"type": u"array",
                                     u"items": {
                                         u"type": u"string"
                                     },
                                     u"parameters": []
                                 },
                                 {
                                     u"method": u"POST",
                                     u"nickname": u"createPet",
                                     u"type": u"string",
                                     u"parameters": [
                                         {
                                             u"name": u"name",
                                             u"paramType": u"query",
                                             u"type": u"string",
                                             u"required": True
                                         },
                                         {
                                             u"name": u"birthday",
                                             u"paramType": u"query",
                                             u"type": u"string",
                                             u"format": u"date",
                                             u"required": False
                                         }
                                     ]
                                 }
                             ]
                         },
                         {
                             u"path": u"/pet/find",
                             u"operations": [
                                 {
                                     u"method": u"GET",
                                     u"nickname": u"findPets",
                                     u"type": u"array",
                                     u"items": {
                                         u"type": u"string"
                                     },
                                     u"parameters": [
                                         {
                                             u"name": u"species",
                                             u"paramType": u"query",
                                             u"type": u"string",
                                             u"allowMultiple": True
                                         }
                                     ]
                                 }
                             ]
                         },
                         {
                             u"path": u"/pet/{petId}",
                             u"operations": [
                                 {
                                     u"method": u"DELETE",
                                     u"nickname": u"deletePet",
                                     u"type": u"void",
                                     u"parameters": [
                                         {
                                             u"name": u"petId",
                                             u"type": u"integer",
                                             u"paramType": u"path"
                                         }
                                     ]
                                 }
                             ]
                         },
                         {
                             u"path": u"/pet/{petId}/vaccine",
                             u"operations": [
                                 {
                                     u"method": u"POST",
                                     u"nickname": u"postVaccine",
                                     u"type": u"void",
                                     u"parameters": [
                                         {
                                             u"name": u"petId",
                                             u"type": u"integer",
                                             u"paramType": u"path"
                                         },
                                         {
                                             u"name": u"vaccineFile",
                                             u"type": u"File",
                                             u"paramType": u"form"
                                         }
                                     ]
                                 }
                             ]
                         }
                     ],
                     u"models": {}
                 }
             }
         ]
     }
     self.uut = SwaggerClient.from_spec(self.resource_listing)
Ejemplo n.º 44
0
    }

    if useBravadoRemote:
        bravado_config['validate_swagger_spec'] = False
        client = SwaggerClient.from_url(
                    host + '/swagger.json',
                    config=bravado_config)

    else:
        from bravado_core.spec import Spec

        # Load local swagger.json, but adjust it to point at correct host
        spec_dict = json.load(open('swagger.json'))
        spec_dict['host'] = 'api.monarchinitiative.org'
        client = SwaggerClient.from_spec(
                    spec_dict,
                    config=bravado_config)


    try:
        result = client.bioentity.get_gene_interactions(id=gene_id).result()
        print('Bravado result')
        pp = pprint.PrettyPrinter(indent=2)
        pp.pprint(result)

    except Exception as e:
        print("Exception when calling client.bioentity.get_gene_interactions: %s\n" % e)


# import requests
# # Or alternatively without the swagger client
Ejemplo n.º 45
0
def client_swagger(falcon_api, swagger_spec):
    return SwaggerClient.from_spec(swagger_spec,
                                   http_client=FalconHttpClient(falcon_api))
Ejemplo n.º 46
0
def client_no_req_validation(falcon_api, swagger_spec):
    return SwaggerClient.from_spec(swagger_spec,
                                   http_client=FalconHttpClient(falcon_api),
                                   config={'validate_requests': False})
Ejemplo n.º 47
0
def client(swagger_spec):
    return SwaggerClient.from_spec(swagger_spec,
                                   http_client=FalconHttpClient(tests.service.api),
                                   config={'also_return_response': True})
Ejemplo n.º 48
0
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'dist'),)

WEBPACK_LOADER = {
    'DEFAULT': {
        'CACHE': not DEBUG,
        'BUNDLE_DIR_NAME': './',
        'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
    }
}

if os.environ.get('DEPLOYMENT') == 'MATGEN':
    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

from bravado.client import SwaggerClient
from bravado.requests_client import RequestsClient
from bravado.swagger_model import Loader
# docker containers networking within docker-compose or Fargate task
apihost = 'api' if DEBUG else 'localhost'
apihost = f'{apihost}:5000'
spec_url = 'http://{}/apispec.json'.format(apihost)
http_client = RequestsClient()
loader = Loader(http_client)
spec_dict = loader.load_spec(spec_url)
spec_dict['host'] = apihost
spec_dict['schemes'] = ['http']
swagger_client = SwaggerClient.from_spec(
    spec_dict, spec_url, http_client,
    {'validate_responses': False, 'use_models': False}
)
Ejemplo n.º 49
0
 def test_from_spec(self):
     client_stub = SwaggerClient.from_spec(self.resource_listing)
     assert isinstance(client_stub, SwaggerClient)