Exemplo n.º 1
0
def test_graphql(env):
    from ert_storage.graphql import schema as ert_schema
    from ert_shared.dark_storage.graphql import schema as dark_schema
    from graphql import print_schema

    def _sort_schema(schema: str) -> str:
        """
        Assuming that each block is separated by an empty line, we sort the contents
        so that the order is irrelevant
        """
        sorted_blocks: List[str] = []
        for block in schema.split("\n\n"):
            lines = block.splitlines()
            if len(lines) == 1:  # likely a lone "Scalar SomeType"
                sorted_blocks.append(block)
                continue
            body = sorted(
                line for line in lines[1:-1] if "Pk:" not in line and " pk:" not in line
            )
            sorted_blocks.append("\n".join([lines[0], *body, lines[-1]]))
        return "\n\n".join(sorted_blocks)

    expect = _sort_schema(print_schema(ert_schema))
    actual = _sort_schema(print_schema(dark_schema))

    assert expect == actual
Exemplo n.º 2
0
    def generates_correct_types():
        some_mutation = mutation_with_client_mutation_id(
            "SomeMutation",
            description="Some Mutation Description",
            input_fields={},
            output_fields={"result": GraphQLField(GraphQLInt)},
            mutate_and_get_payload=dummy_resolve,
            deprecation_reason="Just because",
        )

        schema = wrap_in_schema({"someMutation": some_mutation})

        assert print_schema(schema).rstrip() == dedent('''
            type Query {
              dummy: Int
            }

            type Mutation {
              """Some Mutation Description"""
              someMutation(input: SomeMutationInput!): SomeMutationPayload @deprecated(reason: "Just because")
            }

            type SomeMutationPayload {
              result: Int
              clientMutationId: String
            }

            input SomeMutationInput {
              clientMutationId: String
            }
            '''

                                                       # noqa: E501
                                                       )
Exemplo n.º 3
0
    def get_schema(self, schema, out, indent):
        schema_dict = {"data": schema.introspect()}
        if out == "-" or out == "-.json":
            self.stdout.write(
                json.dumps(schema_dict, indent=indent, sort_keys=True))
        elif out == "-.graphql":
            self.stdout.write(print_schema(schema))
        else:
            # Determine format
            _, file_extension = os.path.splitext(out)

            if file_extension == ".graphql":
                self.save_graphql_file(out, schema)
            elif file_extension == ".json":
                self.save_json_file(out, schema_dict, indent)
            else:
                raise CommandError(
                    'Unrecognised file format "{}"'.format(file_extension))

            style = getattr(self, "style", None)
            success = getattr(style, "SUCCESS", lambda x: x)

            self.stdout.write(
                success(
                    "Successfully dumped GraphQL schema to {}".format(out)))
Exemplo n.º 4
0
def compute_schema_fingerprint(schema: GraphQLSchema) -> str:
    """Compute a fingerprint compactly representing the data in the given schema.

    The fingerprint is not sensitive to things like type or field order. This function is guaranteed
    to be robust enough that if two GraphQLSchema have the same fingerprint, then they also
    represent the same schema.

    Because of internal implementation changes, different versions of this library *may* produce
    different fingerprints for the same schema. Since cross-version fingerprint stability
    is an *explicit non-goal* here, changing a schema's fingerprint will not be considered
    a breaking change.

    The fingerprint is computed on a best-effort basis and has some known issues at the moment.
    Please see the discussion in the pull request below for more details.
    https://github.com/kensho-technologies/graphql-compiler/pull/737

    Args:
        schema: the schema for which to compute a fingerprint.

    Returns:
        a hexadecimal string fingerprint compactly representing the data in the schema.
    """
    lexicographically_sorted_schema = lexicographic_sort_schema(schema)
    text = print_schema(lexicographically_sorted_schema)
    return sha256(text.encode("utf-8")).hexdigest()
