Beispiel #1
0
def test_complex_field():
    engine = Engine(SyncExecutor())

    def get_a(fields, ids):
        return [[{'s': 'bar'} for _ in fields] for _ in ids]

    ll_graph = Graph([
        Node('Foo', [
            Field('a', Record[{
                's': String
            }], get_a),
        ]),
    ])
    foo_sg = SubGraph(ll_graph, 'Foo')
    hl_graph = Graph([
        Node('Foo', [
            Field('a', Record[{
                's': String
            }], foo_sg),
        ]),
        Root([
            Link('foo', TypeRef['Foo'], lambda: 1, requires=None),
        ]),
    ])
    result = engine.execute(hl_graph, build([Q.foo[Q.a[Q.s]]]))
    check_result(result, {'foo': {'a': {'s': 'bar'}}})
Beispiel #2
0
def test_batch_endpoint(sync_graph):
    endpoint = BatchGraphQLEndpoint(Engine(SyncExecutor()), sync_graph)

    assert endpoint.dispatch([]) == []

    result = endpoint.dispatch({'query': '{answer}'})
    assert result == {'data': {'answer': '42'}}

    batch_result = endpoint.dispatch([
        {
            'query': '{answer}'
        },
        {
            'query': '{__typename}'
        },
    ])
    assert batch_result == [
        {
            'data': {
                'answer': '42'
            }
        },
        {
            'data': {
                '__typename': 'Query'
            }
        },
    ]
Beispiel #3
0
def execute(graph, query_string):
    graphql_endpoint = FederatedGraphQLEndpoint(
        Engine(SyncExecutor()),
        graph,
    )

    return graphql_endpoint.dispatch(query_string)
Beispiel #4
0
def test_with_pass_context(graph_name, sample_count):
    def root_fields1(fields):
        return [1 for _ in fields]

    @pass_context
    def root_fields2(ctx, fields):
        return [2 for _ in fields]

    graph = Graph([
        Root([
            Field('a', None, root_fields1),
            Field('b', None, root_fields2),
        ]),
    ])

    graph = apply(graph, [GraphMetrics(graph_name)])

    assert sample_count('Root', 'a') is None
    assert sample_count('Root', 'b') is None

    result = Engine(SyncExecutor()).execute(
        graph, q.Node([
            q.Field('a'),
            q.Field('b'),
        ]))
    check_result(result, {
        'a': 1,
        'b': 2,
    })

    assert sample_count('Root', 'a') == 1.0
    assert sample_count('Root', 'b') == 1.0
def introspect(graph):
    engine = Engine(SyncExecutor())
    graph = apply(graph, [GraphQLIntrospection()])

    query = read(QUERY)
    errors = validate(graph, query)
    assert not errors

    norm_result = engine.execute(graph, query)
    return denormalize(graph, norm_result, query)
Beispiel #6
0
def test_process_ordered_node():
    ordering = []

    def f1(fields):
        names = tuple(f.name for f in fields)
        ordering.append(names)
        return names

    def f2(fields):
        return f1(fields)

    def f3():
        ordering.append('x1')
        return 'x1'

    @listify
    def f4(fields, ids):
        for i in ids:
            yield ['{}-e'.format(i) for _ in fields]

    graph = Graph([
        Node('X', [
            Field('e', None, f4),
        ]),
        Root([
            Field('a', None, f1),
            Field('b', None, f1),
            Field('c', None, f2),
            Field('d', None, f2),
            Link('x', TypeRef['X'], f3, requires=None),
        ]),
    ])
    query = q.Node([
        q.Field('d'),
        q.Field('b'),
        q.Field('a'),
        q.Link('x', q.Node([
            q.Field('e'),
        ])),
        q.Field('c'),
    ], ordered=True)

    engine = Engine(SyncExecutor())
    result = engine.execute(graph, query)
    check_result(result, {
        'a': 'a',
        'b': 'b',
        'c': 'c',
        'd': 'd',
        'x': {
            'e': 'x1-e',
        },
    })
    assert ordering == [('d',), ('b', 'a'), 'x1', ('c',)]
def introspect(query_graph, mutation_graph=None):
    engine = Engine(SyncExecutor())
    query_graph = apply(query_graph, [
        GraphQLIntrospection(query_graph, mutation_graph),
    ])

    query = read(QUERY)
    errors = validate(query_graph, query)
    assert not errors

    norm_result = engine.execute(query_graph, query)
    return denormalize(query_graph, norm_result)
