def test_mutation_type():
    data_types = {
        'Foo': Record[{
            'bar': Integer,
        }],
    }
    query_graph = Graph([Root([
        Field('getFoo', Integer, _noop, options=[
            Option('getterArg', TypeRef['Foo']),
        ]),
    ])], data_types)
    mutation_graph = Graph(query_graph.nodes + [Root([
        Field('setFoo', Integer, _noop, options=[
            Option('setterArg', TypeRef['Foo']),
        ]),
    ])], data_types=query_graph.data_types)
    assert introspect(query_graph, mutation_graph) == _schema([
        _type('Query', 'OBJECT', fields=[
            _field('getFoo', _non_null(_INT), args=[
                _ival('getterArg', _non_null(_iobj('IOFoo'))),
            ]),
        ]),
        _type('Mutation', 'OBJECT', fields=[
            _field('setFoo', _non_null(_INT), args=[
                _ival('setterArg', _non_null(_iobj('IOFoo'))),
            ]),
        ]),
        _type('Foo', 'OBJECT', fields=[
            _field('bar', _non_null(_INT)),
        ]),
        _type('IOFoo', 'INPUT_OBJECT', inputFields=[
            _ival('bar', _non_null(_INT)),
        ]),
    ], with_mutation=True)
示例#2
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'}}})
示例#3
0
async def test_simple_async(graph_name, sample_count):
    async def x_fields(fields, ids):
        return [[42 for _ in fields] for _ in ids]

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

    async 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, [AsyncGraphMetrics(graph_name)])

    query = q.Node([
        q.Field('a'),
        q.Link('x', q.Node([
            q.Field('id'),
        ])),
    ])

    engine = Engine(AsyncIOExecutor())

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

    result = await engine.execute(hl_graph, query)
    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
示例#4
0
def test_node_complex_fields():
    f1 = Mock(return_value=[1])
    f2 = Mock(return_value=[[{'f': 'marshes'}]])
    f3 = Mock(return_value=[[{'g': 'colline'}]])
    f4 = Mock(return_value=[[[{'h': 'magi'}]]])

    graph = Graph([
        Node('a', [
            Field('b', Optional[Record[{'f': Integer}]], f2),
            Field('c', Record[{'g': Integer}], f3),
            Field('d', Sequence[Record[{'h': Integer}]], f4),
        ]),
        Root([
            Link('e', Sequence[TypeRef['a']], f1, requires=None),
        ]),
    ])

    check_result(
        execute(graph, build([Q.e[Q.b[Q.f], Q.c[Q.g], Q.d[Q.h]]])),
        {'e': [{'b': {'f': 'marshes'},
                'c': {'g': 'colline'},
                'd': [{'h': 'magi'}]}]},
    )

    f1.assert_called_once_with()
    f2.assert_called_once_with(
        [q.Link('b', q.Node([q.Field('f')]))], [1],
    )
    f3.assert_called_once_with(
        [q.Link('c', q.Node([q.Field('g')]))], [1],
    )
    f4.assert_called_once_with(
        [q.Link('d', q.Node([q.Field('h')]))], [1],
    )
示例#5
0
def test_link_optional(value, expected):
    graph = Graph([
        Node('Bar', [
            Field('baz', Integer, _),
        ]),
        Node('Foo', [
            Link('bar', Optional[TypeRef['Bar']], _, requires=None),
        ]),
        Root([
            Link('foo', Optional[TypeRef['Foo']], _, requires=None),
        ]),
    ])
    query = build([
        Q.foo[Q.bar[Q.baz, ], ],
    ])
    index = Index()
    index[ROOT.node][ROOT.ident].update({
        'foo': Reference('Foo', 1),
    })
    index['Foo'][1].update({
        'bar': value,
    })
    index['Bar'][2].update({'baz': 42})
    result = Proxy(index, ROOT, query)
    assert Denormalize(graph, result).process(query) == {
        'foo': {
            'bar': expected,
        },
    }
示例#6
0
def test_type_ref():
    assert_dumps(
        Graph([
            Node('xeric', [
                Field('derrida', String, _),
            ]),
            Node('amb', [
                Field('loor', String, _),
                Link('cressy', TypeRef['xeric'], _, requires=None),
            ]),
            Node('offeree', [
                Field('abila', String, _),
                Link('ferber', Sequence[TypeRef['xeric']], _, requires=None),
            ]),
        ]),
        """
        type xeric
          Record
            :derrida String

        type amb
          Record
            :loor String
            :cressy xeric

        type offeree
          Record
            :abila String
            :ferber
              List xeric
        """,
    )