Exemplo n.º 5
0
    def generates_correct_types():
        assert print_schema(schema).rstrip() == dedent('''
            """An object with an ID"""
            interface Node {
              """The id of the object."""
              id: ID!
            }

            type User implements Node {
              id: ID!
              name: String
            }

            type Photo implements Node {
              id: ID!
              width: Int
            }

            type Query {
              """Fetches an object given its ID"""
              node(
                """The ID of an object"""
                id: ID!
              ): Node

              """Fetches objects given their IDs"""
              nodes(
                """The IDs of objects"""
                ids: [ID!]!
              ): [Node]!
            }
            ''')
Exemplo n.º 6
0
async def view_graphql_schema(request, datasette):
    database = request.url_vars.get("database")
    try:
        datasette.get_database(database)
    except KeyError:
        raise NotFound("Database does not exist")
    schema = await schema_for_database_via_cache(datasette, database=database)
    return Response.text(print_schema(schema))
Exemplo n.º 7
0
def main():
    pp = PrettyPrinter(indent=4)
    client = GraphQLClient('http://swapi.graph.cool/')
    query_intros = get_introspection_query(descriptions=True)
    intros_result = client.execute(query_intros,
                                   variables=None,
                                   operationName=None)
    client_schema = build_client_schema(intros_result.get('data', None))
    sdl = print_schema(client_schema)
    print(sdl)
    pp.pprint(sdl)
    def handle(self, *args, **options):
        """Support multiple interface notation in schema for Apollo tooling.

        In `graphql-core` V2 separator for interaces is `,`.
        Apollo tooling to generate TypeScript types using `&` as interfaces separator.
        https://github.com/graphql-python/graphql-core/pull/258
        """
        printed_schema = print_schema(schema)
        for line in printed_schema.splitlines():
            if "implements" in line:
                line = line.replace(",", " &")
            self.stdout.write(f"{line}\n")
Exemplo n.º 9
0
def main():
    pp = PrettyPrinter(indent=4)

    # query over the network
    query_intros = get_introspection_query(descriptions=True)
    #introspection_query_result = graphql_sync(schema, query)
    intros_result = client.execute(query_intros,
                                   variables=None,
                                   operationName=None)
    client_schema = build_client_schema(intros_result.get('data', None))
    sdl = print_schema(client_schema)
    print(sdl)
    pp.pprint(sdl)
    print("\n")

    # query again using the graphql_sync()
    from graphql import graphql_sync
    introspection_query_result = graphql_sync(client_schema, query_intros)
    client_schema = build_client_schema(introspection_query_result.data)
    sdl = print_schema(client_schema)
    print(sdl)
    pp.pprint(sdl)
    print("\n")
Exemplo n.º 10
0
def IntrospectionQuery(endpoint, filename):

    url = endpoint
    #  for headers request
    headers = {
        "User-Agent":
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:67.0) Gecko/20100101 Firefox/67.0",
        "Accept": "*/*",
        "Accept-Language": "id,en-US;q=0.7,en;q=0.3",
        "Accept-Encoding": "gzip, deflate",
        "content-type": "application/json"
    }

    # Post Request Query for grab schema IntrospectionQuery
    body = {
        "query":
        "query IntrospectionQuery {__schema {queryType { name },mutationType { name },subscriptionType { name },types {...FullType},directives {name,description,args {...InputValue},onOperation,onFragment,onField,locations}}}\nfragment 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}}\nfragment InputValue on __InputValue {name,description,type { ...TypeRef },defaultValue}\nfragment TypeRef on __Type {kind,name,ofType {kind,name,ofType {kind,name,ofType {kind,name}}}}"
    }
    data = requests.post(url, headers=headers, json=body)
    status = data.status_code

    print("\n[+] Checking endpoint ", endpoint, " .. ")
    if (status == 400):
        print("[+] IntrospectionQuery Now Allowed")

    if (status == 200):
        print("[+] IntrospectionQuery Allowed ")

        print("[+] Saving  IntrospectionQuery to folder output .. ")
        save = (json.loads(data.text))
        filename_saved = 'output/' + filename + ".json"
        with open(filename_saved, 'w') as outfile:
            json.dump(save, outfile)
        print("[+] __schema saved in ", filename_saved)

        # Convert to client schema
        instropection = json.loads(data.text)
        client_schema = build_client_schema(instropection['data'])
        _schema = print_schema(client_schema)

        print(_schema)
        print("[+] Saving  client_schema to folder output ..")

        client_schema_saved = 'output/' + filename + ".schema"
        with open(client_schema_saved, 'w') as file:
            file.write(_schema)
        print("[+] client_schema  saved in ", client_schema_saved)
