def test_fragments__recursive(starwars_data):
    document = '''
    {
        hero {
            ...heroIdFragment
        }
    }

    fragment heroIdFragment on Character {
        id
        ...heroNameFragment
    }

    fragment heroNameFragment on Character {
        name
        ...heroIdFragment
    }
    '''
    request = Request(document, schema)
    data, errors = request.execute()
    assert data == {
        'hero': {
            'name': 'R2-D2',
            'id': 2001,
        },
    }
    assert errors == []
def test_episode_and_characters(starwars_data):
    document = '''
        {
            episode(number: 5) {
                name
                number
                characters (types: ["human", "droid"]) {
                    name
                }
            }
        }
        '''
    request = Request(document, schema)
    data, errors = request.execute()
    assert data == {
        'episode': {
            'name': 'The Empire Strikes Back',
            'number': 5,
            'characters': [
                {'name': 'Luke Skywalker'},
                {'name': 'Darth Vader'},
                {'name': 'Han Solo'},
                {'name': 'Leia Organa'},
                {'name': 'C-3PO'},
                {'name': 'R2-D2'},
            ]
        },
    }
    assert errors == []
def test_hero_name_and_episodes(starwars_data):
    document = '''
    {
        hero {
            name
            appears_in {
                name
                number
            }
        }
    }
    '''
    request = Request(document, schema)
    data, errors = request.execute()
    assert data == {
        'hero': {
            'name':
            'R2-D2',
            'appears_in': [
                {
                    'name': 'A New Hope',
                    'number': 4
                },
                {
                    'name': 'The Empire Strikes Back',
                    'number': 5
                },
            ]
        },
    }
    assert errors == []
def test_episodes_and_droids(starwars_data):
    document = '''
        {
            episodes {
                name
                number
                characters (types: "droid") {
                    name
                }
            }
        }
        '''
    request = Request(document, schema)
    data, errors = request.execute()
    assert data == {
        'episodes': [
            {
                'name': 'A New Hope',
                'number': 4,
                'characters': [
                    {'name': 'C-3PO'},
                    {'name': 'R2-D2'},
                ]
            },
            {
                'name': 'The Empire Strikes Back',
                'number': 5,
                'characters': [
                    {'name': 'C-3PO'},
                    {'name': 'R2-D2'},
                ]
            },
        ]
    }
    assert errors == []
    def post(self, request, *args, **kwargs):
        # Python 2 json library raises ValueError; Python 3 raises more specific error.
        JSONDecodeError = getattr(json, 'JSONDecodeError', ValueError)

        try:
            request_data = self.get_request_data()
            graphql_request = Request(
                document=request_data['query'],
                variables=request_data.get('variables'),
                operation_name=request_data.get('operationName'),
                schema=self.schema)
        except (KeyError, JSONDecodeError):
            return JsonResponse({
                'errors': [
                    {
                        'message':
                        'Data must be json with a "query" key and optional "variables" key'
                    },
                ],
            })

        graphql_request.validate()
        data = None
        errors = graphql_request.errors
        if not errors:
            data, errors = graphql_request.execute()

        response = {}
        if data:
            response['data'] = data

        if errors:
            response['errors'] = [error.serialize() for error in errors]
        return JsonResponse(response)
def test_valid_input():
    document = '''
    {
        nested(arg: [[1]])
    }
    '''
    request = Request(document, test_schema)
    errors = request.validate()
    assert errors is None
def test_missing_int():
    document = '''
    {
        nested(arg: [[]])
    }
    '''
    request = Request(document, test_schema)
    request.validate()
    assert request.errors == [
        GraphQLError("Non-null argument 'arg' on 'nested' is null"),
    ]
def test_missing_arg():
    document = '''
    {
        nested
    }
    '''
    request = Request(document, test_schema)
    request.validate()
    assert request.errors == [
        GraphQLError("Required argument 'arg' on 'nested' is missing")
    ]
def test_null_list_item():
    document = '''
    {
        nested(arg: [null])
    }
    '''
    request = Request(document, test_schema)
    request.validate()
    assert request.errors == [
        GraphQLError("Non-null argument 'arg' on 'nested' is null"),
    ]
def test_missing_scalar():
    document = '''
    {
        episode {
            name
        }
    }
    '''
    request = Request(document, schema)
    request.validate()
    assert request.errors == [
        GraphQLError("Required argument 'number' on 'episode' is missing"),
    ]
