Beispiel #1
0
 def prints_string_field_with_string_arg_with_default():
     output = print_single_field_schema(
         GraphQLField(type_=GraphQLString,
                      args={
                          'argOne':
                          GraphQLArgument(GraphQLString,
                                          default_value='tes\t de\fault')
                      }))
     assert output == dedent(r"""
         type Query {
           singleField(argOne: String = "tes\t de\fault"): String
         }
         """)
Beispiel #2
0
    def transforms_arguments_using_out_names():
        # This is an extension of GraphQL.js.
        schema = _test_schema(
            GraphQLField(
                GraphQLString,
                args={
                    "aStr": GraphQLArgument(GraphQLString, out_name="a_str"),
                    "aInt": GraphQLArgument(GraphQLInt, out_name="a_int"),
                },
                resolve=lambda source, info, **args: repr([source, args]),
            ))

        def execute(source, root_value=None):
            return graphql_sync(schema=schema,
                                source=source,
                                root_value=root_value)

        assert execute("{ test }") == ({"test": "[None, {}]"}, None)

        assert execute("{ test }", "Source!") == (
            {
                "test": "['Source!', {}]"
            },
            None,
        )

        assert execute('{ test(aStr: "String!") }', "Source!") == (
            {
                "test": "['Source!', {'a_str': 'String!'}]"
            },
            None,
        )

        assert execute('{ test(aInt: -123, aStr: "String!") }', "Source!") == (
            {
                "test": "['Source!', {'a_str': 'String!', 'a_int': -123}]"
            },
            None,
        )
Beispiel #3
0
 def includes_nested_input_objects_in_the_map():
     NestedInputObject = GraphQLInputObjectType(
         'NestedInputObject', {'value': GraphQLInputField(GraphQLString)})
     SomeInputObject = GraphQLInputObjectType(
         'SomeInputObject',
         {'nested': GraphQLInputField(NestedInputObject)})
     SomeMutation = GraphQLObjectType(
         'SomeMutation', {
             'mutateSomething':
             GraphQLField(BlogArticle,
                          {'input': GraphQLArgument(SomeInputObject)})
         })
     SomeSubscription = GraphQLObjectType(
         'SomeSubscription', {
             'subscribeToSomething':
             GraphQLField(BlogArticle,
                          {'input': GraphQLArgument(SomeInputObject)})
         })
     schema = GraphQLSchema(query=BlogQuery,
                            mutation=SomeMutation,
                            subscription=SomeSubscription)
     assert schema.type_map['NestedInputObject'] is NestedInputObject
    def prints_string_field_with_multiple_args_last_is_default():
        schema = build_single_field_schema(
            GraphQLField(
                type_=GraphQLString,
                args={
                    "argOne":
                    GraphQLArgument(GraphQLInt),
                    "argTwo":
                    GraphQLArgument(GraphQLString),
                    "argThree":
                    GraphQLArgument(GraphQLBoolean, default_value=False),
                },
            ))

        assert expect_printed_schema(schema) == dedent("""
            type Query {
              singleField(argOne: Int, argTwo: String, argThree: Boolean = false): String
            }
            """

                                                       # noqa: E501
                                                       )
 def includes_input_types_only_used_in_directives():
     directive = GraphQLDirective(
         name="dir",
         locations=[DirectiveLocation.OBJECT],
         args={
             "arg": GraphQLArgument(
                 GraphQLInputObjectType(
                     "Foo", {"field": GraphQLInputField(GraphQLString)}
                 )
             ),
             "argList": GraphQLArgument(
                 GraphQLList(
                     GraphQLInputObjectType(
                         "Bar", {"field": GraphQLInputField(GraphQLString)}
                     )
                 )
             ),
         },
     )
     schema = GraphQLSchema(directives=[directive])
     assert "Foo" in schema.type_map
     assert "Bar" in schema.type_map
Beispiel #6
0
 def prints_string_field_with_int_arg():
     output = print_single_field_schema(
         GraphQLField(
             type_=GraphQLString, args={"argOne": GraphQLArgument(GraphQLInt)}
         )
     )
     assert output == dedent(
         """
         type Query {
           singleField(argOne: Int): String
         }
         """
     )
