コード例 #1
0
def test_appsync_init_with_apikey_auth():
    from gql.transport.appsync_auth import AppSyncApiKeyAuthentication
    from gql.transport.appsync_websockets import AppSyncWebsocketsTransport

    auth = AppSyncApiKeyAuthentication(host=mock_transport_host,
                                       api_key="some-api-key")
    sample_transport = AppSyncWebsocketsTransport(url=mock_transport_url,
                                                  auth=auth)
    assert sample_transport.auth is auth

    assert auth.get_headers() == {
        "host": mock_transport_host,
        "x-api-key": "some-api-key",
    }
コード例 #2
0
async def main():

    # Should look like:
    # https://XXXXXXXXXXXXXXXXXXXXXXXXXX.appsync-api.REGION.amazonaws.com/graphql
    url = os.environ.get("AWS_GRAPHQL_API_ENDPOINT")
    api_key = os.environ.get("AWS_GRAPHQL_API_KEY")

    if url is None or api_key is None:
        print("Missing environment variables")
        sys.exit()

    # Extract host from url
    host = str(urlparse(url).netloc)

    print(f"Host: {host}")

    auth = AppSyncApiKeyAuthentication(host=host, api_key=api_key)

    transport = AppSyncWebsocketsTransport(url=url, auth=auth)

    async with Client(transport=transport) as session:

        subscription = gql("""
subscription onCreateMessage {
  onCreateMessage {
    message
  }
}
""")

        print("Waiting for messages...")

        async for result in session.subscribe(subscription):
            print(result)
コード例 #3
0
async def test_appsync_subscription_api_key(event_loop, server):

    from gql.transport.appsync_auth import AppSyncApiKeyAuthentication
    from gql.transport.appsync_websockets import AppSyncWebsocketsTransport

    path = "/graphql"
    url = f"ws://{server.hostname}:{server.port}{path}"

    auth = AppSyncApiKeyAuthentication(host=server.hostname,
                                       api_key=DUMMY_API_KEY)

    transport = AppSyncWebsocketsTransport(
        url=url, auth=auth, keep_alive_timeout=(5 * SEND_MESSAGE_DELAY))

    await default_transport_test(transport)
コード例 #4
0
async def test_appsync_subscription_variable_values_and_operation_name(
        event_loop, server):

    from gql.transport.appsync_auth import AppSyncApiKeyAuthentication
    from gql.transport.appsync_websockets import AppSyncWebsocketsTransport

    path = "/graphql"
    url = f"ws://{server.hostname}:{server.port}{path}"

    auth = AppSyncApiKeyAuthentication(host=server.hostname,
                                       api_key=DUMMY_API_KEY)

    transport = AppSyncWebsocketsTransport(
        url=url, auth=auth, keep_alive_timeout=(5 * SEND_MESSAGE_DELAY))

    client = Client(transport=transport)

    expected_messages = [
        f"Hello world {number}!" for number in range(NB_MESSAGES)
    ]
    received_messages = []

    async with client as session:
        subscription = gql(on_create_message_subscription_str)

        async for execution_result in session.subscribe(
                subscription,
                operation_name="onCreateMessage",
                variable_values={"key1": "val1"},
                get_execution_result=True,
        ):

            result = execution_result.data
            message = result["onCreateMessage"]["message"]
            print(f"Message received: '{message}'")

            received_messages.append(message)

            print(f"extensions received: {execution_result.extensions}")

            assert execution_result.extensions[
                "operation_name"] == "onCreateMessage"
            variables = execution_result.extensions["variables"]
            assert variables["key1"] == "val1"

    assert expected_messages == received_messages
コード例 #5
0
async def test_appsync_subscription_api_key_unauthorized(event_loop, server):

    from gql.transport.appsync_auth import AppSyncApiKeyAuthentication
    from gql.transport.appsync_websockets import AppSyncWebsocketsTransport
    from gql.transport.exceptions import TransportServerError

    path = "/graphql"
    url = f"ws://{server.hostname}:{server.port}{path}"

    auth = AppSyncApiKeyAuthentication(host=server.hostname, api_key="invalid")

    transport = AppSyncWebsocketsTransport(url=url, auth=auth)

    client = Client(transport=transport)

    with pytest.raises(TransportServerError) as exc_info:
        async with client as _:
            pass

    assert "You are not authorized to make this call." in str(exc_info)