Exemplo n.º 11
0
def test_flattened_converted():
    data2 = deserialize(Data2, {"attr": 0})
    assert isinstance(data2.data_field2,
                      Field2) and data2.data_field2.attr == 0
    assert serialize(Data2, data2) == {"attr": 0}
    assert (deserialization_schema(Data) == serialization_schema(Data) == {
        "$schema":
        "http://json-schema.org/draft/2019-09/schema#",
        "type":
        "object",
        "allOf": [
            {
                "type": "object",
                "additionalProperties": False
            },
            {
                "type": "object",
                "properties": {
                    "attr": {
                        "type": "integer"
                    }
                },
                "required": ["attr"],
                "additionalProperties": False,
            },
        ],
        "unevaluatedProperties":
        False,
    })
    schema = graphql_schema(query=[get_data2])
    assert graphql_sync(schema, "{getData2{attr}}").data == {
        "getData2": {
            "attr": 0
        }
    }
    assert (print_schema(schema) == """\
type Query {
  getData2: Data2!
}

type Data2 {
  attr: Int!
}
""")
Exemplo n.º 12
0
    def generate_source(self, schema, query):
        variables = {'schemaDsl': print_schema(schema), 'query': query}

        json_response = self.make_post_request(
            "{}/graphql".format(self.api_url),
            auth=(self.public_key, self.secret_key),
            json_payload={
                'query': GRAPHQL_QUERY,
                'variables': variables
            })

        data = json_response.get('data', {})
        code_generation = data.get('generateCode', {})
        code = code_generation.get('code')
        if not code:
            raise Exception(
                "Cant get the code. Received json from Quiver Cloud")
        code = str(code)
        return code
Exemplo n.º 13
0
Arquivo: main.py Projeto: syfun/gqlcli
def sync_schema(
    ctx,
    name: str,
    version: str,
    user: str = 'teletraan',
    password: str = 'teletraan',
    host: str = 'https://graphql.teletraan.io',
):
    """Sync schema sdl to Graphql Studio"""
    schema = ctx.obj['schema']

    url = urljoin(host, f'/api/services/{name}/versions')
    resp = requests.put(url,
                        auth=(user, password),
                        json=dict(version=version, sdl=print_schema(schema)))
    if not resp.ok:
        print(resp.content)
    else:
        print(urljoin(host,
                      f'/api/services/{name}/versions/{version}/graphql'))
Exemplo n.º 14
0
    def initialize(self):
        loop = tornado.ioloop.IOLoop.current()

        generate_schema()
        api_schema = get_api_schema()
        module_schema = get_module_schema()

        if options.generate_schema_and_exit:
            query = get_introspection_query(descriptions=False)
            introspection_query_result = graphql_sync(api_schema, query)
            client_schema = build_client_schema(introspection_query_result.data)
            sdl = print_schema(client_schema)

            with open(
                Path(options.basedir).joinpath("..", "schema.graphql").resolve(), "w+"
            ) as fid:
                fid.write(sdl)
            sys.exit(0)

        start_all_modules()
        self.database = None  # MavDatabase()

        application = TornadoQL()

        # Start Non-SSL server
        server = tornado.httpserver.HTTPServer(application)
        server.listen(port=options.server_port_nonssl, address=options.server_interface)
        application_log.info(
            f"Starting Maverick API server: {options.server_interface}:{options.server_port_nonssl}/{options.app_prefix}"
        )

        # Start SSL server, unless disabled
        if not options.disable_ssl:
            ssl_options = self.get_ssl_options()
            server = tornado.httpserver.HTTPServer(application, ssl_options=ssl_options)
            server.listen(
                port=options.server_port_ssl, address=options.server_interface
            )
            application_log.info(
                f"Starting Maverick API server - SSL: {options.server_interface}:{options.server_port_ssl}/{options.app_prefix}"
            )
