def test_filters():
    test_parent_1 = ParentModel(name="Adriel")
    test_parent_2 = ParentModel(name="Carolina")
    test_parent_3 = ParentModel(name="Cotu")
    session.add(test_parent_1)
    session.add(test_parent_2)
    session.add(test_parent_3)
    session.commit()
    schema = R.Schema(R.Query)
    query = '{{parentModels (ids:[{}, {}]) {{id, name}} }}'.format(test_parent_1.id, test_parent_2.id)
    results = graphql(schema, query)
    expected_results = {
        'parentModels': [
            {'name': 'Adriel', 'id': test_parent_1.id}, {'name': 'Carolina', 'id': test_parent_2.id}
        ]
    }
    assert results.data == expected_results
    query = '{{parentModels (ids:[{}, {}], name:"Adriel") {{id, name}} }}'.format(test_parent_1.id, test_parent_2.id)
    results = graphql(schema, query)
    expected_results = {
        'parentModels': [
            {'name': 'Adriel', 'id': test_parent_1.id}
        ]
    }
    assert results.data == expected_results
    session.delete(test_parent_3)
    session.delete(test_parent_2)
    session.delete(test_parent_1)
    session.commit()
def test_normal_querying():
    test_parent_1 = ParentModel(name="Adriel")
    test_parent_2 = ParentModel(name="Carolina")
    session.add(test_parent_1)
    session.add(test_parent_2)
    session.commit()
    schema = R.Schema(R.Query)

    query = "{parentModels {id, name}}"
    results = graphql(schema, query)
    assert len(results.data.get("parentModels")) == 2

    test_child_1 = ChildModel(name="Oona", parent_id=test_parent_1.id)
    session.add(test_child_1)
    session.commit()
    query = "{childModel {id,name, parent {id, name}}}"
    results = graphql(schema, query)
    expected_results = {
        "childModel": {
            "id": test_child_1.id,
            "name": "Oona",
            "parent": {
                "id": test_parent_1.id,
                "name": test_parent_1.name
            }
        }
    }
    assert results.data == expected_results
    query = '{additionalFilters (name:"Someting"){id,name}'
    assert len(results.errors) == 0
    session.delete(test_parent_2)
    session.delete(test_parent_1)
    session.commit()
def test_cannot_use_client_schema_for_general_execution():
    customScalar = GraphQLScalarType(name='CustomScalar',
                                     serialize=lambda: None)

    schema = GraphQLSchema(query=GraphQLObjectType(
        name='Query',
        fields={
            'foo':
            GraphQLField(GraphQLString,
                         args=OrderedDict([('custom1',
                                            GraphQLArgument(customScalar)),
                                           ('custom2',
                                            GraphQLArgument(customScalar))]))
        }))

    introspection = graphql(schema, introspection_query)
    client_schema = build_client_schema(introspection.data)

    class data:
        foo = 'bar'

    result = graphql(
        client_schema,
        'query NoNo($v: CustomScalar) { foo(custom1: 123, custom2: $v) }',
        data, {'v': 'baz'})

    assert result.data == {'foo': None}
    assert [format_error(e) for e in result.errors] == [{
        'locations': [{
            'column': 32,
            'line': 1
        }],
        'message':
        'Client Schema cannot be used for execution.'
    }]
def _test_schema(server_schema):
    initial_introspection = graphql(server_schema, introspection_query)
    client_schema = build_client_schema(initial_introspection.data)
    second_introspection = graphql(client_schema, introspection_query)
    assert initial_introspection.data == second_introspection.data

    return client_schema
def _test_schema(server_schema):
    initial_introspection = graphql(server_schema, introspection_query)
    client_schema = build_client_schema(initial_introspection.data)
    second_introspection = graphql(client_schema, introspection_query)
    assert initial_introspection.data == second_introspection.data

    return client_schema
예제 #6
0
def test_custom_scalar_type():
    R = TypeRegistry()

    def serialize_date_time(dt):
        assert isinstance(dt, datetime.datetime)
        return dt.isoformat()

    def parse_literal(node):
        if isinstance(node, ast.StringValue):
            return datetime.datetime.strptime(node.value, "%Y-%m-%dT%H:%M:%S.%f")

    def parse_value(value):
        return datetime.datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%f")

    DateTimeType = GraphQLScalarType(name='DateTime', serialize=serialize_date_time,
                                     parse_literal=parse_literal,
                                     parse_value=parse_value)
    R(DateTimeType)

    class Query(R.ObjectType):
        datetime = R.DateTime(args={
            'in': R.DateTime
        })

        def resolve_datetime(self, obj, args, info):
            return args.get('in')

    now = datetime.datetime.now()
    isoformat = now.isoformat()

    Schema = R.Schema(R.Query)

    response = graphql(Schema, '''
        {
            datetime(in: "%s")
        }

    ''' % isoformat)

    assert not response.errors
    assert response.data == {
        'datetime': isoformat
    }

    response = graphql(Schema, '''
        query Test($date: DateTime) {
            datetime(in: $date)
        }

    ''', args={
        'date': isoformat
    })

    assert not response.errors
    assert response.data == {
        'datetime': isoformat
    }
