def test_multiple_chunks(schema, curl, unix_endpoint):

    state = dict(chunks=0)
    old_data_received = aiographql.ConnectionFromClient.data_received

    def new_data_received(self, chunk):
        state['chunks'] += 1
        old_data_received(self, chunk)

    aiographql.ConnectionFromClient.data_received = new_data_received

    try:
        servers = aiographql.serve(schema, listen=[unix_endpoint], run=False)
        loop = asyncio.get_event_loop()

        async def client():
            result = await curl(unix_endpoint, '''{
  me {
    # {comment}
    id
  }
}'''.replace('{comment}',
             's' * 10 * 1024))  # enough to produce multiple chunks
            await servers.close()
            return result

        result = loop.run_until_complete(client())
        assert result == {'data': {'me': {'id': '42'}}}
        assert state['chunks'] >= 2

    finally:
        aiographql.ConnectionFromClient.data_received = old_data_received
def test_simple(schema, curl, unix_endpoint):

    servers = aiographql.serve(schema, listen=[unix_endpoint], run=False)
    loop = asyncio.get_event_loop()

    async def client():
        result = await curl(
            unix_endpoint, '''{
  me {
    id
    name
    friends {
      id
      name
    }
  }
}''')
        await servers.close()
        return result

    result = loop.run_until_complete(client())
    assert result == {
        'data': {
            'me': {
                'id': '42',
                'name': 'John',
                'friends': []
            }
        }
    }
Exemple #3
0
def test_exception_handler(schema, curl, tcp_endpoint):

    state = dict(loop=None, context=None)

    def exception_handler(loop, context):
        state.update(loop=loop, context=context)

    servers = aiographql.serve(schema, listen=[tcp_endpoint], exception_handler=exception_handler, run=False)
    loop = asyncio.get_event_loop()

    async def client():
        result = await curl(tcp_endpoint, '''{
    me {
        password
    }
}''')
        await servers.close()
        return result

    result = loop.run_until_complete(client())

    assert result == {'errors': [{'locations': [{'line': 3, 'column': 9}], 'message': 'Cannot query field "password" on type "User".'}]}
    assert repr(state['loop']).startswith('<uvloop.Loop ')

    context = state['context']
    assert isinstance(context, dict)
    assert context['message'] == 'Cannot query field "password" on type "User".'
    assert repr(context['exception']) == '''GraphQLError('Cannot query field "password" on type "User".',)'''
    assert repr(context['protocol']).startswith('<aiographql.ConnectionFromClient object at 0x')

    remote_addr = context['transport'].get_extra_info('peername')
    assert isinstance(remote_addr, tuple)
    assert len(remote_addr) == 2
    host, port = remote_addr
    assert host == '127.0.0.1'
    assert isinstance(port, int)

    assert context['headers'] == b'''POST / HTTP/1.1
Host: localhost:25100
Origin: null
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,ru;q=0.8
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36
Content-Type: application/json
Accept: application/json
Connection: keep-alive
Content-Length: 89'''.replace(b'\n', b'\r\n')

    assert context['request'] == {
        'variables': None,
        'operationName': None,
        'query': '''{
    me {
        password
    }
}'''}
def test_listen_tcp(schema, curl, tcp_endpoint):

    servers = aiographql.serve(schema, listen=[tcp_endpoint], run=False)
    loop = asyncio.get_event_loop()

    async def client():
        result = await curl(tcp_endpoint, '{me {id}}')
        await servers.close()
        return result

    result = loop.run_until_complete(client())
    assert result == {'data': {'me': {'id': '42'}}}
def _test_get_context(schema, curl, unix_endpoint, get_context):
    servers = aiographql.serve(schema,
                               listen=[unix_endpoint],
                               get_context=get_context,
                               run=False)
    loop = asyncio.get_event_loop()

    async def client():
        result = await curl(
            unix_endpoint,
            '{me {id}}',
            extra_headers=['Authorization: Bearer {}'.format(JWT)])
        await servers.close()
        return result

    result = loop.run_until_complete(client())
    assert result == {'data': {'me': {'id': '1042'}}}
def test_listen_unsupported(schema, curl, tcp_endpoint):

    contexts = []

    def exception_handler(loop, context):
        contexts.append(context)

    unsupported_endpoint = tcp_endpoint.copy()
    unsupported_endpoint['protocol'] = 'udp'

    servers = aiographql.serve(schema,
                               listen=[unsupported_endpoint],
                               exception_handler=exception_handler,
                               run=False)
    loop = asyncio.get_event_loop()
    loop.run_until_complete(servers.close())

    assert len(contexts) == 1
    assert str(contexts[0]['exception']) == "Unsupported protocol='udp'"
def test_concurrency(schema, curl, unix_endpoint):

    servers = aiographql.serve(schema, listen=[unix_endpoint], run=False)
    loop = asyncio.get_event_loop()

    async def clients():

        started_at = time.perf_counter()
        sloths = [
            curl(unix_endpoint, 'query Sloth($seconds: Float) { slowDb(seconds: $seconds) }', {"seconds": seconds})
            for seconds in [0.5, 0.7, 0.5, 0.7, 0.5]
        ]
        await asyncio.gather(*sloths)
        result = time.perf_counter() - started_at

        await servers.close()
        return result

    result = loop.run_until_complete(clients())
    assert 0.70 < result < 0.75