示例#7
0
def test_conflicting_fields():
    x_data = {'xN': {'a': 42}}

    @listify
    def x_fields(fields, ids):
        for i in ids:
            yield ['{}-{}'.format(x_data[i][f.name], f.options['k'])
                   for f in fields]

    graph = Graph([
        Node('X', [
            Field('a', None, x_fields, options=[Option('k', Integer)]),
        ]),
        Root([
            Link('x1', TypeRef['X'], lambda: 'xN', requires=None),
            Link('x2', TypeRef['X'], lambda: 'xN', requires=None),
        ]),
    ])

    result = execute(graph, q.Node([
        q.Link('x1', q.Node([q.Field('a', options={'k': 1})])),
        q.Link('x2', q.Node([q.Field('a', options={'k': 2})])),
    ]))
    check_result(result, {
        'x1': {'a': '42-1'},
        'x2': {'a': '42-2'},
    })
示例#8
0
def test_root_link_alias():
    data = {
        'xN': {'a': 1, 'b': 2},
    }

    @listify
    def x_fields(fields, ids):
        for i in ids:
            yield [data[i][f.name] for f in fields]

    graph = Graph([
        Node('X', [
            Field('a', None, x_fields),
            Field('b', None, x_fields),
        ]),
        Root([
            Link('x', TypeRef['X'], lambda: 'xN', requires=None),
        ]),
    ])
    result = execute(graph, q.Node([
        q.Link('x', q.Node([q.Field('a')]), alias='x1'),
        q.Link('x', q.Node([q.Field('b')]), alias='x2'),
    ]))
    check_result(result, {
        'x1': {'a': 1},
        'x2': {'b': 2},
    })
示例#9
0
def test_field_complex():
    assert_dumps(
        Graph([
            Root([
                Field('behave', Optional[Record[{
                    'burieth': Integer
                }]], _),
                Field('gemara', Record[{
                    'trevino': Integer
                }], _),
                Field('riffage', Sequence[Record[{
                    'shophar': Integer
                }]], _),
            ])
        ]),
        """
        type behave
          Option
            Record
              :burieth Integer

        type gemara
          Record
            :trevino Integer

        type riffage
          List
            Record
              :shophar Integer
        """,
    )
示例#10
0
def test_links():
    fb = Mock(return_value=[1])
    fc = Mock(return_value=[2])
    fi = Mock(return_value=[3])
    fd = Mock(return_value=[['boners']])
    fe = Mock(return_value=[['julio']])

    graph = Graph([
        Node('a', [
            Field('d', None, fd),
            Field('e', None, fe),
        ]),
        Root([
            Field('i', None, fi),
            Link('b', Sequence[TypeRef['a']], fb, requires=None),
            Link('c', Sequence[TypeRef['a']], fc, requires='i'),
        ]),
    ])

    result = execute(graph, build([Q.b[Q.d], Q.c[Q.e]]))
    check_result(result, {'b': [{'d': 'boners'}],
                          'c': [{'e': 'julio'}]})

    fi.assert_called_once_with([q.Field('i')])
    fb.assert_called_once_with()
    fc.assert_called_once_with(3)
    fd.assert_called_once_with([q.Field('d')], [1])
    fe.assert_called_once_with([q.Field('e')], [2])
示例#11
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
示例#12
0
def test_links():
    f1 = Mock(return_value=[1])
    f2 = Mock(return_value=[2])
    f3 = Mock(return_value=[['boners']])
    f4 = Mock(return_value=[['julio']])

    graph = Graph([
        Node('a', [
            Field('d', None, f3),
            Field('e', None, f4),
        ]),
        Root([
            Link('b', Sequence[TypeRef['a']], f1, requires=None),
            Link('c', Sequence[TypeRef['a']], f2, requires=None),
        ]),
    ])

    result = execute(graph, build([Q.b[Q.d], Q.c[Q.e]]))
    check_result(result, {'b': [{'d': 'boners'}], 'c': [{'e': 'julio'}]})
    assert result.index == {'a': {1: {'d': 'boners'}, 2: {'e': 'julio'}}}

    f1.assert_called_once_with()
    f2.assert_called_once_with()
    with reqs_eq_patcher():
        f3.assert_called_once_with([query.Field('d')], [1])
        f4.assert_called_once_with([query.Field('e')], [2])