예제 #7
0
def test_allows_fetching():
    query = '''
    {
      usernames(usernames:["dschafer", "leebyron", "schrockn"]) {
        username
        url
      }
    }
    '''
    expected = {
      'usernames': [
        {
          'username': '******',
          'url': 'www.facebook.com/dschafer'
        },
        {
          'username': '******',
          'url': 'www.facebook.com/leebyron'
        },
        {
          'username': '******',
          'url': 'www.facebook.com/schrockn'
        },
      ]
    }
    result = graphql(schema, query)
    assert result.errors == None
    assert result.data == expected
예제 #8
0
def test_requires_an_argument():
    query = '''
      mutation M {
        simpleMutation {
          result
        }
      }
    '''
    expected = {
      'allObjects': [
        {
          'id': 'VXNlcjox'
        },
        {
          'id': 'VXNlcjoy'
        },
        {
          'id': 'UGhvdG86MQ=='
        },
        {
          'id': 'UGhvdG86Mg=='
        },
      ]
    }
    result = graphql(schema, query)
    assert len(result.errors) == 1
예제 #9
0
    def handle(request):
        schema, root_value, pretty = get_options(request)

        if request.method != 'GET' and request.method != 'POST':
            return error_response(
                Error('GraphQL only supports GET and POST requests.',
                      status=405,
                      headers={'Allow': 'GET, POST'}), pretty)

        try:
            data = parse_body(request)
        except Error as e:
            return error_response(e, pretty)

        try:
            query, variables, operation_name = get_graphql_params(
                request, data)
        except Error as e:
            return error_response(e, pretty)
        result = graphql(schema, query, root_value, variables, operation_name)

        if result.invalid:
            status = 400
        else:
            status = 200

        d = {'data': result.data}
        if result.errors:
            d['errors'] = [format_error(error) for error in result.errors]

        return Response(status=status,
                        content_type='application/json',
                        body=json_dump(d, pretty))
예제 #10
0
def test_use_fragment():
    query = '''
        query UseFragment {
          luke: human(id: "1000") {
            ...HumanFragment
          }
          leia: human(id: "1003") {
            ...HumanFragment
          }
        }
        fragment HumanFragment on Human {
          name
          homePlanet
        }
    '''
    expected = {
        'luke': {
            'name': 'Luke Skywalker',
            'homePlanet': 'Tatooine',
        },
        'leia': {
            'name': 'Leia Organa',
            'homePlanet': 'Alderaan',
        }
    }
    result = graphql(StarWarsSchema, query)
    assert not result.errors
    assert result.data == expected
예제 #11
0
def test_does_not_accept_string_variables_as_enum_input():
    result = graphql(
        Schema, 'query test($color: String!) { colorEnum(fromEnum: $color) }',
        None, {'color': 'BLUE'})
    assert not result.data
    assert result.errors[
        0].message == 'Variable "color" of type "String!" used in position expecting type "Color".'
예제 #12
0
def test_enum_may_be_both_input_and_output_type():
    result = graphql(Schema, '{ colorEnum(fromEnum: GREEN) }')

    assert not result.errors
    assert result.data == {
        'colorEnum': 'GREEN'
    }
예제 #13
0
def test_identifies_deprecated_enum_values():
    TestEnum = GraphQLEnumType('TestEnum', OrderedDict([
        ('NONDEPRECATED', GraphQLEnumValue(0)),
        ('DEPRECATED', GraphQLEnumValue(1, deprecation_reason='Removed in 1.0')),
        ('ALSONONDEPRECATED', GraphQLEnumValue(2))
    ]))
    TestType = GraphQLObjectType('TestType', {
        'testEnum': GraphQLField(TestEnum)
    })
    schema = GraphQLSchema(TestType)
    request = '''{__type(name: "TestEnum") {
        name
        enumValues(includeDeprecated: true) {
            name
            isDeprecated
            deprecationReason
        }
    } }'''
    result = graphql(schema, request)
    assert not result.errors
    assert result.data == {'__type': {
        'name': 'TestEnum',
        'enumValues': [
            {'name': 'NONDEPRECATED', 'isDeprecated': False, 'deprecationReason': None},
            {'name': 'DEPRECATED', 'isDeprecated': True, 'deprecationReason': 'Removed in 1.0'},
            {'name': 'ALSONONDEPRECATED', 'isDeprecated': False, 'deprecationReason': None},
        ]}}
예제 #14
0
def test_identifies_deprecated_enum_values():
    TestEnum = GraphQLEnumType(
        "TestEnum",
        {
            "NONDEPRECATED": 0,
            "DEPRECATED": GraphQLEnumValue(1, deprecation_reason="Removed in 1.0"),
            "ALSONONDEPRECATED": 2,
        },
    )
    TestType = GraphQLObjectType("TestType", {"testEnum": GraphQLField(TestEnum)})
    schema = GraphQLSchema(TestType)
    request = """{__type(name: "TestEnum") {
        name
        enumValues(includeDeprecated: true) {
            name
            isDeprecated
            deprecationReason
        }
    } }"""
    result = graphql(schema, request)
    assert not result.errors
    assert sort_lists(result.data) == sort_lists(
        {
            "__type": {
                "name": "TestEnum",
                "enumValues": [
                    {"name": "NONDEPRECATED", "isDeprecated": False, "deprecationReason": None},
                    {"name": "DEPRECATED", "isDeprecated": True, "deprecationReason": "Removed in 1.0"},
                    {"name": "ALSONONDEPRECATED", "isDeprecated": False, "deprecationReason": None},
                ],
            }
        }
    )