Beispiel #7
0
def test_correctly_threads_arguments():
    # type: () -> None
    doc = """
        query Example {
            b(numArg: 123, stringArg: "foo")
        }
    """

    def resolver(source, info, numArg, stringArg):
        # type: (Optional[Any], ResolveInfo, int, str) -> None
        assert numArg == 123
        assert stringArg == "foo"
        resolver.got_here = True

    resolver.got_here = False

    doc_ast = parse(doc)

    Type = GraphQLObjectType(
        "Type",
        {
            "b":
            GraphQLField(
                GraphQLString,
                args={
                    "numArg": GraphQLArgument(GraphQLInt),
                    "stringArg": GraphQLArgument(GraphQLString),
                },
                resolver=resolver,
            )
        },
    )

    result = execute(GraphQLSchema(Type),
                     doc_ast,
                     None,
                     operation_name="Example")
    assert not result.errors
    assert resolver.got_here
 def prints_string_field_with_int_arg_with_default_null():
     output = print_single_field_schema(
         GraphQLField(
             type_=GraphQLString,
             args={
                 "argOne": GraphQLArgument(GraphQLInt, default_value=None)
             },
         ))
     assert output == dedent("""
         type Query {
           singleField(argOne: Int = null): String
         }
         """)
Beispiel #9
0
    def transforms_arguments_with_inputs_using_out_names():
        # This is an extension of GraphQL.js.
        TestInputObject = GraphQLInputObjectType(
            "TestInputObjectType",
            lambda: {
                "inputOne":
                GraphQLInputField(GraphQLString, out_name="input_one"),
                "inputRecursive":
                GraphQLInputField(TestInputObject, out_name="input_recursive"),
            },
        )

        schema = _test_schema(
            GraphQLField(
                GraphQLString,
                args={
                    "aInput": GraphQLArgument(TestInputObject,
                                              out_name="a_input")
                },
                resolve=lambda source, info, **args: repr([source, args]),
            ))

        def execute(source, root_value=None):
            return graphql_sync(
                schema=schema,
                source=source,
                root_value=root_value,
            )

        assert execute("{ test }") == ({"test": "[None, {}]"}, None)

        assert execute(
            '{ test(aInput: {inputOne: "String!"}) }', "Source!") == (
                {
                    "test":
                    "['Source!', {'a_input': {'input_one': 'String!'}}]"
                },
                None,
            )

        assert execute(
            '{ test(aInput: {inputRecursive: {inputOne: "SourceRecursive!"}}) }',
            "Source!",
        ) == (
            {
                "test":
                "['Source!',"
                " {'a_input': {'input_recursive': {'input_one': 'SourceRecursive!'}}}]"
            },
            None,
        )
Beispiel #10
0
def test_maps_argument_out_names_well_with_input():
    # type: () -> None
    def resolver(source, info, **args):
        # type: (Optional[str], ResolveInfo, **Any) -> str
        return json.dumps([source, args], separators=(",", ":"))

    TestInputObject = GraphQLInputObjectType(
        "TestInputObject",
        lambda: OrderedDict([
            (
                "inputOne",
                GraphQLInputObjectField(GraphQLString, out_name="input_one"),
            ),
            (
                "inputRecursive",
                GraphQLInputObjectField(TestInputObject,
                                        out_name="input_recursive"),
            ),
        ]),
    )

    schema = _test_schema(
        GraphQLField(
            GraphQLString,
            args=OrderedDict([("aInput",
                               GraphQLArgument(TestInputObject,
                                               out_name="a_input"))]),
            resolver=resolver,
        ))

    result = graphql(schema, "{ test }", None)
    assert not result.errors
    assert result.data == {"test": "[null,{}]"}

    result = graphql(schema, '{ test(aInput: {inputOne: "String!"} ) }',
                     "Source!")
    assert not result.errors
    assert result.data == {
        "test": '["Source!",{"a_input":{"input_one":"String!"}}]'
    }

    result = graphql(
        schema,
        '{ test(aInput: {inputRecursive:{inputOne: "SourceRecursive!"}} ) }',
        "Source!",
    )
    assert not result.errors
    assert result.data == {
        "test":
        '["Source!",{"a_input":{"input_recursive":{"input_one":"SourceRecursive!"}}}]'
    }
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.'}
    ]