def test_null_scalar():
    document = '''
    {
        episode(number: null) {
            name
        }
    }
    '''
    request = Request(document, schema)
    request.validate()
    assert request.errors == [
        GraphQLError("Non-null argument 'number' on 'episode' is null"),
    ]
def test_related_object_args():
    document = '''
    {
        episode (number: 4) {
            characters (types: [null]) {
                name
            }
        }
    }
    '''
    request = Request(document, schema)
    request.validate()
    assert request.errors == [
        GraphQLError("Non-null argument 'types' on 'characters' is null"),
    ]

    document = '''
    {
        episode (number: 4) {
            characters {
                appears_in {
                    characters(types: [null]) {
                        name
                    }
                }
            }
        }
    }
    '''
    request = Request(document, schema)
    request.validate()
    assert request.errors == [
        GraphQLError("Non-null argument 'types' on 'characters' is null"),
    ]
def test_non_existent_field(starwars_data):
    document = '''
        {
            episode (number: 4) {
                name
                other_field
            }
        }
        '''
    request = Request(document, schema)
    data, errors = request.execute()
    assert data == {"episode": {"name": "A New Hope", "other_field": None}}
    assert errors == [
        GraphQLError('Episode does not have field other_field'),
    ]
def test_non_existent_episode(starwars_data):
    document = '''
        {
            episode (number: 12) {
                name
            }
        }
        '''
    request = Request(document, schema)
    data, errors = request.execute()
    assert data == {"episode": None}
    assert errors == [
        GraphQLError(
            'Error resolving episode: Episode matching query does not exist.'),
    ]
def test_hero_name(starwars_data):
    document = '''
    {
        hero {
            name
        }
    }
    '''
    request = Request(document, schema)
    data, errors = request.execute()
    assert data == {
        'hero': {
            'name': 'R2-D2',
        },
    }
    assert errors == []
Beispiel #16
0
def test_query_episodes_and_droids(starwars_data):
    document = '''
        query EpisodesAndCharacterType($type: String) {
            episodes {
                name
                number
                characters (types: $type) {
                    name
                }
            }
        }
        '''
    request = Request(document=document,
                      variables={'type': 'droid'},
                      schema=schema)
    data, errors = request.execute()
    assert data == {
        'episodes': [
            {
                'name': 'A New Hope',
                'number': 4,
                'characters': [
                    {
                        'name': 'C-3PO'
                    },
                    {
                        'name': 'R2-D2'
                    },
                ]
            },
            {
                'name': 'The Empire Strikes Back',
                'number': 5,
                'characters': [
                    {
                        'name': 'C-3PO'
                    },
                    {
                        'name': 'R2-D2'
                    },
                ]
            },
        ]
    }
    assert errors == []
Beispiel #17
0
def test_query_missing_variable_no_default(starwars_data):
    document = '''
        query Episodes($episode: Int) {
            episodes(number: $episode) {
                number
            }
        }
        '''
    request = Request(document, schema)
    data, errors = request.execute()
    assert data == {
        'episodes': [{
            'number': 4,
        }, {
            'number': 5,
        }]
    }
    assert errors == []
Beispiel #18
0
def test_execute__introspect_directives():
    document = '''{
        __schema {
            directives {
                name
                description
                locations
            }
        }
    }
    '''
    request = Request(document, schema)
    data, errors = request.execute()
    assert data == {
        '__schema': {
            'directives': [],
        },
    }
    assert errors == []
def test_hero_name_and_friends_names(starwars_data):
    document = '''
    {
        hero {
            name
            friends {
                name
            }
            best_friend {
                name
            }
        }
    }
    '''
    request = Request(document, schema)
    data, errors = request.execute()
    assert data == {
        'hero': {
            'name':
            'R2-D2',
            'friends': [
                {
                    'name': 'Luke Skywalker',
                },
                {
                    'name': 'Han Solo',
                },
                {
                    'name': 'Leia Organa',
                },
                {
                    'name': 'C-3PO',
                },
            ],
            'best_friend': {
                'name': 'Luke Skywalker'
            }
        },
    }
    assert errors == []