def test_input_type():
    R = TypeRegistry()

    class SimpleInput(R.InputType):
        a = R.Int
        b = R.Int

    class Query(R.ObjectType):
        f = R.String(args={
            'input': R.SimpleInput
        })

        def resolve_f(self, obj, args, info):
            input = SimpleInput(args['input'])
            return "I was given {i.a} and {i.b}".format(i=input)

    Schema = R.Schema(R.Query)
    query = '''
    {
        f(input: {a: 1, b: 2})
    }
    '''

    result = graphql(Schema, query)
    assert not result.errors
    assert result.data == {
        'f': "I was given 1 and 2"
    }
def test_relay_node_field_resolver():
    data_source = InMemoryDataSource()

    R = TypeRegistry()
    Relay = R.Mixin(RelayMixin, data_source)

    class Pet(R.Implements[R.Node]):
        name = R.String

    class Query(R.ObjectType):
        pets = R.Pet.List
        node = Relay.NodeField

    schema = R.Schema(R.Query)

    data_source.add(Pet(id=5, name="Garfield"))
    data_source.add(Pet(id=6, name="Odis"))

    result = graphql(
        schema,
        """
    {
        node(id: "UGV0OjU=") {
            id,
            ... on Pet {
                name
            }
        }
    }
    """,
    )

    assert not result.errors
    assert result.data == {"node": {"id": "UGV0OjU=", "name": "Garfield"}}
예제 #17
0
def test_identifies_deprecated_fields():
    TestType = GraphQLObjectType(
        "TestType",
        {
            "nonDeprecated": GraphQLField(GraphQLString),
            "deprecated": GraphQLField(GraphQLString, deprecation_reason="Removed in 1.0"),
        },
    )
    schema = GraphQLSchema(TestType)
    request = """{__type(name: "TestType") {
        name
        fields(includeDeprecated: true) {
            name
            isDeprecated
            deprecationReason
        }
    } }"""
    result = graphql(schema, request)
    assert not result.errors
    assert sort_lists(result.data) == sort_lists(
        {
            "__type": {
                "name": "TestType",
                "fields": [
                    {"name": "nonDeprecated", "isDeprecated": False, "deprecationReason": None},
                    {"name": "deprecated", "isDeprecated": True, "deprecationReason": "Removed in 1.0"},
                ],
            }
        }
    )
예제 #18
0
def test_hero_name_and_friends_query():
    query = '''
        query HeroNameAndFriendsQuery {
          hero {
            id
            name
            friends {
              name
            }
          }
        }
    '''
    expected = {
        'hero': {
            'id': '2001',
            'name': 'R2-D2',
            'friends': [
                {'name': 'Luke Skywalker'},
                {'name': 'Han Solo'},
                {'name': 'Leia Organa'},
            ]
        }
    }
    result = graphql(StarWarsSchema, query)
    assert not result.errors
    assert result.data == expected
예제 #19
0
def test_use_fragment():
    query = '''
        query UseFragment {
          luke: human(id: "1000") {
            ...HumanFragment
          }
          leia: human(id: "1003") {
            ...HumanFragment
          }
        }
        fragment HumanFragment on Human {
          name
          homePlanet
        }
    '''
    expected = {
        'luke': {
            'name': 'Luke Skywalker',
            'homePlanet': 'Tatooine',
        },
        'leia': {
            'name': 'Leia Organa',
            'homePlanet': 'Alderaan',
        }
    }
    result = graphql(StarWarsSchema, query)
    assert not result.errors
    assert result.data == expected
예제 #20
0
def test_fails_as_expected_on_the_type_root_field_without_an_arg():
    TestType = GraphQLObjectType("TestType", {"testField": GraphQLField(GraphQLString)})
    schema = GraphQLSchema(TestType)
    request = "{ __type { name } }"
    result = graphql(schema, request)
    # TODO: change after implementing validation
    assert not result.errors
예제 #21
0
def test_duplicate_fields():
    query = '''
        query DuplicateFields {
          luke: human(id: "1000") {
            name
            homePlanet
          }
          leia: human(id: "1003") {
            name
            homePlanet
          }
        }
    '''
    expected = {
        'luke': {
            'name': 'Luke Skywalker',
            'homePlanet': 'Tatooine',
        },
        'leia': {
            'name': 'Leia Organa',
            'homePlanet': 'Alderaan',
        }
    }
    result = graphql(StarWarsSchema, query)
    assert not result.errors
    assert result.data == expected
def test_object_type_can_override_interface_resolver():
    R = TypeRegistry()

    class Pet(R.Interface):
        make_noise = R.String

        def resolve_make_noise(self, *args):
            return 'I am a pet, hear me roar!'

    class Dog(R.Implements.Pet):
        make_noise = R.String

        def resolve_make_noise(self, *args):
            return 'Woof woof! Bark bark!'

    class Query(R.ObjectType):
        dog = R.Dog

        def resolve_dog(self, *args):
            return Dog()

    schema = R.Schema(R.Query)

    result = graphql(schema, '{ dog { makeNoise } }')
    assert not result.errors
    assert result.data == {'dog': {'makeNoise': 'Woof woof! Bark bark!'}}