示例#13
0
def test_pass_context_link():
    f1 = pass_context(Mock(return_value=[1]))
    f2 = Mock(return_value=[['boners']])

    graph = Graph([
        Node('a', [
            Field('b', None, f2),
        ]),
        Root([
            Link('c', Sequence[TypeRef['a']], f1, requires=None),
        ]),
    ])

    result = execute(graph, build([Q.c[Q.b]]), {'fibs': 'dossil'})
    check_result(result, {'c': [{'b': 'boners'}]})
    assert result.index == {'a': {1: {'b': 'boners'}}}

    f1.assert_called_once_with(ANY)
    with reqs_eq_patcher():
        f2.assert_called_once_with([query.Field('b')], [1])

    ctx = f1.call_args[0][0]
    assert isinstance(ctx, Context)
    assert ctx['fibs'] == 'dossil'
    with pytest.raises(KeyError) as err:
        _ = ctx['invalid']  # noqa
    err.match('is not specified in the query context')
示例#14
0
def test_empty_nodes():
    graph = Graph([
        Node('Foo', []),
        Root([]),
    ])
    with pytest.raises(ValueError) as err:
        apply(graph, [GraphQLIntrospection(graph)])
    assert err.match('No fields in the Foo node')
    assert err.match('No fields in the Root node')
示例#15
0
def test_field():
    assert_dumps(
        Graph([Root([
            Field('leones', String, _),
        ])]),
        """
        type leones String
        """,
    )
示例#16
0
def test_list_simple():
    assert_dumps(
        Graph([Root([
            Field('askest', Sequence[Integer], _),
        ])]),
        """
        type askest
          List Integer
        """,
    )
示例#17
0
def test_dict_simple():
    assert_dumps(
        Graph([Root([
            Field('kasseri', Mapping[String, Integer], _),
        ])]),
        """
        type kasseri
          Dict String Integer
        """,
    )
示例#18
0
def test_field_option_valid(option, args, result):
    f = Mock(return_value=['baking'])
    graph = Graph([
        Root([
            Field('auslese', None, f, options=[option]),
        ]),
    ])
    check_result(execute(graph, build([Q.auslese(**args)])),
                 {'auslese': 'baking'})
    f.assert_called_once_with([q.Field('auslese', options=result)])
示例#19
0
def test_field_option_missing():
    graph = Graph([
        Root([
            Field('poofy', None, Mock(), options=[Option('mohism', None)]),
        ]),
    ])
    with pytest.raises(TypeError) as err:
        execute(graph, build([Q.poofy]))
    err.match('^Required option "mohism" for Field\(\'poofy\', '
              '(.*) was not provided$')
示例#20
0
文件: sdl.py 项目: kindermax/hiku
    def visit_graph(self, obj):
        def skip(node):
            if node.name is None:
                # check if it is a Root node from introspection
                return '__schema' in node.fields_map

            return node.name.startswith('__')

        return Graph(
            [self.visit(node) for node in obj.items if not skip(node)],
            obj.data_types)
示例#21
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',)]
示例#22
0
def test_list_complex():
    assert_dumps(
        Graph([Root([
            Field('gladden', Sequence[Sequence[Integer]], _),
        ])]),
        """
        type gladden
          List
            List Integer
        """,
    )
示例#23
0
def test_typename():
    graph = Graph([
        Node('Bar', [
            Field('baz', Integer, _),
        ]),
        Node('Foo', [
            Link('bar', Sequence[TypeRef['Bar']], _, requires=None),
        ]),
        Root([
            Link('foo', TypeRef['Foo'], _, requires=None),
        ]),
    ])
    query = read("""
    query {
        __typename
        foo {
            __typename
            bar {
                __typename
                baz
            }
        }
    }
    """)
    index = Index()
    index[ROOT.node][ROOT.ident].update({
        'foo': Reference('Foo', 1),
    })
    index['Foo'][1].update({
        'bar': [Reference('Bar', 2), Reference('Bar', 3)],
    })
    index['Bar'][2].update({
        'baz': 42
    })
    index['Bar'][3].update({
        'baz': 43
    })
    result = Proxy(index, ROOT, query)
    assert DenormalizeGraphQL(graph, result, 'Query').process(query) == {
        '__typename': 'Query',
        'foo': {
            '__typename': 'Foo',
            'bar': [
                {
                    '__typename': 'Bar',
                    'baz': 42,
                },
                {
                    '__typename': 'Bar',
                    'baz': 43,
                },
            ],
        },
    }