Beispiel #12
0
def test_does_not_include_arguments_that_were_not_set():
    schema = GraphQLSchema(GraphQLObjectType(
        'Type',
        {
            'field': GraphQLField(
                GraphQLString,
                resolver=lambda data, args, *_: args and json.dumps(args, sort_keys=True, separators=(',', ':')),
                args={
                    'a': GraphQLArgument(GraphQLBoolean),
                    'b': GraphQLArgument(GraphQLBoolean),
                    'c': GraphQLArgument(GraphQLBoolean),
                    'd': GraphQLArgument(GraphQLInt),
                    'e': GraphQLArgument(GraphQLInt),
                }
            )
        }
    ))

    ast = parse('{ field(a: true, c: false, e: 0) }')
    result = execute(schema, ast)
    assert result.data == {
        'field': '{"a":true,"c":false,"e":0}'
    }
Beispiel #13
0
    def prints_string_field_with_int_arg():
        schema = build_single_field_schema(
            GraphQLField(
                type_=GraphQLString, args={"argOne": GraphQLArgument(GraphQLInt)}
            )
        )

        assert expect_printed_schema(schema) == dedent(
            """
            type Query {
              singleField(argOne: Int): String
            }
            """
        )
Beispiel #14
0
    def does_not_include_arguments_that_were_not_set():
        schema = GraphQLSchema(
            GraphQLObjectType(
                'Type', {
                    'field':
                    GraphQLField(GraphQLString,
                                 args={
                                     'a': GraphQLArgument(GraphQLBoolean),
                                     'b': GraphQLArgument(GraphQLBoolean),
                                     'c': GraphQLArgument(GraphQLBoolean),
                                     'd': GraphQLArgument(GraphQLInt),
                                     'e': GraphQLArgument(GraphQLInt)
                                 },
                                 resolve=lambda _source, _info, **args: args
                                 and dumps(args))
                }))

        query = parse('{ field(a: true, c: false, e: 0) }')

        assert execute(schema, query) == ({
            'field':
            '{"a": true, "c": false, "e": 0}'
        }, None)
def test_builds_a_schema_with_field_arguments():
    schema = GraphQLSchema(
        query=GraphQLObjectType(
            name='ArgFields',
            fields=OrderedDict([
                ('one', GraphQLField(GraphQLString, description='A field with a single arg', args={
                    'intArg': GraphQLArgument(GraphQLInt, description='This is an int arg')
                })),
                ('two', GraphQLField(GraphQLString, description='A field with two args', args=OrderedDict([
                    ('listArg', GraphQLArgument(
                        GraphQLList(GraphQLInt),
                        description='This is a list of int arg'
                    )),
                    ('requiredArg', GraphQLArgument(
                        GraphQLNonNull(GraphQLBoolean),
                        description='This is a required arg'
                    ))
                ]))),
            ])
        )
    )

    _test_schema(schema)
Beispiel #16
0
def test_builds_a_schema_with_an_input_object():
    AddressType = GraphQLInputObjectType(
        name="Address",
        description="An input address",
        fields=OrderedDict(
            [
                (
                    "street",
                    GraphQLInputObjectField(
                        GraphQLNonNull(GraphQLString),
                        description="What street is this address?",
                    ),
                ),
                (
                    "city",
                    GraphQLInputObjectField(
                        GraphQLNonNull(GraphQLString),
                        description="The city the address is within?",
                    ),
                ),
                (
                    "country",
                    GraphQLInputObjectField(
                        GraphQLString,
                        description="The country (blank will assume USA).",
                        default_value="USA",
                    ),
                ),
            ]
        ),
    )

    schema = GraphQLSchema(
        query=GraphQLObjectType(
            name="HasInputObjectFields",
            fields={
                "geocode": GraphQLField(
                    description="Get a geocode from an address",
                    type=GraphQLString,
                    args={
                        "address": GraphQLArgument(
                            description="The address to lookup", type=AddressType
                        )
                    },
                )
            },
        )
    )

    _test_schema(schema)