def test_will_choose_first_resolver_of_first_defined_interface():
    R = TypeRegistry()

    class Pet(R.Interface):
        make_noise = R.String

        def resolve_make_noise(self, *args):
            return 'I am a pet, hear me roar!'

    class Barker(R.Interface):
        make_noise = R.String

        def resolve_make_noise(self, *args):
            return 'Woof, woof!!'

    class Dog(R.Implements[Barker, Pet]):
        make_noise = R.String

    class Query(R.ObjectType):
        dog = R.Dog

        def resolve_dog(self, *args):
            return Dog()

    schema = R.Schema(R.Query)
    result = graphql(schema, '{ dog { makeNoise } }')
    assert not result.errors
    assert result.data == {'dog': {'makeNoise': 'Woof, woof!!'}}
예제 #24
0
def test_correct_fetch_first_ship_rebels():
    query = '''
    query RebelsShipsQuery {
      rebels {
        name,
        ships(first: 1) {
          edges {
            node {
              name
            }
          }
        }
      }
    }
    '''
    expected = {
      'rebels': {
        'name': 'Alliance to Restore the Republic',
        'ships': {
          'edges': [
            {
              'node': {
                'name': 'X-Wing'
              }
            }
          ]
        }
      }
    }
    result = graphql(StarWarsSchema, query)
    assert result.errors == None
    assert result.data == expected
예제 #25
0
def test_does_not_accept_internal_value_as_enum_input():
    result = graphql(
        Schema, 'query test($color: Int!) { colorEnum(fromEnum: $color) }',
        None, {'color': 2})
    assert not result.data
    assert result.errors[
        0].message == 'Variable "color" of type "Int!" used in position expecting type "Color".'
예제 #26
0
def test_identifies_deprecated_fields():
    TestType = GraphQLObjectType('TestType', {
        'nonDeprecated': GraphQLField(GraphQLString),
        'deprecated': GraphQLField(GraphQLString,
                                   deprecation_reason='Removed in 1.0')
    })
    schema = GraphQLSchema(TestType)
    request = '''{__type(name: "TestType") {
        name
        fields(includeDeprecated: true) {
            name
            isDeprecated
            deprecationReason
        }
    } }'''
    result = graphql(schema, request)
    assert not result.errors
    assert sort_lists(result.data) == sort_lists({'__type': {
        'name': 'TestType',
        'fields': [
            {'name': 'nonDeprecated', 'isDeprecated': False, 'deprecationReason': None},
            {'name': 'deprecated', 'isDeprecated': True,
             'deprecationReason': 'Removed in 1.0'},
        ]
    }})
def test_relay_node_definition_using_custom_type():
    R = TypeRegistry()
    Relay = R.Mixin(RelayMixin, InMemoryDataSource())

    class Pet(R.Implements[R.Node]):
        name = R.String

    class Query(R.ObjectType):
        pets = R.Pet.List
        node = Relay.NodeField

    schema = R.Schema(R.Query)

    @R.Pet.CanBe
    class MyPet(object):
        def __init__(self, id, name):
            self.id = id
            self.name = name

    pets = {5: MyPet(id=5, name="Garfield"), 6: MyPet(id=6, name="Odis")}

    data = Query(pets=[pets[5], pets[6]])
    result = graphql(schema, "{ pets { id, name } }", data)
    assert result.data == {"pets": [{"id": "UGV0OjU=", "name": "Garfield"}, {"id": "UGV0OjY=", "name": "Odis"}]}
    assert not result.errors
예제 #28
0
def test_duplicate_fields():
    query = '''
        query DuplicateFields {
          luke: human(id: "1000") {
            name
            homePlanet
          }
          leia: human(id: "1003") {
            name
            homePlanet
          }
        }
    '''
    expected = {
        'luke': {
            'name': 'Luke Skywalker',
            'homePlanet': 'Tatooine',
        },
        'leia': {
            'name': 'Leia Organa',
            'homePlanet': 'Alderaan',
        }
    }
    result = graphql(StarWarsSchema, query)
    assert not result.errors
    assert result.data == expected
예제 #29
0
def test_gives_different_ids():
    query = '''
    {
      allObjects {
        id
      }
    }
    '''
    expected = {
      'allObjects': [
        {
          'id': 'VXNlcjox'
        },
        {
          'id': 'VXNlcjoy'
        },
        {
          'id': 'UGhvdG86MQ=='
        },
        {
          'id': 'UGhvdG86Mg=='
        },
      ]
    }
    result = graphql(schema, query)
    assert result.errors == None
    assert result.data == expected
예제 #30
0
def test_hero_name_and_friends_query():
    query = '''
        query HeroNameAndFriendsQuery {
          hero {
            id
            name
            friends {
              name
            }
          }
        }
    '''
    expected = {
        'hero': {
            'id':
            '2001',
            'name':
            'R2-D2',
            'friends': [
                {
                    'name': 'Luke Skywalker'
                },
                {
                    'name': 'Han Solo'
                },
                {
                    'name': 'Leia Organa'
                },
            ]
        }
    }
    result = graphql(StarWarsSchema, query)
    assert not result.errors
    assert result.data == expected
예제 #31
0
def test_respects_the_includedeprecated_parameter_for_fields():
    TestType = GraphQLObjectType(
        "TestType",
        {
            "nonDeprecated": GraphQLField(GraphQLString),
            "deprecated": GraphQLField(GraphQLString, deprecation_reason="Removed in 1.0"),
        },
    )
    schema = GraphQLSchema(TestType)
    request = """{__type(name: "TestType") {
        name
        trueFields: fields(includeDeprecated: true) { name }
        falseFields: fields(includeDeprecated: false) { name }
        omittedFields: fields { name }
    } }"""
    result = graphql(schema, request)
    assert not result.errors
    assert sort_lists(result.data) == sort_lists(
        {
            "__type": {
                "name": "TestType",
                "trueFields": [{"name": "nonDeprecated"}, {"name": "deprecated"}],
                "falseFields": [{"name": "nonDeprecated"}],
                "omittedFields": [{"name": "nonDeprecated"}],
            }
        }
    )
