Пример #1
0
async def test_api_exception_cert(mocked_api_client):
    session_auth_client = mocked_api_client()
    key_auth_client = mocked_api_client()

    session_auth_client.call_api.side_effect = ApiException(status=401)
    key_auth_client.call_api.side_effect = ApiException(status=401)

    bot_authenticator = BotAuthenticatorCert(session_auth_client, key_auth_client, minimal_retry_config())

    with pytest.raises(AuthUnauthorizedError):
        await bot_authenticator.retrieve_session_token()

    with pytest.raises(AuthUnauthorizedError):
        await bot_authenticator.retrieve_key_manager_token()
Пример #2
0
async def test_api_exception_rsa(config, mocked_api_client):
    with patch("symphony.bdk.core.auth.bot_authenticator.create_signed_jwt",
               return_value="privateKey"):
        login_api_client = mocked_api_client()
        relay_api_client = mocked_api_client()

        login_api_client.call_api.side_effect = ApiException(status=401)
        relay_api_client.call_api.side_effect = ApiException(status=401)

        bot_authenticator = BotAuthenticatorRsa(config, login_api_client,
                                                relay_api_client,
                                                minimal_retry_config())

        with pytest.raises(AuthUnauthorizedError):
            await bot_authenticator.retrieve_session_token()

        with pytest.raises(AuthUnauthorizedError):
            await bot_authenticator.retrieve_key_manager_token()
Пример #3
0
async def test_start_recreate_datafeed_error(datafeed_repository, datafeed_api,
                                             auth_session, config):
    datafeed_repository.write("persisted_id")
    datafeed_loop = auto_stopping_datafeed_loop_v1(datafeed_api, auth_session,
                                                   config, datafeed_repository)

    datafeed_api.v4_datafeed_id_read_get.side_effect = ApiException(
        400, "Expired Datafeed id")
    datafeed_api.v4_datafeed_create_post.side_effect = ApiException(
        400, "Unhandled exception")

    with pytest.raises(ApiException):
        await datafeed_loop.start()

    datafeed_api.v4_datafeed_id_read_get.assert_called_once_with(
        id="persisted_id",
        session_token="session_token",
        key_manager_token="km_token")

    datafeed_api.v4_datafeed_create_post.assert_called_once_with(
        session_token="session_token", key_manager_token="km_token")
Пример #4
0
async def test_api_exception_cert_auth_in_userid_authenticate():
    with patch(
            "symphony.bdk.core.auth.obo_authenticator.CertificateAuthenticationApi"
    ) as auth_api:
        auth_api.v1_app_authenticate_post = AsyncMock(return_value=Token(
            token="app_token"))
        auth_api.v1_app_user_uid_authenticate_post = AsyncMock(
            side_effect=ApiException(400))
        obo_authenticator = OboAuthenticatorCert(auth_api,
                                                 minimal_retry_config())

        with pytest.raises(ApiException):
            await obo_authenticator.retrieve_obo_session_token_by_user_id(1234)
Пример #5
0
async def test_api_exception_in_authenticate_userid(config):
    with patch("symphony.bdk.core.auth.obo_authenticator.create_signed_jwt", return_value="signed_jwt"), \
            patch("symphony.bdk.core.auth.obo_authenticator.AuthenticationApi") as auth_api:
        auth_api.pubkey_app_authenticate_post = AsyncMock(return_value=Token(
            token="app_token"))
        auth_api.pubkey_app_user_user_id_authenticate_post = AsyncMock(
            side_effect=ApiException(400))

        obo_authenticator = OboAuthenticatorRsa(config, auth_api,
                                                minimal_retry_config())

        with pytest.raises(ApiException):
            await obo_authenticator.retrieve_obo_session_token_by_user_id(1234)
Пример #6
0
    async def request(self,
                      method,
                      url,
                      query_params=None,
                      headers=None,
                      body=None,
                      post_params=None,
                      _preload_content=True,
                      _request_timeout=None):
        """Execute request

        :param method: http request method
        :param url: http request url
        :param query_params: query parameters in the url
        :param headers: http request headers
        :param body: request json body, for `application/json`
        :param post_params: request post parameters,
                            `application/x-www-form-urlencoded`
                            and `multipart/form-data`
        :param _preload_content: this is a non-applicable field for
                                 the AiohttpClient.
        :param _request_timeout: timeout setting for this request. If one
                                 number provided, it will be total request
                                 timeout. It can also be a pair (tuple) of
                                 (connection, read) timeouts.
        """
        method = method.upper()
        assert method in [
            'GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH', 'OPTIONS'
        ]

        if post_params and body:
            raise ApiValueError(
                "body parameter cannot be used with post_params parameter.")

        post_params = post_params or {}
        headers = headers or {}
        timeout = _request_timeout or 5 * 60

        if 'Content-Type' not in headers:
            headers['Content-Type'] = 'application/json'

        args = {
            "method": method,
            "url": url,
            "timeout": timeout,
            "headers": headers
        }

        if self.proxy:
            args["proxy"] = self.proxy
        if self.proxy_headers:
            args["proxy_headers"] = self.proxy_headers

        if query_params:
            args["url"] += '?' + urlencode(query_params)

        # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE`
        if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']:
            if re.search('json', headers['Content-Type'], re.IGNORECASE):
                if body is not None:
                    body = json.dumps(body)
                args["data"] = body
            elif headers[
                    'Content-Type'] == 'application/x-www-form-urlencoded':  # noqa: E501
                args["data"] = aiohttp.FormData(post_params)
            elif headers['Content-Type'] == 'multipart/form-data':
                # must del headers['Content-Type'], or the correct
                # Content-Type which generated by aiohttp
                del headers['Content-Type']
                data = aiohttp.FormData()
                for param in post_params:
                    k, v = param
                    if isinstance(v, tuple) and len(v) == 3:
                        data.add_field(k,
                                       value=v[1],
                                       filename=v[0],
                                       content_type=v[2])
                    elif isinstance(v, tuple) and len(v) == 2:
                        data.add_field(k, v[0], content_type=v[1])
                    else:
                        data.add_field(k, v)
                args["data"] = data

            # Pass a `bytes` parameter directly in the body to support
            # other content types than Json when `body` argument is provided
            # in serialized form
            elif isinstance(body, bytes):
                args["data"] = body
            else:
                # Cannot generate the request from given parameters
                msg = """Cannot prepare a request message for provided
                         arguments. Please check that your arguments match
                         declared content type."""
                raise ApiException(status=0, reason=msg)

        r = await self.pool_manager.request(**args)
        if _preload_content:

            data = await r.read()
            r = RESTResponse(r, data)

            if not 200 <= r.status <= 299:
                if r.status == 401:
                    raise UnauthorizedException(http_resp=r)

                if r.status == 403:
                    raise ForbiddenException(http_resp=r)

                if r.status == 404:
                    raise NotFoundException(http_resp=r)

                if 500 <= r.status <= 599:
                    raise ServiceException(http_resp=r)

                raise ApiException(http_resp=r)

        return r