Exemplo n.º 15
0
def get_schema_from_tree(root_node: VSSNode, additional_leaf_fields: list) -> str:
    """Takes a VSSNode and additional fields for the leafs. Returns a graphql schema as string."""
    args = dict(
        id=GraphQLArgument(
            GraphQLNonNull(GraphQLString),
            description="VIN of the vehicle that you want to request data for.",
        ),
        after=GraphQLArgument(
            GraphQLString,
            description=(
                "Filter data to only provide information that was sent "
                "from the vehicle after that timestamp."
            ),
        ),
    )

    root_query = GraphQLObjectType(
        "Query",
        lambda: {"vehicle": GraphQLField(to_gql_type(root_node, additional_leaf_fields), args)},
    )
    return print_schema(GraphQLSchema(root_query))
    def test_schema_fingerprint_basic(self):
        schema_text = """
            type Object{
                field2: String
                field1: String
                field4: String
                field3: String
            }
        """
        schema = build_ast_schema(parse(schema_text))
        fingerprint = compute_schema_fingerprint(schema)

        # Assert that compute_schema_fingerprint does not modify the original schema.
        compare_graphql(self, schema_text, print_schema(schema))

        # Assert that compute_schema_fingerprint disregards field order.
        reordered_schema_text = """
            type Object{
                field1: String
                field3: String
                field4: String
                field2: String
            }
        """
        self.assertEqual(_compute_schema_text_fingerprint(reordered_schema_text), fingerprint)

        # Assert that the computed fingerprint is not the same if we add a new field.
        schema_text_with_added_field = """
            type Object{
                field1: String
                field3: String
                field4: String
                field2: String
                field5: String
            }
        """
        schema_with_added_field_fingerprint = _compute_schema_text_fingerprint(
            schema_text_with_added_field
        )
        self.assertNotEqual(schema_with_added_field_fingerprint, fingerprint)
def test_manager_adds_federation_specs(federated_schema):

    assert (graphql.print_schema(federated_schema) ==
            """directive @external on FIELD_DEFINITION

directive @requires(fields: _FieldSet!) on FIELD_DEFINITION

directive @provides(fields: _FieldSet!) on FIELD_DEFINITION

directive @key(fields: _FieldSet!) on OBJECT | INTERFACE

directive @extends on OBJECT

type Photo {
  id: ID!
  url: String!
  description: String
}

type Query {
  _entities(representations: [_Any!]!): [_Entity]!
  _service: _Service!
}

type User {
  id: ID!
  photos: [Photo]!
}

scalar _Any

union _Entity = User

scalar _FieldSet

type _Service {
  sdl: String
}
""")
Exemplo n.º 18
0
def add_mutations_to_schema(schema):
    types = types_to_augment(schema)

    # FIXME: don't use printSchema (custom directives are lost), instead use extend schema
    # FIXME: type extensions are lost
    mutation_schema_sdl = print_schema(schema)

    # TODO: compose augment funcs
    # let mutationSchemaSDLWithTypes = augmentTypes(types, schema, mutationSchemaSDL);

    mutation_schema_sdl_with_types_and_mutations = augment_mutations(types, schema, mutation_schema_sdl)

    def resolve_neo4j(obj, info, **kwargs):
        return neo4j_graphql(obj, info.context, info, **kwargs)

    # console.log(mutationSchemaSDLWithTypesAndMutations);
    def f(acc, t):
        # FIXME: inspect actual mutations, not construct mutation names here
        acc['Mutation'][f'Create{t}'] = resolve_neo4j
        for field_type in types:
            for rel_mutation in add_relationship_mutations(schema.type_map[field_type], True):
                acc['Mutation'][rel_mutation] = resolve_neo4j
        return acc

    resolvers = reduce_(types, f, {'Query': {}, 'Mutation': {}})

    # delegate query resolvers to original schema
    def f2(acc, t):
        acc['Query'][t] = resolve_neo4j
        return acc

    resolvers = reduce_(list(schema.query_type.fields.keys()), f2, resolvers)

    mutation_schema = make_executable_schema(mutation_schema_sdl_with_types_and_mutations, resolvers)

    final_schema = mutation_schema
    return final_schema