コード例 #6
0
async def main():

    # Should look like:
    # https://XXXXXXXXXXXXXXXXXXXXXXXXXX.appsync-api.REGION.amazonaws.com/graphql
    url = os.environ.get("AWS_GRAPHQL_API_ENDPOINT")
    api_key = os.environ.get("AWS_GRAPHQL_API_KEY")

    if url is None or api_key is None:
        print("Missing environment variables")
        sys.exit()

    # Extract host from url
    host = str(urlparse(url).netloc)

    auth = AppSyncApiKeyAuthentication(host=host, api_key=api_key)

    transport = AIOHTTPTransport(url=url, auth=auth)

    async with Client(
        transport=transport,
        fetch_schema_from_transport=False,
    ) as session:

        query = gql(
            """
mutation createMessage($message: String!) {
  createMessage(input: {message: $message}) {
    id
    message
    createdAt
  }
}"""
        )

        variable_values = {"message": "Hello world!"}

        result = await session.execute(query, variable_values=variable_values)
        print(result)
コード例 #7
0
async def test_appsync_subscription_server_sending_an_error_without_an_id(
        event_loop, server):

    from gql.transport.appsync_auth import AppSyncApiKeyAuthentication
    from gql.transport.appsync_websockets import AppSyncWebsocketsTransport
    from gql.transport.exceptions import TransportServerError

    path = "/graphql"
    url = f"ws://{server.hostname}:{server.port}{path}"

    auth = AppSyncApiKeyAuthentication(host=server.hostname,
                                       api_key=DUMMY_API_KEY)

    transport = AppSyncWebsocketsTransport(url=url, auth=auth)

    client = Client(transport=transport)

    with pytest.raises(TransportServerError) as exc_info:
        async with client as _:
            pass

    assert "Sometimes AppSync will send you an error without an id" in str(
        exc_info)
コード例 #8
0
async def test_appsync_subscription_server_sending_a_not_json_answer(
        event_loop, server):

    from gql.transport.appsync_auth import AppSyncApiKeyAuthentication
    from gql.transport.appsync_websockets import AppSyncWebsocketsTransport
    from gql.transport.exceptions import TransportProtocolError

    path = "/graphql"
    url = f"ws://{server.hostname}:{server.port}{path}"

    auth = AppSyncApiKeyAuthentication(host=server.hostname,
                                       api_key=DUMMY_API_KEY)

    transport = AppSyncWebsocketsTransport(url=url, auth=auth)

    client = Client(transport=transport)

    with pytest.raises(TransportProtocolError) as exc_info:
        async with client as _:
            pass

    assert "Server did not return a GraphQL result: Something not json" in str(
        exc_info)
コード例 #9
0
def get_transport(args: Namespace) -> Optional[AsyncTransport]:
    """Instantiate a transport from the parsed command line arguments

    :param args: parsed command line arguments
    """

    # Get the url scheme from server parameter
    url = URL(args.server)

    # Validate scheme
    if url.scheme not in ["http", "https", "ws", "wss"]:
        raise ValueError("URL protocol should be one of: http, https, ws, wss")

    # Get extra transport parameters from command line arguments
    # (headers)
    transport_args = get_transport_args(args)

    # Either use the requested transport or autodetect it
    if args.transport == "auto":
        transport_name = autodetect_transport(url)
    else:
        transport_name = args.transport

    # Import the correct transport class depending on the transport name
    if transport_name == "aiohttp":
        from gql.transport.aiohttp import AIOHTTPTransport

        return AIOHTTPTransport(url=args.server, **transport_args)

    elif transport_name == "phoenix":
        from gql.transport.phoenix_channel_websockets import (
            PhoenixChannelWebsocketsTransport,
        )

        return PhoenixChannelWebsocketsTransport(url=args.server, **transport_args)

    elif transport_name == "websockets":
        from gql.transport.websockets import WebsocketsTransport

        transport_args["ssl"] = url.scheme == "wss"

        return WebsocketsTransport(url=args.server, **transport_args)

    else:

        from gql.transport.appsync_auth import AppSyncAuthentication

        assert transport_name in ["appsync_http", "appsync_websockets"]
        assert url.host is not None

        auth: AppSyncAuthentication

        if args.api_key:
            from gql.transport.appsync_auth import AppSyncApiKeyAuthentication

            auth = AppSyncApiKeyAuthentication(host=url.host, api_key=args.api_key)

        elif args.jwt:
            from gql.transport.appsync_auth import AppSyncJWTAuthentication

            auth = AppSyncJWTAuthentication(host=url.host, jwt=args.jwt)

        else:
            from gql.transport.appsync_auth import AppSyncIAMAuthentication
            from botocore.exceptions import NoRegionError

            try:
                auth = AppSyncIAMAuthentication(host=url.host)
            except NoRegionError:
                # A warning message has been printed in the console
                return None

        transport_args["auth"] = auth

        if transport_name == "appsync_http":
            from gql.transport.aiohttp import AIOHTTPTransport

            return AIOHTTPTransport(url=args.server, **transport_args)

        else:
            from gql.transport.appsync_websockets import AppSyncWebsocketsTransport

            try:
                return AppSyncWebsocketsTransport(url=args.server, **transport_args)
            except Exception:
                # This is for the NoCredentialsError but we cannot import it here
                return None