示例#24
0
def test_introspection_query():
    graph = Graph([
        Node('flexed', [
            Field('yari',
                  Boolean,
                  _noop,
                  options=[
                      Option('membuka', Sequence[String], default=['frayed']),
                      Option('modist',
                             Optional[Integer],
                             default=None,
                             description='callow'),
                  ]),
        ]),
        Node('decian', [
            Field('dogme', Integer, _noop),
            Link('clarkia', Sequence[TypeRef['flexed']], _noop, requires=None),
        ]),
        Root([
            Field('_cowered', String, _noop),
            Field('entero', Float, _noop),
            Link('toma', Sequence[TypeRef['decian']], _noop, requires=None),
        ]),
    ])
    assert introspect(graph) == _schema([
        _type('flexed',
              'OBJECT',
              fields=[
                  _field('yari',
                         _non_null(_BOOL),
                         args=[
                             _ival('membuka',
                                   _seq_of(_STR),
                                   defaultValue='["frayed"]'),
                             _ival('modist',
                                   _INT,
                                   defaultValue='null',
                                   description='callow'),
                         ]),
              ]),
        _type('decian',
              'OBJECT',
              fields=[
                  _field('dogme', _non_null(_INT)),
                  _field('clarkia', _seq_of(_obj('flexed'))),
              ]),
        _type('Query',
              'OBJECT',
              fields=[
                  _field('entero', _non_null(_FLOAT)),
                  _field('toma', _seq_of(_obj('decian'))),
              ]),
    ])
def test_untyped_fields():
    graph = Graph([
        Root([
            Field('untyped', None, _noop),
            Field('any_typed', Any, _noop),
        ]),
    ])
    assert introspect(graph) == _schema([
        _type('Query', 'OBJECT', fields=[
            _field('untyped', _ANY),
            _field('any_typed', _ANY),
        ]),
    ])
示例#26
0
def test_dict_complex():
    assert_dumps(
        Graph([
            Root([
                Field('trunks', Mapping[String, Mapping[Integer, Integer]], _),
            ])
        ]),
        """
        type trunks
          Dict String
            Dict Integer Integer
        """,
    )
示例#27
0
def test_link_option_missing():
    graph = Graph([
        Node('slices', [
            Field('papeete', None, Mock()),
        ]),
        Root([
            Link('eclairs', Sequence[TypeRef['slices']], Mock(), requires=None,
                 options=[Option('nocks', None)]),
        ]),
    ])
    with pytest.raises(TypeError) as err:
        execute(graph, build([Q.eclairs[Q.papeete]]))
    err.match(r'^Required option "nocks" for Link\(\'eclairs\', '
              r'(.*) was not provided$')
示例#28
0
def test_root_node_field_func_result_validation(value):
    with pytest.raises(TypeError) as err:
        execute(
            Graph([
                Root([
                    Node('a', [Field('b', None, Mock(return_value=value))]),
                ]),
            ]),
            build([Q.a[Q.b]]),
        )
    err.match(
        re.escape("Can't store field values, node: 'a', fields: ['b'], "
                  "expected: list (len: 1), returned: {value!r}".format(
                      value=value)))
示例#29
0
def test_any_in_option():
    graph = Graph([
        Root([
            Field('get', None, None, options=[
                Option('foo', Mapping[String, Any]),
            ]),
        ]),
    ])
    assert validate(graph, q.Node([
        q.Field('get', options={'foo': {u'key': 1}}),
    ])) == []
    assert validate(graph, q.Node([
        q.Field('get', options={'foo': 'bar'}),
    ])) == ['Invalid value for option "root.get:foo", '
            '"str" instead of Mapping[String, Any]']
示例#30
0
def test_falsy_link_result():
    x_fields = Mock(return_value=[[42]])
    graph = Graph([
        Node('X', [
            Field('a', None, x_fields),
        ]),
        Root([
            Link('x', TypeRef['X'], lambda: 0, requires=None),
        ]),
    ])
    result = execute(graph, q.Node([
        q.Link('x', q.Node([q.Field('a')])),
    ]))
    assert denormalize(graph, result) == {'x': {'a': 42}}
    x_fields.assert_called_once_with([q.Field('a')], [0])