def test_may_extend_mutations_and_subscriptions():
    mutationSchema = GraphQLSchema(
        query=GraphQLObjectType('Query',
                                fields=lambda: {
                                    'queryField': GraphQLField(GraphQLString),
                                }),
        mutation=GraphQLObjectType('Mutation',
                                   fields={
                                       'mutationField':
                                       GraphQLField(GraphQLString),
                                   }),
        subscription=GraphQLObjectType('Subscription',
                                       fields={
                                           'subscriptionField':
                                           GraphQLField(GraphQLString),
                                       }),
    )

    ast = parse('''
      extend type Query {
        newQueryField: Int
      }
      extend type Mutation {
        newMutationField: Int
      }
      extend type Subscription {
        newSubscriptionField: Int
      }
    ''')
    original_print = print_schema(mutationSchema)
    extended_schema = extend_schema(mutationSchema, ast)
    assert extended_schema != mutationSchema
    assert print_schema(mutationSchema) == original_print
    assert print_schema(extended_schema) == \
        '''schema {
def test_extends_objects_by_adding_implemented_interfaces_2():
    ast = parse('''
      extend type Foo {
        newObject: NewObject
        newInterface: NewInterface
        newUnion: NewUnion
        newScalar: NewScalar
        newEnum: NewEnum
        newTree: [Foo]!
      }
      type NewObject implements NewInterface {
        baz: String
      }
      type NewOtherObject {
        fizz: Int
      }
      interface NewInterface {
        baz: String
      }
      union NewUnion = NewObject | NewOtherObject
      scalar NewScalar
      enum NewEnum {
        OPTION_A
        OPTION_B
      }
    ''')
    original_print = print_schema(test_schema)
    extended_schema = extend_schema(test_schema, ast)
    assert extended_schema != test_schema
    assert print_schema(test_schema) == original_print
    assert print_schema(extended_schema) == \
        '''schema {
Пример #3
0
 def test_get_schema_with_macros_original_schema_unchanged(self) -> None:
     empty_macro_registry = get_empty_test_macro_registry()
     original_printed_schema = print_schema(self.macro_registry.schema_without_macros)
     printed_schema_with_0_macros = print_schema(get_schema_with_macros(empty_macro_registry))
     printed_schema_afterwards = print_schema(self.macro_registry.schema_without_macros)
     self.assertEqual(original_printed_schema, printed_schema_afterwards)
     self.assertEqual(original_printed_schema, printed_schema_with_0_macros)
def test_extends_objects_by_adding_implemented_interfaces_2():
    ast = parse('''
      extend type Foo {
        newObject: NewObject
        newInterface: NewInterface
        newUnion: NewUnion
        newScalar: NewScalar
        newEnum: NewEnum
        newTree: [Foo]!
      }
      type NewObject implements NewInterface {
        baz: String
      }
      type NewOtherObject {
        fizz: Int
      }
      interface NewInterface {
        baz: String
      }
      union NewUnion = NewObject | NewOtherObject
      scalar NewScalar
      enum NewEnum {
        OPTION_A
        OPTION_B
      }
    ''')
    original_print = print_schema(test_schema)
    extended_schema = extend_schema(test_schema, ast)
    assert extended_schema != test_schema
    assert print_schema(test_schema) == original_print
    assert print_schema(extended_schema) == \
        '''schema {
def test_extends_objects_by_adding_implemented_new_interfaces():
    ast = parse("""
      extend type Foo implements NewInterface {
        baz: String
      }
      interface NewInterface {
        baz: String
      }
    """)
    original_print = print_schema(test_schema)
    extended_schema = extend_schema(test_schema, ast)
    assert extended_schema != test_schema
    assert print_schema(test_schema) == original_print
    assert (print_schema(extended_schema) == """schema {
  query: Query
}

type Bar implements SomeInterface {
  name: String
  some: SomeInterface
  foo: Foo
}

type Biz {
  fizz: String
}

type Foo implements SomeInterface, NewInterface {
  name: String
  some: SomeInterface
  tree: [Foo]!
  baz: String
}

interface NewInterface {
  baz: String
}

type Query {
  foo: Foo
  someUnion: SomeUnion
  someEnum: SomeEnum
  someInterface(id: ID!): SomeInterface
}

enum SomeEnum {
  ONE
  TWO
}

interface SomeInterface {
  name: String
  some: SomeInterface
}

union SomeUnion = Foo | Biz
""")
def test_extends_without_altering_original_schema():
    ast = parse('''
      extend type Query {
        newField: String
      }
    ''')
    original_print = print_schema(test_schema)
    extended_schema = extend_schema(test_schema, ast)
    assert extend_schema != test_schema
    assert print_schema(test_schema) == original_print
    assert 'newField' in print_schema(extended_schema)
    assert 'newField' not in print_schema(test_schema)
def test_extends_objects_by_adding_new_fields_with_existing_types():
    ast = parse('''
      extend type Foo {
        newField(arg1: SomeEnum!): SomeEnum
      }
    ''')
    original_print = print_schema(test_schema)
    extended_schema = extend_schema(test_schema, ast)
    assert extended_schema != test_schema
    assert print_schema(test_schema) == original_print
    assert print_schema(extended_schema) == \
        '''schema {
def test_extends_without_altering_original_schema():
    ast = parse('''
      extend type Query {
        newField: String
      }
    ''')
    original_print = print_schema(test_schema)
    extended_schema = extend_schema(test_schema, ast)
    assert extend_schema != test_schema
    assert print_schema(test_schema) == original_print
    assert 'newField' in print_schema(extended_schema)
    assert 'newField' not in print_schema(test_schema)
def test_extends_objects_by_adding_new_fields_with_existing_types():
    ast = parse('''
      extend type Foo {
        newField(arg1: SomeEnum!): SomeEnum
      }
    ''')
    original_print = print_schema(test_schema)
    extended_schema = extend_schema(test_schema, ast)
    assert extended_schema != test_schema
    assert print_schema(test_schema) == original_print
    assert print_schema(extended_schema) == \
        '''schema {
def test_extends_objects_by_adding_implemented_interfaces():
    ast = parse('''
      extend type Biz implements SomeInterface {
        name: String
        some: SomeInterface
      }
    ''')
    original_print = print_schema(test_schema)
    extended_schema = extend_schema(test_schema, ast)
    assert extended_schema != test_schema
    assert print_schema(test_schema) == original_print
    assert print_schema(extended_schema) == \
        '''schema {
def test_extends_objects_by_adding_implemented_interfaces():
    ast = parse('''
      extend type Biz implements SomeInterface {
        name: String
        some: SomeInterface
      }
    ''')
    original_print = print_schema(test_schema)
    extended_schema = extend_schema(test_schema, ast)
    assert extended_schema != test_schema
    assert print_schema(test_schema) == original_print
    assert print_schema(extended_schema) == \
        '''schema {
def test_extends_objects_by_adding_new_unused_types():
    ast = parse('''
      type Unused {
        someField: String
      }
    ''')
    original_print = print_schema(test_schema)
    extended_schema = extend_schema(test_schema, ast)
    assert extended_schema != test_schema
    assert print_schema(test_schema) == original_print
    # print original_print
    assert print_schema(extended_schema) == \
        '''schema {
def test_extends_objects_by_adding_new_fields():
    ast = parse('''
      extend type Foo {
        newField: String
      }
    ''')
    original_print = print_schema(test_schema)
    extended_schema = extend_schema(test_schema, ast)
    assert extended_schema != test_schema
    assert print_schema(test_schema) == original_print
    # print original_print
    assert print_schema(extended_schema) == \
        '''schema {
def test_extends_objects_by_adding_new_fields():
    ast = parse('''
      extend type Foo {
        newField: String
      }
    ''')
    original_print = print_schema(test_schema)
    extended_schema = extend_schema(test_schema, ast)
    assert extended_schema != test_schema
    assert print_schema(test_schema) == original_print
    # print original_print
    assert print_schema(extended_schema) == \
        '''schema {
def test_extends_objects_by_adding_new_unused_types():
    ast = parse('''
      type Unused {
        someField: String
      }
    ''')
    original_print = print_schema(test_schema)
    extended_schema = extend_schema(test_schema, ast)
    assert extended_schema != test_schema
    assert print_schema(test_schema) == original_print
    # print original_print
    assert print_schema(extended_schema) == \
        '''schema {
def test_extends_objects_by_adding_implemented_new_interfaces():
    ast = parse('''
      extend type Foo implements NewInterface {
        baz: String
      }
      interface NewInterface {
        baz: String
      }
    ''')
    original_print = print_schema(test_schema)
    extended_schema = extend_schema(test_schema, ast)
    assert extended_schema != test_schema
    assert print_schema(test_schema) == original_print
    assert print_schema(extended_schema) == \
        '''schema {
def test_extends_objects_by_adding_implemented_new_interfaces():
    ast = parse('''
      extend type Foo implements NewInterface {
        baz: String
      }
      interface NewInterface {
        baz: String
      }
    ''')
    original_print = print_schema(test_schema)
    extended_schema = extend_schema(test_schema, ast)
    assert extended_schema != test_schema
    assert print_schema(test_schema) == original_print
    assert print_schema(extended_schema) == \
        '''schema {
def test_may_extend_mutations_and_subscriptions():
    mutationSchema = GraphQLSchema(
        query=GraphQLObjectType(
            "Query",
            fields=lambda: {"queryField": GraphQLField(GraphQLString)}),
        mutation=GraphQLObjectType(
            "Mutation", fields={"mutationField": GraphQLField(GraphQLString)}),
        subscription=GraphQLObjectType(
            "Subscription",
            fields={"subscriptionField": GraphQLField(GraphQLString)}),
    )

    ast = parse("""
      extend type Query {
        newQueryField: Int
      }
      extend type Mutation {
        newMutationField: Int
      }
      extend type Subscription {
        newSubscriptionField: Int
      }
    """)
    original_print = print_schema(mutationSchema)
    extended_schema = extend_schema(mutationSchema, ast)
    assert extended_schema != mutationSchema
    assert print_schema(mutationSchema) == original_print
    assert (print_schema(extended_schema) == """schema {
  query: Query
  mutation: Mutation
  subscription: Subscription
}

type Mutation {
  mutationField: String
  newMutationField: Int
}

type Query {
  queryField: String
  newQueryField: Int
}

type Subscription {
  subscriptionField: String
  newSubscriptionField: Int
}
""")
Пример #19
0
def cycle_output(body):
    """This function does a full cycle of going from a string with the contents of the DSL,
    parsed in a schema AST, materializing that schema AST into an in-memory GraphQLSchema,
    and then finally printing that GraphQL into the DSL"""
    ast = parse(body)
    schema = build_ast_schema(ast)
    return "\n" + print_schema(schema)
def cycle_output(body):
    """This function does a full cycle of going from a string with the contents of the DSL,
    parsed in a schema AST, materializing that schema AST into an in-memory GraphQLSchema,
    and then finally printing that GraphQL into the DSL"""
    ast = parse(body)
    schema = build_ast_schema(ast)
    return "\n" + print_schema(schema)
Пример #21
0
def print_schema():
    from graphql.utils import schema_printer
    from app import graphql_service
    schema = graphql_service.get_schema()
    schema_str = schema_printer.print_schema(schema)
    with open('schema.graphql', 'w') as schemafile:
        schemafile.write(schema_str)
def test_extends_objects_by_adding_new_fields_with_arguments():
    ast = parse('''
      extend type Foo {
        newField(arg1: String, arg2: NewInputObj!): String
      }
      input NewInputObj {
        field1: Int
        field2: [Float]
        field3: String!
      }
    ''')
    original_print = print_schema(test_schema)
    extended_schema = extend_schema(test_schema, ast)
    assert extended_schema != test_schema
    assert print_schema(test_schema) == original_print
    assert print_schema(extended_schema) == \
        '''schema {
Пример #23
0
def make_merged_schema_descriptor(orientdb_schema,
                                  orientdb_type_equivalence_hints,
                                  postgres_schema,
                                  postgres_type_equivalence_hints):
    merged_type_equivalence_hints = dict(postgres_type_equivalence_hints,
                                         **orientdb_type_equivalence_hints)

    schema_id_to_ast = {
        'orientdb': parse(print_schema(orientdb_schema)),
        'postgres': parse(print_schema(postgres_schema)),
    }

    cross_schema_edges = [
        CrossSchemaEdgeDescriptor(
            edge_name='Airport_BasedIn',
            outbound_field_reference=FieldReference(
                schema_id='postgres',
                type_name='Airport',
                field_name='alpha2_country',
            ),
            inbound_field_reference=FieldReference(
                schema_id='orientdb',
                type_name='Country',
                field_name='alpha2',
            ),
            out_edge_only=False,
        ),
        CrossSchemaEdgeDescriptor(
            edge_name='Airline_RegisteredIn',
            outbound_field_reference=FieldReference(
                schema_id='postgres',
                type_name='Airline',
                field_name='alpha2_country',
            ),
            inbound_field_reference=FieldReference(
                schema_id='orientdb',
                type_name='Country',
                field_name='alpha2',
            ),
            out_edge_only=False,
        )
    ]

    return merge_schemas(schema_id_to_ast,
                         cross_schema_edges,
                         type_equivalence_hints=merged_type_equivalence_hints)
def test_extends_objects_by_adding_new_fields_with_arguments():
    ast = parse('''
      extend type Foo {
        newField(arg1: String, arg2: NewInputObj!): String
      }
      input NewInputObj {
        field1: Int
        field2: [Float]
        field3: String!
      }
    ''')
    original_print = print_schema(test_schema)
    extended_schema = extend_schema(test_schema, ast)
    assert extended_schema != test_schema
    assert print_schema(test_schema) == original_print
    assert print_schema(extended_schema) == \
        '''schema {
Пример #25
0
def schema(c):
    """generate schema.graphql from the graphene schema"""
    from buck.api.schema import schema
    from graphql.utils import schema_printer
    from buck.components.folders import Folders
    file_path = Folders.frontend / 'schema.graphql'
    file_path.write_text(schema_printer.print_schema(schema))
    print('schema.graphql has been written')
 def test_snapshot_graphql_schema_from_orientdb_schema(self):
     class_to_field_type_overrides = {"UniquelyIdentifiable": {"uuid": GraphQLID}}
     schema, _ = generate_schema(
         self.orientdb_client,  # type: ignore  # from fixture
         class_to_field_type_overrides=class_to_field_type_overrides,
         hidden_classes={ORIENTDB_BASE_VERTEX_CLASS_NAME},
     )
     compare_ignoring_whitespace(self, SCHEMA_TEXT, print_schema(schema), None)
Пример #27
0
def dump(schema: GraphQLSchema, json: bool, pretty: bool, file: IO[str]) -> None:
    if json:
        import json as mjson
        data = graphql(schema, introspection_query).data
        mjson.dump(
            {'data': data}, file, indent=2 if pretty else None
        )
    else:
        file.write(print_schema(schema))
Пример #28
0
 def test_snapshot_graphql_schema_from_orientdb_schema(self):
     class_to_field_type_overrides = {
         'UniquelyIdentifiable': {
             'uuid': GraphQLID
         }
     }
     schema, _ = generate_schema(
         self.graph_client,
         class_to_field_type_overrides=class_to_field_type_overrides)
     compare_ignoring_whitespace(self, SCHEMA_TEXT, print_schema(schema),
                                 None)
Пример #29
0
def get_schema_with_macros(macro_registry):
    """Get a new GraphQLSchema with fields where macro edges can be used.

    Preconditions:
    1. No macro in the registry has the same name as a field on the vertex where it applies.
    2. Members of a union type do not have outgoing macros with the same name.

    An easy way to satisfy the preconditions is to create the macro_registry using
    create_macro_registry, and only update it with register_macro_edge, which does all
    the necessary validation.

    Postconditions:
    1. Every GraphQLQuery that uses macros from this registry appropriately should
       successfully type-check against the schema generated from this function.
    2. A GraphQLQuery that uses macros not present in the registry, or uses valid
       macros but on types they are not defined at should fail schema validation with
       the schema generated from this function.
    3. This function is total -- A valid macro registry should not fail to create a
       GraphQL schema with macros.

    Args:
        macro_registry: MacroRegistry object containing a schema and macro descriptors
                        we want to add to the schema.

    Returns:
        GraphQLSchema with additional fields where macroe edges can be used.
    """
    # The easiest way to manipulate the schema is through its AST. The easiest
    # way to get an AST is to print it and parse it.
    schema_ast = parse(print_schema(macro_registry.schema_without_macros))

    definitions_by_name = {}
    for definition in schema_ast.definitions:
        if isinstance(definition,
                      (ObjectTypeDefinition, InterfaceTypeDefinition)):
            definitions_by_name[definition.name.value] = definition

    for class_name, macros_for_class in six.iteritems(
            macro_registry.macro_edges_at_class):
        for macro_edge_name, macro_edge_descriptor in six.iteritems(
                macros_for_class):
            list_type_at_target = ListType(
                NamedType(Name(macro_edge_descriptor.target_class_name)))
            arguments = []
            directives = [Directive(Name(MacroEdgeDirective.name))]
            definitions_by_name[class_name].fields.append(
                FieldDefinition(Name(macro_edge_name),
                                arguments,
                                list_type_at_target,
                                directives=directives))

    return build_ast_schema(schema_ast)
def test_may_extend_mutations_and_subscriptions():
    mutationSchema = GraphQLSchema(
        query=GraphQLObjectType(
            'Query',
            fields=lambda: {
                'queryField': GraphQLField(GraphQLString),
            }
        ),
        mutation=GraphQLObjectType(
            'Mutation',
            fields={
                'mutationField': GraphQLField(GraphQLString),
            }
        ),
        subscription=GraphQLObjectType(
            'Subscription',
            fields={
                'subscriptionField': GraphQLField(GraphQLString),
            }
        ),
    )

    ast = parse('''
      extend type Query {
        newQueryField: Int
      }
      extend type Mutation {
        newMutationField: Int
      }
      extend type Subscription {
        newSubscriptionField: Int
      }
    ''')
    original_print = print_schema(mutationSchema)
    extended_schema = extend_schema(mutationSchema, ast)
    assert extended_schema != mutationSchema
    assert print_schema(mutationSchema) == original_print
    assert print_schema(extended_schema) == \
        '''schema {
Пример #31
0
        def _get_directives_in_string_form(directives):
            """Return a set of directives in their string form, from the native directive type."""
            fake_query_type = GraphQLObjectType(
                'Query', fields={'foo': GraphQLField(GraphQLString)})
            fake_schema = GraphQLSchema(fake_query_type, directives=directives)

            schema_lines = [
                line.strip() for line in print_schema(fake_schema).split('\n')
            ]

            return {
                line
                for line in schema_lines if line.startswith('directive')
            }
def test_extends_objects_multiple_times():
    ast = parse('''
      extend type Biz implements NewInterface {
        buzz: String
      }
      extend type Biz implements SomeInterface {
        name: String
        some: SomeInterface
        newFieldA: Int
      }
      extend type Biz {
        newFieldA: Int
        newFieldB: Float
      }
      interface NewInterface {
        buzz: String
      }
    ''')
    original_print = print_schema(test_schema)
    extended_schema = extend_schema(test_schema, ast)
    assert extended_schema != test_schema
    assert print_schema(test_schema) == original_print
    assert print_schema(extended_schema) == \
        '''schema {
def test_extends_objects_multiple_times():
    ast = parse('''
      extend type Biz implements NewInterface {
        buzz: String
      }
      extend type Biz implements SomeInterface {
        name: String
        some: SomeInterface
        newFieldA: Int
      }
      extend type Biz {
        newFieldA: Int
        newFieldB: Float
      }
      interface NewInterface {
        buzz: String
      }
    ''')
    original_print = print_schema(test_schema)
    extended_schema = extend_schema(test_schema, ast)
    assert extended_schema != test_schema
    assert print_schema(test_schema) == original_print
    assert print_schema(extended_schema) == \
        '''schema {
Пример #34
0
        def _get_directives_in_string_form(directives):
            """Return a set of directives in their string form, from the native directive type."""
            fake_query_type = GraphQLObjectType('Query',
                                                fields={'foo': GraphQLField(GraphQLString)})
            fake_schema = GraphQLSchema(fake_query_type, directives=directives)

            schema_lines = [
                line.strip()
                for line in print_schema(fake_schema).split('\n')
            ]

            return {
                line
                for line in schema_lines
                if line.startswith('directive')
            }
Пример #35
0
    def test_meta_fields_from_constant(self):
        fields = schema.EXTENDED_META_FIELD_DEFINITIONS.copy()
        fields.update(OrderedDict((
            ('foo', GraphQLField(GraphQLString)),
            ('bar', GraphQLField(GraphQLInt)),
        )))
        graphql_type = GraphQLObjectType('MyType', fields)
        custom_schema = GraphQLSchema(graphql_type, directives=schema.DIRECTIVES)

        # Ensure that stringifying and parsing this schema works just fine.
        printed_schema = print_schema(custom_schema)
        expected_type_definition = '''\
type MyType {
    _x_count: Int
    foo: String
    bar: Int
}'''.replace('    ', '  ')  # 2 space indentation instead of 4 spaces
        self.assertIn(expected_type_definition, printed_schema)
Пример #36
0
def get_schema(url, directory=None):
    pp = PrettyPrinter(indent=4)
    client = GraphQLClient(url)
    intros_result = client.execute(introspection_query, variables=None)
    dict_res = json.loads(intros_result)
    client_schema = build_client_schema(dict_res['data'])
    sdl = print_schema(client_schema)
    if directory:
        path = pathlib.Path(directory)
        if not path.is_absolute():

            path = pathlib.Path(path.cwd(), path)

        file_path = pathlib.Path(path, "graphql.schema")
        print(file_path)
        with open(file_path, 'w+') as f:
            f.write(sdl)
    else:
        print(sdl)
    return sdl
Пример #37
0
 def __str__(self):
     return print_schema(self)
Пример #38
0
def print_for_test(schema):
    return '\n' + print_schema(schema)
Пример #39
0
def print_for_test(schema):
    return "\n" + print_schema(schema)
Пример #40
0
 def __init__(self):
     self.schema = schema_printer.print_schema(schema)
     self.currentDirectory = ""
Пример #41
0
 def __str__(self):
     return print_schema(self.schema)
Пример #42
0
#       type TeacherReviewActivity implements Activity, ReviewActivity {

#     graphql-schema-typescript implements a newer graphql spec which uses the ampersand whereas graphql-core v2.2.1 is using
#     the older style comma based separation between parents.

#     This won't be necessary anymore when we transition to graphene v3 / graphql-core-next, since the schema printer
#     in there generates the new-style schema out of the box.
#     """

#     interfaces = type.interfaces
#     implemented_interfaces = (
#         " implements {}".format(" & ".join(i.name for i in interfaces))
#         if interfaces
#         else ""
#     )

#     return ("type {}{} {{\n" "{}\n" "}}").format(
#         type.name, implemented_interfaces, schema_printer._print_fields(type)
#     )

# schema_printer._print_object = patched_print_object

if __name__ == '__main__':
    schema_str = schema_printer.print_schema(schema)
    with open(f'schema.graphql', 'w') as schema_file:
        schema_file.write(schema_str)

    # subprocess.run(
    #     "npm run generate-graphql-types", shell=True, cwd=settings.JS_DIR
    # )
Пример #43
0
def write_schema():
    schema_str = schema_printer.print_schema(schema)
    with open("schema.graphql", "w") as fp:
        fp.write(schema_str)
def print_for_test(schema):
    return '\n' + print_schema(schema)
def cycle_output(body):
    ast = parse(body)
    schema = build_ast_schema(ast)
    return '\n' + print_schema(schema)