def test_parser_mutation(swapi_schema): query = """ mutation CreateHero { createHero { hero { name } ok } } """ parser = QueryParser(swapi_schema) parsed = parser.parse(query) expected = asdict( ParsedQuery(query=query, objects=[ ParsedOperation( name='CreateHero', type='mutation', children=[ ParsedObject( name='CreateHeroData', fields=[ ParsedField(name='createHero', type='CreateHeroPayload', nullable=True) ], children=[ ParsedObject( name='CreateHeroPayload', fields=[ ParsedField(name='hero', type='Hero', nullable=True), ParsedField(name='ok', type='bool', nullable=True) ], children=[ ParsedObject( name='Hero', fields=[ ParsedField( name='name', type='str', nullable=False) ]) ]) ]) ]) ])) parsed_dict = asdict(parsed) assert bool(parsed) assert parsed_dict == expected, str(DeepDiff(parsed_dict, expected))
def test_parser_query_with_variables(swapi_schema): query = """ query GetFilm($theFilmID: ID!) { returnOfTheJedi: film(id: $theFilmID) { title director } } """ parser = QueryParser(swapi_schema) parsed = parser.parse(query) expected = asdict( ParsedQuery(query=query, objects=[ ParsedOperation( name='GetFilm', type='query', variables=[ ParsedVariableDefinition(name='theFilmID', type='str', nullable=False) ], children=[ ParsedObject( name='GetFilmData', fields=[ ParsedField(name='returnOfTheJedi', type='Film', nullable=True) ], children=[ ParsedObject( name='Film', fields=[ ParsedField(name='title', type='str', nullable=False), ParsedField(name='director', type='str', nullable=False), ]) ]) ]) ])) parsed_dict = asdict(parsed) assert bool(parsed) assert parsed_dict == expected, str(DeepDiff(parsed_dict, expected))
def test_parser_query_inline_fragment(swapi_schema): query = """ query GetFilm { returnOfTheJedi: film(id: "1") { ... on Film { title director } } } """ parser = QueryParser(swapi_schema) parsed = parser.parse(query) expected = asdict( ParsedQuery(query=query, objects=[ ParsedOperation( name='GetFilm', type='query', children=[ ParsedObject( name='GetFilmData', fields=[ ParsedField(name='returnOfTheJedi', type='Film', nullable=True) ], children=[ ParsedObject( name='Film', fields=[ ParsedField(name='title', type='str', nullable=False), ParsedField(name='director', type='str', nullable=False), ]) ], ) ]) ])) parsed_dict = asdict(parsed) assert bool(parsed) assert parsed_dict == expected, str(DeepDiff(parsed_dict, expected))
def test_parser_fails_on_nameless_op(swapi_schema): query = """ { allFilms { totalCount edges { node { id title director } } } } """ parser = QueryParser(swapi_schema) with pytest.raises(AnonymousQueryError): parser.parse(query)
def test_parser_fails_invalid_query(swapi_schema): query = """ query ShouldFail { allFilms { totalCount edges { node { title nonExistingField } } } } """ parser = QueryParser(swapi_schema) with pytest.raises(InvalidQueryError) as excinfo: parser.parse(query) print(str(excinfo))
def run(config_filename): if not isfile(config_filename): click.echo(f'Could not find configuration file {config_filename}') config = Config.load(config_filename) schema = load_schema(config.schema) filenames = glob.glob(config.documents, recursive=True) query_parser = QueryParser(schema) query_renderer = DataclassesRenderer(schema, config) for filename in filenames: process_file(filename, query_parser, query_renderer)
def process_file(filename: str, parser: QueryParser, renderer: DataclassesRenderer): root, _s = os.path.splitext(filename) target_filename = root + '.py' click.echo(f'Parsing {filename} ... ', nl=False) with open(filename, 'r') as fin: query = fin.read() try: parsed = parser.parse(query) rendered = renderer.render(parsed) with open(target_filename, 'w') as outfile: outfile.write(rendered) click.secho('Success!', fg='bright_white') except AnonymousQueryError: click.secho('Failed!', fg='bright_red') click.secho('\tQuery is missing a name', fg='bright_black') safe_remove(target_filename) except InvalidQueryError as invalid_err: click.secho('Failed!', fg='bright_red') click.secho(f'\t{invalid_err}', fg='bright_black') safe_remove(target_filename)
def test_non_nullable_list(module_compiler, mocker): from gql.query_parser import QueryParser from graphql import (GraphQLSchema, GraphQLObjectType, GraphQLField, GraphQLString, GraphQLList, GraphQLNonNull) PersonType = GraphQLObjectType( 'Person', lambda: { 'name': GraphQLField(GraphQLString), }) schema = GraphQLSchema(query=GraphQLObjectType( name='RootQueryType', fields={ 'people': GraphQLField(GraphQLList(GraphQLNonNull(PersonType)), resolve=lambda obj, info: {'name': 'eran'}) })) query = """ query GetPeople { people { name } } """ parser = QueryParser(schema) dataclass_renderer = DataclassesRenderer( schema, Config(schema='schemaurl', endpoint='schemaurl', documents='')) parsed = parser.parse(query) rendered = dataclass_renderer.render(parsed) m = module_compiler(rendered) now = datetime.now() call_mock = mocker.patch.object(m.Client, 'call') call_mock.return_value = """ { "data": { "people": [ { "name": "eran" }, { "name": "eran1" } ] } } """ result = m.GetPeople.execute() assert result assert isinstance(result, m.GetPeople) data = result.data assert len(data.people) == 2 assert data.people[0].name == 'eran' assert data.people[1].name == 'eran1'
def test_simple_query_with_enums_default_value(module_compiler): """ enum LengthUnit { METER KM } type Starship { id: ID! name: String! length(unit: LengthUnit = METER): Float } type Query { ship(id: String!): Starship } """ length_unit_enum = GraphQLEnumType( 'LengthUnit', { 'METER': GraphQLEnumValue('METER'), 'KM': GraphQLEnumValue('KM'), }, description='One of the films in the Star Wars Trilogy', ) starship_type = GraphQLObjectType( 'Starship', lambda: { 'id': GraphQLField(GraphQLNonNull(GraphQLString), description='The id of the ship.'), 'name': GraphQLField(GraphQLString, description='The name of the ship.'), 'length': GraphQLField(GraphQLInt, args={ 'unit': GraphQLArgument(GraphQLNonNull(length_unit_enum), default_value='METER', description='id of the droid') }) }) query_type = GraphQLObjectType( 'Query', lambda: { 'ship': GraphQLField( starship_type, args={ 'id': GraphQLArgument(GraphQLNonNull(GraphQLString), description='id of the ship') }, ) }) schema = GraphQLSchema(query_type, types=[length_unit_enum, starship_type]) query = """ query GetStarship { ship(id: "Enterprise") { id name length(unit: METER) } } """ query_parser = QueryParser(schema) query_renderer = DataclassesRenderer( schema, Config(schema='schemaurl', endpoint='schemaurl', documents='')) parsed = query_parser.parse(query) rendered = query_renderer.render(parsed) m = module_compiler(rendered) response = m.GetStarship.from_json(""" { "data": { "ship": { "id": "Enterprise", "name": "Enterprise", "length": 100 } } } """) assert response ship = response.data.ship assert ship assert ship.id == 'Enterprise' assert ship.name == 'Enterprise' assert ship.length == 100
def __init__(self, config: Config, schema: GraphQLSchema): self.parser = QueryParser(schema) self.renderer = DataclassesRenderer(schema, config)
def github_parser(github_schema): from gql.query_parser import QueryParser return QueryParser(github_schema)
def swapi_parser(swapi_schema): from gql.query_parser import QueryParser return QueryParser(swapi_schema)
def test_parser_connection_query(swapi_schema): query = """ query GetAllFilms { allFilms { count: totalCount edges { node { id title director } } } allHeroes { edges { node { ...HeroFields } } } } fragment HeroFields on Hero { id name } """ parser = QueryParser(swapi_schema) parsed = parser.parse(query) expected = asdict( ParsedQuery( query=query, objects=[ ParsedOperation( name='GetAllFilms', type='query', children=[ ParsedObject( name='GetAllFilmsData', fields=[ ParsedField(name='allFilms', type='FilmConnection', nullable=True), ParsedField(name='allHeroes', type='HeroConnection', nullable=True) ], children=[ ParsedObject( name='FilmConnection', fields=[ ParsedField(name='count', type='int', nullable=True), ParsedField(name='edges', type='List[FilmEdge]', nullable=True), ], children=[ ParsedObject( name='FilmEdge', fields=[ ParsedField(name='node', type='Film', nullable=True) ], children=[ ParsedObject( name='Film', fields=[ ParsedField( name='id', type='str', nullable=False), ParsedField( name='title', type='str', nullable=False), ParsedField( name='director', type='str', nullable=False) ]) ]) ]), ParsedObject( name='HeroConnection', fields=[ ParsedField(name='edges', type='List[HeroEdge]', nullable=True), ], children=[ ParsedObject( name='HeroEdge', fields=[ ParsedField(name='node', type='Hero', nullable=True) ], children=[ ParsedObject( name='Hero', parents=['HeroFields'], fields=[]) ]) ]), ], ), ]), ParsedObject( name='HeroFields', fields=[ ParsedField(name='id', type='str', nullable=False), ParsedField(name='name', type='str', nullable=False), ], ) ])) parsed_dict = asdict(parsed) assert bool(parsed) assert parsed_dict == expected, str(DeepDiff(parsed_dict, expected))
def test_parser_query_complex_fragment(swapi_schema): query = """ query GetPerson { luke: character(id: "luke") { ...CharacterFields } } fragment CharacterFields on Person { name home: homeworld { name } } """ parser = QueryParser(swapi_schema) parsed = parser.parse(query) expected = asdict( ParsedQuery( query=query, objects=[ ParsedOperation(name='GetPerson', type='query', children=[ ParsedObject( name='GetPersonData', fields=[ ParsedField(name='luke', type='Person', nullable=True) ], children=[ ParsedObject( name='Person', parents=['CharacterFields'], fields=[]) ], ), ]), ParsedObject(name='CharacterFields', fields=[ ParsedField(name='name', type='str', nullable=False), ParsedField(name='home', type='Planet', nullable=False), ], children=[ ParsedObject(name='Planet', fields=[ ParsedField(name='name', type='str', nullable=False), ]) ]) ])) parsed_dict = asdict(parsed) assert bool(parsed) assert parsed_dict == expected, str(DeepDiff(parsed_dict, expected))
def test_simple_query_with_enums_default_value(module_compiler): """ enum LengthUnit { METER KM } type Starship { id: ID! name: String! length(unit: LengthUnit = METER): Float } type Query { ship(id: String!): Starship } """ length_unit_enum = GraphQLEnumType( 'LengthUnit', { 'METER': GraphQLEnumValue('METER'), 'KM': GraphQLEnumValue('KM'), }, description='One of the films in the Star Wars Trilogy', ) starship_type = GraphQLObjectType( 'Starship', lambda: { 'id': GraphQLField(GraphQLNonNull(GraphQLString), description='The id of the ship.'), 'name': GraphQLField(GraphQLString, description='The name of the ship.'), 'length': GraphQLField( GraphQLInt, args={ 'unit': GraphQLArgument( GraphQLNonNull(length_unit_enum), default_value='METER', description='id of the droid' ) } ) } ) query_type = GraphQLObjectType( 'Query', lambda: { 'ship': GraphQLField( starship_type, args={ 'id': GraphQLArgument(GraphQLNonNull(GraphQLString), description='id of the ship') }, ) } ) schema = GraphQLSchema(query_type, types=[length_unit_enum, starship_type]) query = """ query GetStarship { ship(id: "Enterprise") { id name length(unit: METER) } } """ query_parser = QueryParser(schema) query_renderer = DataclassesRenderer(schema, Config(schema='schemaurl', endpoint='schemaurl', documents='')) parsed = query_parser.parse(query) rendered = query_renderer.render(parsed) m = module_compiler(rendered) response = m.GetStarship.from_json(""" { "data": { "ship": { "id": "Enterprise", "name": "Enterprise", "length": 100 } } } """) assert response ship = response.data.ship assert ship assert ship.id == 'Enterprise' assert ship.name == 'Enterprise' assert ship.length == 100