Exemplo n.º 19
0
async def test3():
    schema = graphql_schema(query=[plop],
                            subscription=[(events, handle_event)])
    print(print_schema(schema))
    subscription = await subscribe(schema,
                                   parse("subscription {handleEvent{name}}"))
    assert (await anext(subscription)).data == {
        "handleEvent": {
            "name": "bonjour"
        }
    }
    assert (await anext(subscription)).data == {
        "handleEvent": {
            "name": "au revoir"
        }
    }
    with raises(StopAsyncIteration):
        await anext(subscription)
    subscription = await subscribe(
        schema, parse("subscription {handleEvent(trunc: 2){name}}"))
    assert (await anext(subscription)).data == {"handleEvent": {"name": "bo"}}
    assert (await anext(subscription)).data == {"handleEvent": {"name": "au"}}
    with raises(StopAsyncIteration):
        await anext(subscription)
Exemplo n.º 20
0
#!/usr/bin/env python3

from graphql import print_schema
from forum_backend import graphql_schema

print(print_schema(graphql_schema).rstrip())
Exemplo n.º 21
0
 def __str__(self):
     return print_schema(self.graphql_schema)
Exemplo n.º 22
0
# We need to have a root query that we can extend, according to th SDL spec
# we can not have an empty query type. So we initialize it with `_empty` which
# will never get used.
root_query = GraphQLObjectType("Query",
                               {"_empty": GraphQLField(GraphQLString)})

# In order to extend the schema we need to start with a valid schema
# class instance. In graphql-core-next we can use a SDL file for the root
# as well. Here we need a little hack to future proof the rest of our
# application structure.
root_schema = GraphQLSchema(query=root_query)

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

schema_files = os.listdir(os.path.join(BASE_DIR, 'gql'))
schema_files.sort()

for filename in schema_files:
    with open(os.path.join(BASE_DIR, 'gql', filename)) as schema_file:
        schema_data = schema_file.read()
        # Each time we extend the root schema it makes a copy and returns
        # the newly extended schema and the orginal is unchanged.
        root_schema = extend_schema(root_schema, parse(schema_data))

# Since extend_schema parses client schema you'll get an error if you attempt
# to execute it: 'Client Schema cannot be used for execution.'
# Printing out the full schema and then parsing it avoids this issue.
fully_extended_schema_sdl = print_schema(root_schema)
schema = build_ast_schema(parse(fully_extended_schema_sdl))
Exemplo n.º 23
0
schema = Schema(query=Query).graphql_schema

# from graphql import GraphQLSchema, GraphQLObjectType, GraphQLField, GraphQLString
#
# schema = GraphQLSchema(
#     query=GraphQLObjectType(
#         name='RootQueryType',
#         fields={
#             'hello': GraphQLField(
#                 GraphQLString,
#                 resolve=lambda obj, info: 'world')
#             }))

# print graphql schema to frontend/schema.graphql (needed by frontend Relay)
schema_file = Path(__file__).parent / '../frontend/schema.graphql'
schema_file.write_text(print_schema(schema))

routes = RouteTableDef()  # aiohttp handlers table


@routes.get('/')
async def index_handler(request):
    return Response(text='Hello World!\n')