예제 #32
0
def test_respects_the_includedeprecated_parameter_for_fields():
    TestType = GraphQLObjectType(
        'TestType', {
            'nonDeprecated':
            GraphQLField(GraphQLString),
            'deprecated':
            GraphQLField(GraphQLString, deprecation_reason='Removed in 1.0')
        })
    schema = GraphQLSchema(TestType)
    request = '''{__type(name: "TestType") {
        name
        trueFields: fields(includeDeprecated: true) { name }
        falseFields: fields(includeDeprecated: false) { name }
        omittedFields: fields { name }
    } }'''
    result = graphql(schema, request)
    assert not result.errors
    assert sort_lists(result.data) == sort_lists({
        '__type': {
            'name': 'TestType',
            'trueFields': [{
                'name': 'nonDeprecated'
            }, {
                'name': 'deprecated'
            }],
            'falseFields': [{
                'name': 'nonDeprecated'
            }],
            'omittedFields': [{
                'name': 'nonDeprecated'
            }],
        }
    })
예제 #33
0
def test_respects_the_includedeprecated_parameter_for_enum_values():
    TestEnum = GraphQLEnumType(
        "TestEnum",
        {
            "NONDEPRECATED": 0,
            "DEPRECATED": GraphQLEnumValue(1, deprecation_reason="Removed in 1.0"),
            "ALSONONDEPRECATED": 2,
        },
    )
    TestType = GraphQLObjectType("TestType", {"testEnum": GraphQLField(TestEnum)})
    schema = GraphQLSchema(TestType)
    request = """{__type(name: "TestEnum") {
        name
        trueValues: enumValues(includeDeprecated: true) { name }
        falseValues: enumValues(includeDeprecated: false) { name }
        omittedValues: enumValues { name }
    } }"""
    result = graphql(schema, request)
    assert not result.errors
    assert sort_lists(result.data) == sort_lists(
        {
            "__type": {
                "name": "TestEnum",
                "trueValues": [{"name": "NONDEPRECATED"}, {"name": "DEPRECATED"}, {"name": "ALSONONDEPRECATED"}],
                "falseValues": [{"name": "NONDEPRECATED"}, {"name": "ALSONONDEPRECATED"}],
                "omittedValues": [{"name": "NONDEPRECATED"}, {"name": "ALSONONDEPRECATED"}],
            }
        }
    )
예제 #34
0
def test_accepts_enum_literals_as_input_arguments_to_subscriptions():
    result = graphql(
        Schema,
        'subscription x($color: Color!) { subscribeToEnum(color: $color) }',
        None, {'color': 'GREEN'})
    assert not result.errors
    assert result.data == {'subscribeToEnum': 'GREEN'}
예제 #35
0
def test_identifies_deprecated_fields():
    TestType = GraphQLObjectType('TestType', {
        'nonDeprecated': GraphQLField(GraphQLString),
        'deprecated': GraphQLField(GraphQLString,
                                   deprecation_reason='Removed in 1.0')
    })
    schema = GraphQLSchema(TestType)
    request = '''{__type(name: "TestType") {
        name
        fields(includeDeprecated: true) {
            name
            isDeprecated
            deprecationReason
        }
    } }'''
    result = graphql(schema, request)
    assert not result.errors
    assert sort_lists(result.data) == sort_lists({'__type': {
        'name': 'TestType',
        'fields': [
            {'name': 'nonDeprecated', 'isDeprecated': False, 'deprecationReason': None},
            {'name': 'deprecated', 'isDeprecated': True,
             'deprecationReason': 'Removed in 1.0'},
        ]
    }})
예제 #36
0
def test_does_not_accept_internal_value_as_enum_variable():
    result = graphql(
        Schema, 'query test($color: Color!) { colorEnum(fromEnum: $color) }',
        None, {'color': 2})
    assert not result.data
    assert result.errors[0].message == 'Variable "$color" got invalid value 2.\n' \
                                       'Expected type "Color", found 2.'
예제 #37
0
def test_respects_the_includedeprecated_parameter_for_enum_values():
    TestEnum = GraphQLEnumType('TestEnum', OrderedDict([
        ('NONDEPRECATED', GraphQLEnumValue(0)),
        ('DEPRECATED', GraphQLEnumValue(1, deprecation_reason='Removed in 1.0')),
        ('ALSONONDEPRECATED', GraphQLEnumValue(2))
    ]))
    TestType = GraphQLObjectType('TestType', {
        'testEnum': GraphQLField(TestEnum)
    })
    schema = GraphQLSchema(TestType)
    request = '''{__type(name: "TestEnum") {
        name
        trueValues: enumValues(includeDeprecated: true) { name }
        falseValues: enumValues(includeDeprecated: false) { name }
        omittedValues: enumValues { name }
    } }'''
    result = graphql(schema, request)
    assert not result.errors
    assert result.data == {'__type': {
        'name': 'TestEnum',
        'trueValues': [{'name': 'NONDEPRECATED'}, {'name': 'DEPRECATED'},
                       {'name': 'ALSONONDEPRECATED'}],
        'falseValues': [{'name': 'NONDEPRECATED'},
                        {'name': 'ALSONONDEPRECATED'}],
        'omittedValues': [{'name': 'NONDEPRECATED'},
                          {'name': 'ALSONONDEPRECATED'}],
    }}