Beispiel #17
0
def test_does_not_mutate_passed_field_definitions():
    fields = {
        "field1":
        GraphQLField(GraphQLString),
        "field2":
        GraphQLField(GraphQLString,
                     args={"id": GraphQLArgument(GraphQLString)}),
    }

    TestObject1 = GraphQLObjectType(name="Test1", fields=fields)
    TestObject2 = GraphQLObjectType(name="Test1", fields=fields)

    assert TestObject1.fields == TestObject2.fields
    assert fields == {
        "field1":
        GraphQLField(GraphQLString),
        "field2":
        GraphQLField(GraphQLString,
                     args={"id": GraphQLArgument(GraphQLString)}),
    }

    input_fields = {
        "field1": GraphQLInputObjectField(GraphQLString),
        "field2": GraphQLInputObjectField(GraphQLString),
    }

    TestInputObject1 = GraphQLInputObjectType(name="Test1",
                                              fields=input_fields)
    TestInputObject2 = GraphQLInputObjectType(name="Test2",
                                              fields=input_fields)

    assert TestInputObject1.fields == TestInputObject2.fields

    assert input_fields == {
        "field1": GraphQLInputObjectField(GraphQLString),
        "field2": GraphQLInputObjectField(GraphQLString),
    }
def test_does_not_mutate_passed_field_definitions():
    fields = {
        'field1':
        GraphQLField(GraphQLString),
        'field2':
        GraphQLField(GraphQLString,
                     args={'id': GraphQLArgument(GraphQLString)}),
    }

    TestObject1 = GraphQLObjectType(name='Test1', fields=fields)
    TestObject2 = GraphQLObjectType(name='Test1', fields=fields)

    assert TestObject1.fields == TestObject2.fields
    assert fields == {
        'field1':
        GraphQLField(GraphQLString),
        'field2':
        GraphQLField(GraphQLString,
                     args={'id': GraphQLArgument(GraphQLString)}),
    }

    input_fields = {
        'field1': GraphQLInputObjectField(GraphQLString),
        'field2': GraphQLInputObjectField(GraphQLString),
    }

    TestInputObject1 = GraphQLInputObjectType(name='Test1',
                                              fields=input_fields)
    TestInputObject2 = GraphQLInputObjectType(name='Test2',
                                              fields=input_fields)

    assert TestInputObject1.fields == TestInputObject2.fields

    assert input_fields == {
        'field1': GraphQLInputObjectField(GraphQLString),
        'field2': GraphQLInputObjectField(GraphQLString),
    }
Beispiel #19
0
    def prints_custom_directives():
        simple_directive = GraphQLDirective(
            "simpleDirective", [DirectiveLocation.FIELD]
        )
        complex_directive = GraphQLDirective(
            "complexDirective",
            [DirectiveLocation.FIELD, DirectiveLocation.QUERY],
            description="Complex Directive",
            args={
                "stringArg": GraphQLArgument(GraphQLString),
                "intArg": GraphQLArgument(GraphQLInt, default_value=-1),
            },
            is_repeatable=True,
        )

        schema = GraphQLSchema(directives=[simple_directive, complex_directive])
        assert expect_printed_schema(schema) == dedent(
            '''
            directive @simpleDirective on FIELD

            """Complex Directive"""
            directive @complexDirective(stringArg: String, intArg: Int = -1) repeatable on FIELD | QUERY
            '''  # noqa: E501
        )
