Exemplo n.º 1
0
def subscribe(query, params=None):
    # Using websocket to subscribe to the status of the mission created
    transport_async = WebsocketsTransport(
        url=SERVER_URL.replace("http", "ws"),
        init_payload={"Auth-Key": "sample_auth_key"})
    client_async = Client(transport=transport_async,
                          fetch_schema_from_transport=True)
    return client_async.subscribe(gql(query), variable_values=params)
def test_websocket_subscription_sync_graceful_shutdown(server, subscription_str):
    """Note: this test will simulate a control-C happening while a sync subscription
    is in progress. To do that we will throw a KeyboardInterrupt exception inside
    the subscription async generator.

    The code should then do a clean close:
      - send stop messages for each active query
      - send a connection_terminate message
    Then the KeyboardInterrupt will be reraise (to warn potential user code)

    This test does not work on Windows but the behaviour with Windows is correct.
    """
    from gql.transport.websockets import WebsocketsTransport

    url = f"ws://{server.hostname}:{server.port}/graphql"
    print(f"url = {url}")

    sample_transport = WebsocketsTransport(url=url)

    client = Client(transport=sample_transport)

    count = 10
    subscription = gql(subscription_str.format(count=count))

    interrupt_task = None

    with pytest.raises(KeyboardInterrupt):
        for result in client.subscribe(subscription):

            number = result["number"]
            print(f"Number received: {number}")

            assert number == count

            if count == 5:

                # Simulate a KeyboardInterrupt in the generator
                with warnings.catch_warnings():
                    warnings.filterwarnings(
                        "ignore", message="There is no current event loop"
                    )
                    interrupt_task = asyncio.ensure_future(
                        client.session._generator.athrow(KeyboardInterrupt)
                    )

            count -= 1

    assert count == 4

    # Catch interrupt_task exception to remove warning
    interrupt_task.exception()

    # Check that the server received a connection_terminate message last
    assert logged_messages.pop() == '{"type": "connection_terminate"}'
Exemplo n.º 3
0
    def test_code():
        sample_transport = AIOHTTPTransport(url=url)

        client = Client(transport=sample_transport)

        query = gql(query1_str)

        # Note: subscriptions are not supported on the aiohttp transport
        # But we add this test in order to have 100% code coverage
        # It is to check that we will correctly set an event loop
        # in the subscribe function if there is none (in a Thread for example)
        # We cannot test this with the websockets transport because
        # the websockets transport will set an event loop in its init

        with pytest.raises(NotImplementedError):
            for result in client.subscribe(query):
                pass
    def test_code():
        path = "/graphql"
        url = f"ws://{server.hostname}:{server.port}{path}"
        sample_transport = WebsocketsTransport(url=url)

        client = Client(transport=sample_transport)

        count = 10
        subscription = gql(subscription_str.format(count=count))

        for result in client.subscribe(subscription):

            number = result["number"]
            print(f"Number received: {number}")

            assert number == count
            count -= 1

        assert count == -1
def test_websocket_subscription_sync(server, subscription_str):
    from gql.transport.websockets import WebsocketsTransport

    url = f"ws://{server.hostname}:{server.port}/graphql"
    print(f"url = {url}")

    sample_transport = WebsocketsTransport(url=url)

    client = Client(transport=sample_transport)

    count = 10
    subscription = gql(subscription_str.format(count=count))

    for result in client.subscribe(subscription):

        number = result["number"]
        print(f"Number received: {number}")

        assert number == count
        count -= 1

    assert count == -1
Exemplo n.º 6
0
def test_custom_scalar_subscribe_in_input_variable_values_serialized():

    client = Client(schema=schema)

    query = gql("subscription spendAll($money: Money) {spend(money: $money)}")

    money_value = Money(10, "DM")

    variable_values = {"money": money_value}

    expected_result = {"spend": Money(10, "DM")}

    for result in client.subscribe(
        query,
        variable_values=variable_values,
        root_value=root_value,
        serialize_variables=True,
        parse_result=True,
    ):
        print(f"result = {result!r}")
        assert isinstance(result["spend"], Money)
        expected_result["spend"] = Money(expected_result["spend"].amount - 1, "DM")
        assert expected_result == result
Exemplo n.º 7
0
transport = WebsocketsTransport(
    url=SUBSCRIPTION_ADDRESS,
    headers={
    'x-tenant-id': TENANT_ID, 
    "x-tenant-key": TENANT_KEY
})

client = Client(
    transport=transport,
    fetch_schema_from_transport=True,
)

query = gql('''
 subscription {
  signalAdded {
    id
    mac
    timestamp
    unit
    type
    data {
        rawValue
    }
  }
}
''')


for result in client.subscribe(query):
    print (result)