예제 #38
0
def test_refetches_the_ids():
    query = '''
    {
      user: node(id: "VXNlcjox") {
        id
        ... on User {
          name
        }
      },
      photo: node(id: "UGhvdG86MQ==") {
        id
        ... on Photo {
          width
        }
      }
    }
    '''
    expected = {
      'user': {
        'id': 'VXNlcjox',
        'name': 'John Doe'
      },
      'photo': {
        'id': 'UGhvdG86MQ==',
        'width': 300
      }
    }
    result = graphql(schema, query)
    assert result.errors == None
    assert result.data == expected
예제 #39
0
def test_contains_correct_field():
    query = '''
      {
        __schema {
          mutationType {
            fields {
              name
              args {
                name
                type {
                  name
                  kind
                  ofType {
                    name
                    kind
                  }
                }
              }
              type {
                name
                kind
              }
            }
          }
        }
      }
    '''

    expected = {
      '__schema': {
        'mutationType': {
          'fields': [
            {
              'name': 'simpleMutation',
              'args': [
                {
                  'name': 'input',
                  'type': {
                    'name': None,
                    'kind': 'NON_NULL',
                    'ofType': {
                      'name': 'SimpleMutationInput',
                      'kind': 'INPUT_OBJECT'
                    }
                  },
                }
              ],
              'type': {
                'name': 'SimpleMutationPayload',
                'kind': 'OBJECT',
              }
            },
          ]
        }
      }
    }
    result = graphql(schema, query)
    assert result.errors == None
    assert result.data == expected
예제 #40
0
def test_fails_as_expected_on_the_type_root_field_without_an_arg():
    TestType = GraphQLObjectType('TestType',
                                 {'testField': GraphQLField(GraphQLString)})
    schema = GraphQLSchema(TestType)
    request = '{ __type { name } }'
    result = graphql(schema, request)
    # TODO: change after implementing validation
    assert not result.errors
def test_is_type_of_used_to_resolve_runtime_type_for_interface():
    PetType = GraphQLInterfaceType(
        name='Pet',
        fields={
            'name': GraphQLField(GraphQLString)
        }
    )

    DogType = GraphQLObjectType(
        name='Dog',
        interfaces=[PetType],
        is_type_of=is_type_of(Dog),
        fields={
            'name': GraphQLField(GraphQLString),
            'woofs': GraphQLField(GraphQLBoolean)
        }
    )

    CatType = GraphQLObjectType(
        name='Cat',
        interfaces=[PetType],
        is_type_of=is_type_of(Cat),
        fields={
            'name': GraphQLField(GraphQLString),
            'meows': GraphQLField(GraphQLBoolean)
        }
    )

    schema = GraphQLSchema(
        query=GraphQLObjectType(
            name='Query',
            fields={
                'pets': GraphQLField(
                    GraphQLList(PetType),
                    resolver=lambda *_: [Dog('Odie', True), Cat('Garfield', False)]
                )
            }
        )
    )

    query = '''
    {
        pets {
            name
            ... on Dog {
                woofs
            }
            ... on Cat {
                meows
            }
        }
    }
    '''

    result = graphql(schema, query)
    assert not result.errors
    assert result.data == {'pets': [{'woofs': True, 'name': 'Odie'}, {'name': 'Garfield', 'meows': False}]}
def test_object_type_as_data():
    jake = Human(name='Jake', favorite_color='Red')
    assert jake.name == 'Jake'
    assert jake.favorite_color == 'Red'
    assert repr(jake) == '<Human name={!r} favorite_color={!r}>'.format(jake.name, jake.favorite_color)

    result = graphql(Schema, '{ name favoriteColor }', jake)
    assert not result.errors
    assert result.data == {'name': 'Jake', 'favoriteColor': 'Red'}
def test_object_type_as_data_with_partial_fields_provided():
    jake = Human(name='Jake')
    assert jake.name == 'Jake'
    assert jake.favorite_color is None
    assert repr(jake) == '<Human name={!r} favorite_color={!r}>'.format(jake.name, jake.favorite_color)

    result = graphql(Schema, '{ name favoriteColor }', jake)
    assert not result.errors
    assert result.data == {'name': 'Jake', 'favoriteColor': None}
예제 #44
0
def test_exposes_descriptions_on_types_and_fields():
    QueryRoot = GraphQLObjectType('QueryRoot',
                                  {'f': GraphQLField(GraphQLString)})
    schema = GraphQLSchema(QueryRoot)
    request = '''{
      schemaType: __type(name: "__Schema") {
          name,
          description,
          fields {
            name,
            description
          }
        }
      }
    '''
    result = graphql(schema, request)
    assert not result.errors
    assert result.data == {
        'schemaType': {
            'name':
            '__Schema',
            'description':
            'A GraphQL Schema defines the capabilities of a ' +
            'GraphQL server. It exposes all available types and ' +
            'directives on the server, as well as the entry ' +
            'points for query, mutation and subscription operations.',
            'fields': [{
                'name':
                'types',
                'description':
                'A list of all types supported by this server.'
            }, {
                'name':
                'queryType',
                'description':
                'The type that query operations will be rooted at.'
            }, {
                'name':
                'mutationType',
                'description':
                'If this server supports mutation, the type that '
                'mutation operations will be rooted at.'
            }, {
                'name':
                'subscriptionType',
                'description':
                'If this server support subscription, the type '
                'that subscription operations will be rooted at.'
            }, {
                'name':
                'directives',
                'description':
                'A list of all directives supported by this server.'
            }]
        }
    }