Beispiel #20
0
def test_builds_a_schema_with_field_arguments_with_default_values():
    GeoType = GraphQLInputObjectType(
        name='Geo',
        fields=OrderedDict([
            ('lat', GraphQLInputObjectField(GraphQLFloat)),
            ('lon', GraphQLInputObjectField(GraphQLFloat)),
        ]))

    schema = GraphQLSchema(query=GraphQLObjectType(
        name='ArgFields',
        fields=OrderedDict(
            [('defaultInt',
              GraphQLField(GraphQLString,
                           args={
                               'intArg':
                               GraphQLArgument(GraphQLInt, default_value=10)
                           })),
             ('defaultList',
              GraphQLField(GraphQLString,
                           args={
                               'listArg':
                               GraphQLArgument(GraphQLList(GraphQLInt),
                                               default_value=[1, 2, 3])
                           })),
             ('defaultObject',
              GraphQLField(GraphQLString,
                           args={
                               'objArg':
                               GraphQLArgument(GeoType,
                                               default_value={
                                                   'lat': 37.485,
                                                   'lon': -122.148
                                               })
                           }))])))

    _test_schema(schema)
Beispiel #21
0
 def can_create_instance():
     arg = GraphQLArgument(GraphQLString, description='arg description')
     node = DirectiveDefinitionNode()
     locations = [DirectiveLocation.SCHEMA, DirectiveLocation.OBJECT]
     directive = GraphQLDirective(
         name='test',
         locations=[DirectiveLocation.SCHEMA, DirectiveLocation.OBJECT],
         args={'arg': arg},
         description='test description',
         ast_node=node)
     assert directive.name == 'test'
     assert directive.locations == locations
     assert directive.args == {'arg': arg}
     assert directive.description == 'test description'
     assert directive.ast_node is node
    def uses_provided_resolve_function():
        schema = _test_schema(
            GraphQLField(
                GraphQLString,
                args={
                    "aStr": GraphQLArgument(GraphQLString),
                    "aInt": GraphQLArgument(GraphQLInt),
                },
                resolve=lambda source, info, **args: repr([source, args]),
            )
        )

        def execute_query(query: str, root_value: Any = None) -> ExecutionResult:
            document = parse(query)
            return execute_sync(
                schema=schema,
                document=document,
                root_value=root_value,
            )

        assert execute_query("{ test }") == ({"test": "[None, {}]"}, None)

        assert execute_query("{ test }", "Source!") == (
            {"test": "['Source!', {}]"},
            None,
        )

        assert execute_query('{ test(aStr: "String!") }', "Source!") == (
            {"test": "['Source!', {'aStr': 'String!'}]"},
            None,
        )

        assert execute_query('{ test(aInt: -123, aStr: "String!") }', "Source!") == (
            {"test": "['Source!', {'aStr': 'String!', 'aInt': -123}]"},
            None,
        )
Beispiel #23
0
def email_schema_with_resolvers(subscribe_fn=None, resolve_fn=None):
    return GraphQLSchema(
        query=QueryType,
        subscription=GraphQLObjectType(
            "Subscription",
            {
                "importantEmail": GraphQLField(
                    EmailEventType,
                    args={"priority": GraphQLArgument(GraphQLInt)},
                    resolve=resolve_fn,
                    subscribe=subscribe_fn,
                )
            },
        ),
    )
Beispiel #24
0
    def builds_a_schema_with_field_arguments():
        schema = GraphQLSchema(
            GraphQLObjectType(
                "ArgFields",
                {
                    "one":
                    GraphQLField(
                        GraphQLString,
                        description="A field with a single arg",
                        args={
                            "intArg":
                            GraphQLArgument(GraphQLInt,
                                            description="This is an int arg")
                        },
                    ),
                    "two":
                    GraphQLField(
                        GraphQLString,
                        description="A field with two args",
                        args={
                            "listArg":
                            GraphQLArgument(
                                GraphQLList(GraphQLInt),
                                description="This is a list of int arg",
                            ),
                            "requiredArg":
                            GraphQLArgument(
                                GraphQLNonNull(GraphQLBoolean),
                                description="This is a required arg",
                            ),
                        },
                    ),
                },
            ))

        check_schema(schema)