def test_fragments(starwars_data):
    document = '''
    {
        hero {
            ...heroFragment
        }
        episodes {
            ...episodeFragment
        }
    }

    fragment heroFragment on Character {
        id
        name
    }

    fragment episodeFragment on Episode {
        name
        number
    }
    '''
    request = Request(document, schema)
    data, errors = request.execute()
    assert data == {
        'episodes': [
            {
                'name': 'A New Hope',
                'number': 4,
            },
            {
                'name': 'The Empire Strikes Back',
                'number': 5,
            },
        ],
        'hero': {
            'name': 'R2-D2',
            'id': 2001,
        },
    }
    assert errors == []
def test_null_int():
    document = '''
    {
        nested(arg: [[null]])
    }
    '''
    request = Request(document, test_schema)
    request.validate()
    assert request.errors == [
        GraphQLError("Non-null argument 'arg' on 'nested' is null"),
    ]

    document = '''
    query nestedArgQuery($int: Int){
        nested(arg: [[$int]])
    }
    '''
    variables = {'int': None}

    request = Request(document, test_schema, variables=variables)
    request.validate()
    assert request.errors == [
        GraphQLError("Non-null argument 'arg' on 'nested' is null"),
    ]
def test_blank_query(starwars_data):
    document = ''
    request = Request(document, schema)
    assert request.errors == [
        GraphQLError('Must provide query string.'),
    ]
def test_episode_name_field_description(starwars_data):
    document = """
    query IntrospectionQuery {
      __schema {
        queryType { name }
        mutationType { name }
        types {
          ...FullType
        }
        directives {
          name
          description
          locations
          args {
            ...InputValue
          }
        }
      }
    }

    fragment FullType on __Type {
      kind
      name
      description
      fields(includeDeprecated: true) {
        name
        description
        args {
          ...InputValue
        }
        type {
          ...TypeRef
        }
        isDeprecated
        deprecationReason
      }
      inputFields {
        ...InputValue
      }
      interfaces {
        ...TypeRef
      }
      enumValues(includeDeprecated: true) {
        name
        description
        isDeprecated
        deprecationReason
      }
      possibleTypes {
        ...TypeRef
      }
    }

    fragment InputValue on __InputValue {
      name
      description
      type { ...TypeRef }
      defaultValue
    }

    fragment TypeRef on __Type {
      kind
      name
      ofType {
        kind
        name
        ofType {
          kind
          name
          ofType {
            kind
            name
            ofType {
              kind
              name
              ofType {
                kind
                name
                ofType {
                  kind
                  name
                  ofType {
                    kind
                    name
                  }
                }
              }
            }
          }
        }
      }
    }"""
    request = Request(document, schema)
    data, errors = request.execute()
    assert errors == []
    types = data['__schema']['types']
    episodes = [type_ for type_ in types if type_['name'] == 'Episode'][0]
    name_field = [
        field for field in episodes['fields']
        if field['name'] == 'name'
    ][0]
    assert name_field['description'] == 'The name of an episode'
Beispiel #24
0
def test_execute__filter_type():
    document = '''{
        __type (name: Character) {
            name
            kind
            fields {
                name
                type {
                    name
                    kind
                    ofType {
                        name
                        kind
                    }
                }
            }
        }
    }
    '''
    request = Request(document, schema)
    data, errors = request.execute()
    assert data == {
        '__type': {
            'name':
            'Character',
            'kind':
            'OBJECT',
            'fields': [
                {
                    'name': 'appears_in',
                    'type': {
                        'name': None,
                        'kind': 'LIST',
                        'ofType': {
                            'name': 'Episode',
                            'kind': 'OBJECT'
                        }
                    },
                },
                {
                    'name': 'best_friend',
                    'type': {
                        'name': 'Character',
                        'kind': 'OBJECT',
                        'ofType': None
                    },
                },
                {
                    'name': 'friends',
                    'type': {
                        'name': None,
                        'kind': 'LIST',
                        'ofType': {
                            'name': 'Character',
                            'kind': 'OBJECT'
                        }
                    },
                },
                {
                    'name': 'id',
                    'type': {
                        'name': None,
                        'kind': 'NON_NULL',
                        'ofType': {
                            'name': 'Int',
                            'kind': 'SCALAR'
                        }
                    },
                },
                {
                    'name': 'name',
                    'type': {
                        'name': 'String',
                        'kind': 'SCALAR',
                        'ofType': None
                    },
                },
            ],
        },
    }
    assert errors == []