예제 #45
0
def test_parse_error():
    query = '''
        qeury
    '''
    result = graphql(StarWarsSchema, query)
    assert result.invalid
    formatted_error = format_error(result.errors[0])
    assert formatted_error['locations'] == [{'column': 9, 'line': 2}]
    assert 'Syntax Error GraphQL request (2:9) Unexpected Name "qeury"' in formatted_error['message']
    assert result.data is None
def test_is_type_of_used_to_resolve_runtime_type_for_interface():
    PetType = GraphQLInterfaceType(
        name='Pet', fields={'name': GraphQLField(GraphQLString)})

    DogType = GraphQLObjectType(name='Dog',
                                interfaces=[PetType],
                                is_type_of=is_type_of(Dog),
                                fields={
                                    'name': GraphQLField(GraphQLString),
                                    'woofs': GraphQLField(GraphQLBoolean)
                                })

    CatType = GraphQLObjectType(name='Cat',
                                interfaces=[PetType],
                                is_type_of=is_type_of(Cat),
                                fields={
                                    'name': GraphQLField(GraphQLString),
                                    'meows': GraphQLField(GraphQLBoolean)
                                })

    schema = GraphQLSchema(query=GraphQLObjectType(
        name='Query',
        fields={
            'pets':
            GraphQLField(
                GraphQLList(PetType),
                resolver=lambda *_:
                [Dog('Odie', True), Cat('Garfield', False)])
        }))

    query = '''
    {
        pets {
            name
            ... on Dog {
                woofs
            }
            ... on Cat {
                meows
            }
        }
    }
    '''

    result = graphql(schema, query)
    assert not result.errors
    assert result.data == {
        'pets': [{
            'woofs': True,
            'name': 'Odie'
        }, {
            'name': 'Garfield',
            'meows': False
        }]
    }
예제 #47
0
def test_hero_name_query():
    query = '''
        query HeroNameQuery {
          hero {
            name
          }
        }
    '''
    expected = {'hero': {'name': 'R2-D2'}}
    result = graphql(StarWarsSchema, query)
    assert not result.errors
    assert result.data == expected
예제 #48
0
def test_query():
    schema = GraphQLSchema(query=Human_type)
    query = '''
    {
      name
      pet {
        type
      }
    }
    '''
    expected = {'name': 'Peter', 'pet': {'type': 'Dog'}}
    result = graphql(schema, query, root=Human(object()))
    assert not result.errors
    assert result.data == expected
예제 #49
0
def test_fails_as_expected_on_the_type_root_field_without_an_arg():
    TestType = GraphQLObjectType('TestType', {
        'testField': GraphQLField(GraphQLString)
    })
    schema = GraphQLSchema(TestType)
    request = '''
    {
        __type {
           name
        }
    }'''
    result = graphql(schema, request)
    expected_error = {'message': ProvidedNonNullArguments.missing_field_arg_message('__type', 'name', 'String!'),
                      'locations': [dict(line=3, column=9)]}
    assert (expected_error in [format_error(error) for error in result.errors])
예제 #50
0
def test_invalid_id_query():
    query = '''
        query humanQuery($id: String!) {
          human(id: $id) {
            name
          }
        }
    '''
    params = {
        'id': 'not a valid id',
    }
    expected = {'human': None}
    result = graphql(StarWarsSchema, query, None, params)
    assert not result.errors
    assert result.data == expected
예제 #51
0
def test_fetch_luke_aliased():
    query = '''
        query FetchLukeAliased {
          luke: human(id: "1000") {
            name
          }
        }
    '''
    expected = {
        'luke': {
            'name': 'Luke Skywalker',
        }
    }
    result = graphql(StarWarsSchema, query)
    assert not result.errors
    assert result.data == expected
def test_fails_on_a_deep_non_null():
    schema = GraphQLSchema(query=GraphQLObjectType(
        name='Query',
        fields={
            'foo':
            GraphQLField(
                GraphQLList(
                    GraphQLList(GraphQLList(GraphQLNonNull(GraphQLString)))))
        }))

    introspection = graphql(schema, introspection_query)

    with raises(Exception) as excinfo:
        build_client_schema(introspection.data)

    assert str(
        excinfo.value) == 'Decorated type deeper than introspection query.'
예제 #53
0
def test_check_type_of_luke():
    query = '''
        query CheckTypeOfLuke {
          hero(episode: EMPIRE) {
            __typename
            name
          }
        }
    '''
    expected = {
        'hero': {
            '__typename': 'Human',
            'name': 'Luke Skywalker',
        }
    }
    result = graphql(StarWarsSchema, query)
    assert not result.errors
    assert result.data == expected
예제 #54
0
def test_check_type_of_r2():
    query = '''
        query CheckTypeOfR2 {
          hero {
            __typename
            name
          }
        }
    '''
    expected = {
        'hero': {
            '__typename': 'Droid',
            'name': 'R2-D2',
        }
    }
    result = graphql(StarWarsSchema, query)
    assert not result.errors
    assert result.data == expected