def main():
    p = ArgumentParser()
    p.add_argument('--port', '-p', type=int, default=5000)
    args = p.parse_args()
    setup_logging()
    asyncio.run(async_main(args=args))
Exemplo n.º 24
0
async def main(args: Namespace) -> int:
    """Main entrypoint of the gql-cli script

    :param args: The parsed command line arguments
    :return: The script exit code (0 = ok, 1 = error)
    """

    # Set requested log level
    if args.loglevel is not None:
        logging.basicConfig(level=args.loglevel)

    try:
        # Instantiate transport from command line arguments
        transport = get_transport(args)

        if transport is None:
            return 1

        # Get extra execute parameters from command line arguments
        # (variables, operation_name)
        execute_args = get_execute_args(args)

    except ValueError as e:
        print(f"Error: {e}", file=sys.stderr)
        return 1

    # By default, the exit_code is 0 (everything is ok)
    exit_code = 0

    # Connect to the backend and provide a session
    async with Client(
        transport=transport, fetch_schema_from_transport=args.print_schema
    ) as session:

        if args.print_schema:
            schema_str = print_schema(session.client.schema)
            print(schema_str)

            return exit_code

        while True:

            # Read multiple lines from input and trim whitespaces
            # Will read until EOF character is received (Ctrl-D)
            query_str = sys.stdin.read().strip()

            # Exit if query is empty
            if len(query_str) == 0:
                break

            # Parse query, continue on error
            try:
                query = gql(query_str)
            except GraphQLError as e:
                print(e, file=sys.stderr)
                exit_code = 1
                continue

            # Execute or Subscribe the query depending on transport
            try:
                try:
                    async for result in session.subscribe(query, **execute_args):
                        print(json.dumps(result))
                except KeyboardInterrupt:  # pragma: no cover
                    pass
                except NotImplementedError:
                    result = await session.execute(query, **execute_args)
                    print(json.dumps(result))
            except (GraphQLError, TransportQueryError) as e:
                print(e, file=sys.stderr)
                exit_code = 1

    return exit_code
Exemplo n.º 25
0
 def describe_schema(self) -> str:
     # TODO: remove
     return print_schema(self.schema)
Exemplo n.º 26
0
def test_graphql_schema_matches_the_reference(gql_schema, snapshot):
    actual_schema = print_schema(gql_schema)

    snapshot.assert_match(actual_schema)
Exemplo n.º 27
0
    @classmethod
    def serialize(cls, instance: datetime) -> str:
        return instance.strftime(cls._format)

    @classmethod
    def parse(cls, value: str) -> datetime:
        return datetime.strptime(value, cls._format)


MyUnion = Union[Foo, Bar]

schema = graphotype.make_schema(query=Query, mutation=None, scalars=[Date])

if __name__ == '__main__':
    print(graphql.print_schema(schema))

    query = '''
    query {
        c(d: true, e: 1.0) {
            a
            c
            d
        }
        isGiraffes(g: GIRAFFES)
        unionReturner {
            ...on Bar {
                a
            }
        }
        interfaceReturner {
Exemplo n.º 28
0
 def save_graphql_file(self, out, schema):
     with open(out, "w", encoding="utf-8") as outfile:
         outfile.write(print_schema(schema.graphql_schema))
Exemplo n.º 29
0
            "items": {
                "type": "string"
            },
            "uniqueItems": True
        },
    },
    "required": ["id", "name"],
    "additionalProperties": False,
}


# Define GraphQL operations
def resources(tags: Collection[str] = None) -> Collection[Resource]:
    ...


# Generate GraphQL schema
schema = graphql_schema(query=[resources], id_types={UUID})
schema_str = """\
type Query {
  resources(tags: [String!]): [Resource!]
}

type Resource {
  id: ID!
  name: String!
  tags: [String!]!
}
"""
assert print_schema(schema) == schema_str
Exemplo n.º 30
0
 def handle(self, *args, **options):
     self.stdout.write(print_schema(schema))