Beispiel #25
0
def test_sorts_fields_and_argument_keys_if_not_using_ordered_dict():
    fields = {
        'b':
        GraphQLField(GraphQLString),
        'c':
        GraphQLField(GraphQLString),
        'a':
        GraphQLField(GraphQLString),
        'd':
        GraphQLField(GraphQLString,
                     args={
                         'q': GraphQLArgument(GraphQLString),
                         'x': GraphQLArgument(GraphQLString),
                         'v': GraphQLArgument(GraphQLString),
                         'a': GraphQLArgument(GraphQLString),
                         'n': GraphQLArgument(GraphQLString)
                     })
    }

    test_object = GraphQLObjectType(name='Test', fields=fields)
    ordered_fields = test_object.get_fields()
    assert list(ordered_fields.keys()) == ['a', 'b', 'c', 'd']
    field_with_args = test_object.get_fields().get('d')
    assert [a.name for a in field_with_args.args] == ['a', 'n', 'q', 'v', 'x']
Beispiel #26
0
 def _schema_with_input_field_of_type(input_field_type: GraphQLInputType):
     BadInputObjectType = GraphQLInputObjectType(
         "BadInputObject",
         {"badField": GraphQLInputField(input_field_type)})
     return GraphQLSchema(
         GraphQLObjectType(
             "Query",
             {
                 "f":
                 GraphQLField(
                     GraphQLString,
                     args={"badArg": GraphQLArgument(BadInputObjectType)},
                 )
             },
         ))
def describe_find_deprecated_usages():

    enum_type = GraphQLEnumType(
        "EnumType",
        {
            "ONE": GraphQLEnumValue(),
            "TWO": GraphQLEnumValue(deprecation_reason="Some enum reason."),
        },
    )

    schema = GraphQLSchema(
        GraphQLObjectType(
            "Query",
            {
                "normalField":
                GraphQLField(GraphQLString,
                             args={"enumArg": GraphQLArgument(enum_type)}),
                "deprecatedField":
                GraphQLField(GraphQLString,
                             deprecation_reason="Some field reason."),
            },
        ))

    def should_report_empty_set_for_no_deprecated_usages():
        errors = find_deprecated_usages(schema,
                                        parse("{ normalField(enumArg: ONE) }"))

        assert errors == []

    def should_report_usage_of_deprecated_fields():
        errors = find_deprecated_usages(
            schema, parse("{ normalField, deprecatedField }"))

        error_messages = [err.message for err in errors]

        assert error_messages == [
            "The field Query.deprecatedField is deprecated. Some field reason."
        ]

    def should_report_usage_of_deprecated_enums():
        errors = find_deprecated_usages(schema,
                                        parse("{ normalField(enumArg: TWO) }"))

        error_messages = [err.message for err in errors]

        assert error_messages == [
            "The enum value EnumType.TWO is deprecated. Some enum reason."
        ]
 def can_create_instance():
     arg = GraphQLArgument(GraphQLString, description="arg description")
     node = DirectiveDefinitionNode()
     locations = [DirectiveLocation.SCHEMA, DirectiveLocation.OBJECT]
     directive = GraphQLDirective(
         name="test",
         locations=[DirectiveLocation.SCHEMA, DirectiveLocation.OBJECT],
         args={"arg": arg},
         description="test description",
         ast_node=node,
     )
     assert directive.name == "test"
     assert directive.locations == locations
     assert directive.args == {"arg": arg}
     assert directive.description == "test description"
     assert directive.ast_node is node
Beispiel #29
0
 def reject_field_args_with_invalid_names():
     QueryType = GraphQLObjectType(
         "SomeObject",
         {
             "badField": GraphQLField(
                 GraphQLString,
                 args={"bad-name-with-dashes": GraphQLArgument(GraphQLString)},
             )
         },
     )
     schema = GraphQLSchema(QueryType)
     msg = validate_schema(schema)[0].message
     assert msg == (
         "Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/"
         " but 'bad-name-with-dashes' does not."
     )
    def prints_string_field_with_string_arg_with_default():
        schema = build_single_field_schema(
            GraphQLField(
                type_=GraphQLString,
                args={
                    "argOne":
                    GraphQLArgument(GraphQLString,
                                    default_value="tes\t de\fault")
                },
            ))

        assert expect_printed_schema(schema) == dedent(r"""
            type Query {
              singleField(argOne: String = "tes\t de\fault"): String
            }
            """)