예제 #55
0
def test_fetch_some_id_query2():
    query = '''
        query FetchSomeIDQuery($someId: String!) {
          human(id: $someId) {
            name
          }
        }
    '''
    params = {
        'someId': '1002',
    }
    expected = {
        'human': {
            'name': 'Han Solo',
        }
    }
    result = graphql(StarWarsSchema, query, None, params)
    assert not result.errors
    assert result.data == expected
예제 #56
0
def test_introspects_on_input_object():
    TestInputObject = GraphQLInputObjectType(
        'TestInputObject', {
            'a': GraphQLInputObjectField(GraphQLString, default_value='foo'),
            'b': GraphQLInputObjectField(GraphQLList(GraphQLString)),
        })
    TestType = GraphQLObjectType(
        'TestType', {
            'field':
            GraphQLField(type=GraphQLString,
                         args={'complex': GraphQLArgument(TestInputObject)},
                         resolver=lambda obj, args, info: json.dumps(
                             args.get('complex')))
        })
    schema = GraphQLSchema(TestType)
    request = '''
      {
        __schema {
          types {
            kind
            name
            inputFields {
              name
              type { ...TypeRef }
              defaultValue
            }
          }
        }
      }
      fragment TypeRef on __Type {
        kind
        name
        ofType {
          kind
          name
          ofType {
            kind
            name
            ofType {
              kind
              name
            }
          }
        }
      }
    '''
    result = graphql(schema, request)
    assert not result.errors
    assert sort_lists({'kind': 'INPUT_OBJECT',
            'name': 'TestInputObject',
            'inputFields':
                [{'name': 'a',
                  'type':
                      {'kind': 'SCALAR',
                       'name': 'String',
                       'ofType': None},
                  'defaultValue': '"foo"'},
                 {'name': 'b',
                  'type':
                      {'kind': 'LIST',
                       'name': None,
                       'ofType':
                           {'kind': 'SCALAR',
                            'name': 'String',
                            'ofType': None}},
                  'defaultValue': None}]}) in \
                  sort_lists(result.data['__schema']['types'])
예제 #57
0
def test_nested_query():
    query = '''
        query NestedQuery {
          hero {
            name
            friends {
              name
              appearsIn
              friends {
                name
              }
            }
          }
        }
    '''
    expected = {
        'hero': {
            'name':
            'R2-D2',
            'friends': [
                {
                    'name':
                    'Luke Skywalker',
                    'appearsIn': ['NEWHOPE', 'EMPIRE', 'JEDI'],
                    'friends': [
                        {
                            'name': 'Han Solo',
                        },
                        {
                            'name': 'Leia Organa',
                        },
                        {
                            'name': 'C-3PO',
                        },
                        {
                            'name': 'R2-D2',
                        },
                    ]
                },
                {
                    'name':
                    'Han Solo',
                    'appearsIn': ['NEWHOPE', 'EMPIRE', 'JEDI'],
                    'friends': [
                        {
                            'name': 'Luke Skywalker',
                        },
                        {
                            'name': 'Leia Organa',
                        },
                        {
                            'name': 'R2-D2',
                        },
                    ]
                },
                {
                    'name':
                    'Leia Organa',
                    'appearsIn': ['NEWHOPE', 'EMPIRE', 'JEDI'],
                    'friends': [
                        {
                            'name': 'Luke Skywalker',
                        },
                        {
                            'name': 'Han Solo',
                        },
                        {
                            'name': 'C-3PO',
                        },
                        {
                            'name': 'R2-D2',
                        },
                    ]
                },
            ]
        }
    }
    result = graphql(StarWarsSchema, query)
    assert not result.errors
    assert result.data == expected
예제 #58
0
def test_exposes_descriptions_on_enums():
    QueryRoot = GraphQLObjectType('QueryRoot', {})
    schema = GraphQLSchema(QueryRoot)
    request = '''{
      typeKindType: __type(name: "__TypeKind") {
          name,
          description,
          enumValues {
            name,
            description
          }
        }
      }
    '''
    result = graphql(schema, request)
    assert not result.errors
    assert sort_lists(result.data) == sort_lists({
        'typeKindType': {
            'name':
            '__TypeKind',
            'description':
            'An enum describing what kind of type a given __Type is',
            'enumValues': [{
                'description': 'Indicates this type is a scalar.',
                'name': 'SCALAR'
            }, {
                'description':
                'Indicates this type is an object. ' +
                '`fields` and `interfaces` are valid fields.',
                'name':
                'OBJECT'
            }, {
                'description':
                'Indicates this type is an interface. ' +
                '`fields` and `possibleTypes` are valid fields.',
                'name':
                'INTERFACE'
            }, {
                'description': 'Indicates this type is a union. ' +
                '`possibleTypes` is a valid field.',
                'name': 'UNION'
            }, {
                'description': 'Indicates this type is an enum. ' +
                '`enumValues` is a valid field.',
                'name': 'ENUM'
            }, {
                'description':
                'Indicates this type is an input object. ' +
                '`inputFields` is a valid field.',
                'name':
                'INPUT_OBJECT'
            }, {
                'description': 'Indicates this type is a list. ' +
                '`ofType` is a valid field.',
                'name': 'LIST'
            }, {
                'description':
                'Indicates this type is a non-null. ' +
                '`ofType` is a valid field.',
                'name':
                'NON_NULL'
            }]
        }
    })