Beispiel #8
0
def test_simple_sync(graph_name, sample_count):
    def x_fields(fields, ids):
        return [[42 for _ in fields] for _ in ids]

    def root_fields(fields):
        return [1 for _ in fields]

    def x_link():
        return 2

    ll_graph = Graph([
        Node('X', [
            Field('id', None, x_fields),
        ]),
    ])

    x_sg = SubGraph(ll_graph, 'X')

    hl_graph = Graph([
        Node('X', [
            Field('id', None, x_sg),
        ]),
        Root([
            Field('a', None, root_fields),
            Link('x', TypeRef['X'], x_link, requires=None),
        ]),
    ])

    hl_graph = apply(hl_graph, [GraphMetrics(graph_name)])

    assert sample_count('Root', 'a') is None
    assert sample_count('Root', 'x') is None
    assert sample_count('X', 'id') is None

    result = Engine(SyncExecutor()).execute(
        hl_graph,
        q.Node([
            q.Field('a'),
            q.Link('x', q.Node([
                q.Field('id'),
            ])),
        ]))
    check_result(result, {
        'a': 1,
        'x': {
            'id': 42,
        },
    })

    assert sample_count('Root', 'a') == 1.0
    assert sample_count('Root', 'x') == 1.0
    assert sample_count('X', 'id') == 1.0
Beispiel #9
0
def test():
    for query in [query_graphql(), query_simple(), query_python()]:
        hiku_engine = Engine(SyncExecutor())
        result = hiku_engine.execute(GRAPH, query)
        result = denormalize(GRAPH, result, query)
        assert result == \
        {
            "characters": [
                {
                    "name": "James T. Kirk",
                    "species": "Human"
                },
                {
                    "name": "Spock",
                    "species": "Vulcan/Human"
                },
                {
                    "name": "Leonard McCoy",
                    "species": "Human"
                }
            ]
        }
Beispiel #10
0
GRAPH = Graph([
    Node('Character', [
        Field('name', None, character_data),
        Field('species', None, character_data),
    ]),
    Root([
        Link('characters',
             Sequence[TypeRef['Character']],
             to_characters_link,
             requires=None),
    ]),
])

# test

hiku_engine = Engine(SyncExecutor())


def execute(graph, query_string):
    query = read(query_string)
    result = hiku_engine.execute(graph, query)
    return denormalize(graph, result)


def test():
    result = execute(GRAPH, '[{:characters [:name :species]}]')
    assert result == {
        "characters": [
            {
                "species": "Human",
                "name": "James T. Kirk",
Beispiel #11
0
def test_endpoint(sync_graph):
    endpoint = GraphQLEndpoint(Engine(SyncExecutor()), sync_graph)
    result = endpoint.dispatch({'query': '{answer}'})
    assert result == {'data': {'answer': '42'}}
Beispiel #12
0
    try:
        query = read(data['query'], data.get('variables'))
        errors = validate(app.config['GRAPH'], query)
        if errors:
            result = {'errors': [{'message': e} for e in errors]}
        else:
            result = hiku_engine.execute(app.config['GRAPH'],
                                         query,
                                         ctx=app.config['HIKU_CTX'])
            result = {'data': denormalize(app.config['GRAPH'], result, query)}
    except Exception as err:
        result = {'errors': [{'message': repr(err)}]}
    return jsonify(result)


if __name__ == "__main__":
    sa_engine = create_engine('sqlite://',
                              connect_args={'check_same_thread': False},
                              poolclass=StaticPool)
    setup_db(sa_engine)

    app.config['HIKU_ENGINE'] = Engine(SyncExecutor())
    app.config['HIKU_CTX'] = {SA_ENGINE_KEY: sa_engine}

    graph = get_graph(get_queries(hiku.sources.sqlalchemy, SA_ENGINE_KEY,
                                  SyncQueries))
    graph = apply(graph, [GraphQLIntrospection()])
    app.config['GRAPH'] = graph

    app.run()
Beispiel #13
0
    ]),
    Root([
        Link(
            'cart',
            Optional[TypeRef['Cart']],
            direct_link_id,
            requires=None,
            options=[Option('id', Integer)],
        ),
    ]),
])

app = Flask(__name__)

graphql_endpoint = FederatedGraphQLEndpoint(
    Engine(SyncExecutor()),
    QUERY_GRAPH,
)


@app.route('/graphql', methods={'POST'})
def handle_graphql():
    data = request.get_json()
    result = graphql_endpoint.dispatch(data)
    resp = jsonify(result)
    return resp


def main():
    logging.basicConfig()
    app.run(port=5000)
Beispiel #14
0
def execute(graph, query_, ctx=None):
    engine = Engine(SyncExecutor())
    return engine.execute(graph, query_, ctx=ctx)