示例#1
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 builds_a_schema_with_an_input_object():
        address_type = GraphQLInputObjectType('Address', {
            'street':
            GraphQLInputField(GraphQLNonNull(GraphQLString),
                              description='What street is this address?'),
            'city':
            GraphQLInputField(GraphQLNonNull(GraphQLString),
                              description='The city the address is within?'),
            'country':
            GraphQLInputField(
                GraphQLString,
                default_value='USA',
                description='The country (blank will assume USA).')
        },
                                              description='An input address')

        schema = GraphQLSchema(
            GraphQLObjectType(
                'HasInputObjectFields', {
                    'geocode':
                    GraphQLField(GraphQLString,
                                 args={
                                     'address':
                                     GraphQLArgument(
                                         address_type,
                                         description='The address to lookup')
                                 },
                                 description='Get a geocode from an address')
                }))

        check_schema(schema)
示例#3
0
    def does_not_mutate_passed_field_definitions():
        fields = {
            'field1':
            GraphQLField(GraphQLString),
            'field2':
            GraphQLField(GraphQLString,
                         args={'id': GraphQLArgument(GraphQLString)})
        }

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

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

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

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

        assert TestInputObject1.fields == TestInputObject2.fields
        assert input_fields == {
            'field1': GraphQLInputField(GraphQLString),
            'field2': GraphQLInputField(GraphQLString)
        }
示例#4
0
    def does_not_mutate_passed_field_definitions():
        output_fields = {
            "field1": GraphQLField(ScalarType),
            "field2": GraphQLField(
                ScalarType, args={"id": GraphQLArgument(ScalarType)}
            ),
        }

        test_object_1 = GraphQLObjectType("Test1", output_fields)
        test_object_2 = GraphQLObjectType("Test2", output_fields)

        assert test_object_1.fields == test_object_2.fields
        assert output_fields == {
            "field1": GraphQLField(ScalarType),
            "field2": GraphQLField(
                ScalarType, args={"id": GraphQLArgument(ScalarType)}
            ),
        }

        input_fields = {
            "field1": GraphQLInputField(ScalarType),
            "field2": GraphQLInputField(ScalarType),
        }

        test_input_object_1 = GraphQLInputObjectType("Test1", input_fields)
        test_input_object_2 = GraphQLInputObjectType("Test2", input_fields)

        assert test_input_object_1.fields == test_input_object_2.fields
        assert input_fields == {
            "field1": GraphQLInputField(ScalarType),
            "field2": GraphQLInputField(ScalarType),
        }
示例#5
0
    def does_not_mutate_passed_field_definitions():
        fields = {
            "field1":
            GraphQLField(GraphQLString),
            "field2":
            GraphQLField(GraphQLString,
                         args={"id": GraphQLArgument(GraphQLString)}),
        }

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

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

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

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

        assert TestInputObject1.fields == TestInputObject2.fields
        assert input_fields == {
            "field1": GraphQLInputField(GraphQLString),
            "field2": GraphQLInputField(GraphQLString),
        }
    def describe_for_graphql_input_object():
        TestInputObject = GraphQLInputObjectType(
            "TestInputObject",
            {
                "foo": GraphQLInputField(GraphQLNonNull(GraphQLInt)),
                "bar": GraphQLInputField(GraphQLInt),
            },
        )

        def returns_no_error_for_a_valid_input():
            result = coerce_value({"foo": 123}, TestInputObject)
            assert expect_value(result) == {"foo": 123}

        def returns_an_error_for_a_non_dict_value():
            result = coerce_value(123, TestInputObject)
            assert expect_error(result) == [
                "Expected type TestInputObject to be a dict."
            ]

        def returns_an_error_for_an_invalid_field():
            result = coerce_value({"foo": "abc"}, TestInputObject)
            assert expect_error(result) == [
                "Expected type Int at value.foo;"
                " Int cannot represent non-integer value: 'abc'"
            ]

        def returns_multiple_errors_for_multiple_invalid_fields():
            result = coerce_value({
                "foo": "abc",
                "bar": "def"
            }, TestInputObject)
            assert expect_error(result) == [
                "Expected type Int at value.foo;"
                " Int cannot represent non-integer value: 'abc'",
                "Expected type Int at value.bar;"
                " Int cannot represent non-integer value: 'def'",
            ]

        def returns_error_for_a_missing_required_field():
            result = coerce_value({"bar": 123}, TestInputObject)
            assert expect_error(result) == [
                "Field value.foo of required type Int! was not provided."
            ]

        def returns_error_for_an_unknown_field():
            result = coerce_value({
                "foo": 123,
                "unknownField": 123
            }, TestInputObject)
            assert expect_error(result) == [
                "Field 'unknownField' is not defined by type TestInputObject."
            ]

        def returns_error_for_a_misspelled_field():
            result = coerce_value({"foo": 123, "bart": 123}, TestInputObject)
            assert expect_error(result) == [
                "Field 'bart' is not defined by type TestInputObject;"
                " did you mean bar?"
            ]
示例#7
0
 def graphql_input_field():
     field = GraphQLInputField(GraphQLString, description="not lazy")
     assert field.description == "not lazy"
     with raises(TypeError, match="Input field description must be a string\\."):
         GraphQLInputField(GraphQLString, description=lazy_string)
     with registered(LazyString):
         field = GraphQLInputField(GraphQLString, description=lazy_string)
         assert field.description is lazy_string
         assert str(field.description).endswith("lazy?")
    def converts_input_objects_with_explicit_nulls():
        input_obj = GraphQLInputObjectType(
            "MyInputObj",
            {"foo": GraphQLInputField(GraphQLFloat), "bar": GraphQLInputField(my_enum)},
        )

        assert ast_from_value({"foo": None}, input_obj) == ObjectValueNode(
            fields=[ObjectFieldNode(name=NameNode(value="foo"), value=NullValueNode())]
        )
示例#9
0
    def builds_a_schema_with_field_arguments_with_default_values():
        geo_type = GraphQLInputObjectType(
            "Geo",
            {
                "lat": GraphQLInputField(GraphQLFloat),
                "lon": GraphQLInputField(GraphQLFloat),
            },
        )

        schema = GraphQLSchema(
            GraphQLObjectType(
                "ArgFields",
                {
                    "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(geo_type,
                                            default_value={
                                                "lat": 37.485,
                                                "lon": -122.148
                                            })
                        },
                    ),
                    "defaultNull":
                    GraphQLField(
                        GraphQLString,
                        args={
                            "intArg":
                            GraphQLArgument(GraphQLInt, default_value=None)
                        },
                    ),
                    "noDefaults":
                    GraphQLField(GraphQLString,
                                 args={"intArg": GraphQLArgument(GraphQLInt)}),
                },
            ))

        check_schema(schema)
 def transforms_values_with_out_type():
     # This is an extension of GraphQL.js.
     complex_input_obj = GraphQLInputObjectType(
         "Complex",
         {
             "real": GraphQLInputField(GraphQLFloat),
             "imag": GraphQLInputField(GraphQLFloat),
         },
         out_type=lambda value: complex(value["real"], value["imag"]),
     )
     assert _value_from("{ real: 1, imag: 2 }", complex_input_obj) == 1 + 2j
 def transforms_values_with_out_type():
     # This is an extension of GraphQL.js.
     ComplexInputObject = GraphQLInputObjectType(
         "Complex",
         {
             "real": GraphQLInputField(GraphQLFloat),
             "imag": GraphQLInputField(GraphQLFloat),
         },
         out_type=lambda value: complex(value["real"], value["imag"]),
     )
     result = _coerce_value({"real": 1, "imag": 2}, ComplexInputObject)
     assert expect_value(result) == 1 + 2j
    def converts_input_objects_with_explicit_nulls():
        input_obj = GraphQLInputObjectType(
            'MyInputObj', {
                'foo': GraphQLInputField(GraphQLFloat),
                'bar': GraphQLInputField(my_enum)
            })

        assert ast_from_value({
            'foo': None
        }, input_obj) == ObjectValueNode(fields=[
            ObjectFieldNode(name=NameNode(value='foo'), value=NullValueNode())
        ])
 def transforms_names_using_out_name():
     # This is an extension of GraphQL.js.
     ComplexInputObject = GraphQLInputObjectType(
         "Complex",
         {
             "realPart": GraphQLInputField(GraphQLFloat, out_name="real_part"),
             "imagPart": GraphQLInputField(
                 GraphQLFloat, default_value=0, out_name="imag_part"
             ),
         },
     )
     result = _coerce_value({"realPart": 1}, ComplexInputObject)
     assert expect_value(result) == {"real_part": 1, "imag_part": 0}
示例#14
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,
        )
示例#15
0
        def returns_false_for_optional_input_field():
            opt_field1 = GraphQLInputField(GraphQLString)
            assert is_required_input_field(opt_field1) is False

            opt_field2 = GraphQLInputField(GraphQLString, default_value=None)
            assert is_required_input_field(opt_field2) is False

            opt_field3 = GraphQLInputField(
                GraphQLList(GraphQLNonNull(GraphQLString)))
            assert is_required_input_field(opt_field3) is False

            opt_field4 = GraphQLInputField(GraphQLNonNull(GraphQLString),
                                           default_value="default")
            assert is_required_input_field(opt_field4) is False
 def transforms_names_using_out_name():
     # This is an extension of GraphQL.js.
     complex_input_obj = GraphQLInputObjectType(
         "Complex",
         {
             "realPart": GraphQLInputField(GraphQLFloat, out_name="real_part"),
             "imagPart": GraphQLInputField(
                 GraphQLFloat, default_value=0, out_name="imag_part"
             ),
         },
     )
     assert _value_from("{ realPart: 1 }", complex_input_obj) == {
         "real_part": 1,
         "imag_part": 0,
     }
示例#17
0
    def prints_input_type():
        InputType = GraphQLInputObjectType(
            name="InputType", fields={"int": GraphQLInputField(GraphQLInt)}
        )

        Root = GraphQLObjectType(
            name="Root",
            fields={
                "str": GraphQLField(
                    GraphQLString, args={"argOne": GraphQLArgument(InputType)}
                )
            },
        )

        Schema = GraphQLSchema(Root)
        output = print_for_test(Schema)
        assert output == dedent(
            """
            schema {
              query: Root
            }

            input InputType {
              int: Int
            }

            type Root {
              str(argOne: InputType): String
            }
            """
        )
    def converts_input_objects():
        input_obj = GraphQLInputObjectType(
            "MyInputObj",
            {"foo": GraphQLInputField(GraphQLFloat), "bar": GraphQLInputField(my_enum)},
        )

        assert ast_from_value({"foo": 3, "bar": "HELLO"}, input_obj) == ObjectValueNode(
            fields=[
                ObjectFieldNode(
                    name=NameNode(value="foo"), value=FloatValueNode(value="3")
                ),
                ObjectFieldNode(
                    name=NameNode(value="bar"), value=EnumValueNode(value="HELLO")
                ),
            ]
        )
    def converts_input_objects():
        input_obj = GraphQLInputObjectType(
            'MyInputObj', {
                'foo': GraphQLInputField(GraphQLFloat),
                'bar': GraphQLInputField(my_enum)
            })

        assert ast_from_value({
            'foo': 3,
            'bar': 'HELLO'
        }, input_obj) == ObjectValueNode(fields=[
            ObjectFieldNode(name=NameNode(value='foo'),
                            value=FloatValueNode(value='3')),
            ObjectFieldNode(name=NameNode(value='bar'),
                            value=EnumValueNode(value='HELLO'))
        ])
示例#20
0
    def prints_input_type():
        InputType = GraphQLInputObjectType(
            name='InputType', fields={'int': GraphQLInputField(GraphQLInt)})

        Root = GraphQLObjectType(
            name='Root',
            fields={
                'str':
                GraphQLField(GraphQLString,
                             args={'argOne': GraphQLArgument(InputType)})
            })

        Schema = GraphQLSchema(Root)
        output = print_for_test(Schema)
        assert output == dedent("""
            schema {
              query: Root
            }

            input InputType {
              int: Int
            }

            type Root {
              str(argOne: InputType): String
            }
            """)
示例#21
0
 def with_bad_extensions(extensions):
     with raises(TypeError, match=bad_extensions_msg("SomeInputObject")):
         # noinspection PyTypeChecker
         GraphQLInputObjectType("SomeInputObject", {}, extensions=extensions)
     with raises(TypeError, match=bad_extensions_msg("Input field")):
         # noinspection PyTypeChecker
         GraphQLInputField(dummy_type, extensions=extensions)
示例#22
0
    def describe_for_graphql_input_object():
        TestInputObject = GraphQLInputObjectType('TestInputObject', {
            'foo': GraphQLInputField(GraphQLNonNull(GraphQLInt)),
            'bar': GraphQLInputField(GraphQLInt)})

        def returns_no_error_for_a_valid_input():
            result = coerce_value({'foo': 123}, TestInputObject)
            assert expect_value(result) == {'foo': 123}

        def returns_error_for_a_non_dict_value():
            result = coerce_value(123, TestInputObject)
            assert expect_error(result) == [
                'Expected type TestInputObject to be a dict.']

        def returns_error_for_an_invalid_field():
            result = coerce_value({'foo': 'abc'}, TestInputObject)
            assert expect_error(result) == [
                'Expected type Int at value.foo;'
                " Int cannot represent non-integer value: 'abc'"]

        def returns_multiple_errors_for_multiple_invalid_fields():
            result = coerce_value(
                {'foo': 'abc', 'bar': 'def'}, TestInputObject)
            assert expect_error(result) == [
                'Expected type Int at value.foo;'
                " Int cannot represent non-integer value: 'abc'",
                'Expected type Int at value.bar;'
                " Int cannot represent non-integer value: 'def'"]

        def returns_error_for_a_missing_required_field():
            result = coerce_value({'bar': 123}, TestInputObject)
            assert expect_error(result) == [
                'Field value.foo'
                ' of required type Int! was not provided.']

        def returns_error_for_an_unknown_field():
            result = coerce_value(
                {'foo': 123, 'unknownField': 123}, TestInputObject)
            assert expect_error(result) == [
                "Field 'unknownField' is not defined"
                ' by type TestInputObject.']

        def returns_error_for_a_misspelled_field():
            result = coerce_value({'foo': 123, 'bart': 123}, TestInputObject)
            assert expect_error(result) == [
                "Field 'bart' is not defined"
                ' by type TestInputObject; did you mean bar?']
    def builds_a_schema_with_field_arguments_with_default_values():
        geo_type = GraphQLInputObjectType(
            'Geo', {
                'lat': GraphQLInputField(GraphQLFloat),
                'lon': GraphQLInputField(GraphQLFloat)
            })

        schema = GraphQLSchema(
            GraphQLObjectType(
                'ArgFields', {
                    '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(geo_type,
                                                     default_value={
                                                         'lat': 37.485,
                                                         'lon': -122.148
                                                     })
                                 }),
                    'defaultNull':
                    GraphQLField(GraphQLString,
                                 args={
                                     'intArg':
                                     GraphQLArgument(GraphQLInt,
                                                     default_value=None)
                                 }),
                    'noDefaults':
                    GraphQLField(GraphQLString,
                                 args={'intArg': GraphQLArgument(GraphQLInt)})
                }))

        check_schema(schema)
示例#24
0
 def rejects_an_input_object_type_with_resolver_constant():
     with raises(
         TypeError, match="got an unexpected keyword argument 'resolve'"
     ):
         # noinspection PyArgumentList
         GraphQLInputObjectType(
             "SomeInputObject", {"f": GraphQLInputField(ScalarType, resolve={})}
         )
示例#25
0
 def accepts_an_input_object_type_with_a_field_function():
     input_obj_type = GraphQLInputObjectType(
         "SomeInputObject", lambda: {"f": GraphQLInputField(ScalarType)}
     )
     assert list(input_obj_type.fields) == ["f"]
     input_field = input_obj_type.fields["f"]
     assert isinstance(input_field, GraphQLInputField)
     assert input_field.type is ScalarType
示例#26
0
 def rejects_an_input_object_type_with_resolver_constant():
     with raises(TypeError) as exc_info:
         # noinspection PyArgumentList
         GraphQLInputObjectType(
             "SomeInputObject",
             {"f": GraphQLInputField(GraphQLString, resolve={})})
     msg = str(exc_info.value)
     assert "got an unexpected keyword argument 'resolve'" in msg
示例#27
0
 def build_delete_type(self):
     # TODO: Use a function cache.
     type = getattr(self, '_delete_type', None)
     if not type:
         type = GraphQLInputObjectType(
             name='DeleteByIDInput',
             fields={'id': GraphQLInputField(GraphQLInt)})
         self._delete_type = type
     return type
 def _get_test_input_object(default_value):
     return GraphQLInputObjectType(
         "TestInputObject",
         {
             "foo":
             GraphQLInputField(GraphQLScalarType("TestScalar"),
                               default_value=default_value)
         },
     )
        def returns_a_list_for_a_dictionary():
            test_list_of_objects = GraphQLList(
                GraphQLInputObjectType(
                    "TestObject", {"length": GraphQLInputField(GraphQLInt)}
                )
            )

            result = _coerce_value({"length": 100500}, test_list_of_objects)
            assert expect_value(result) == [{"length": 100500}]
    def prints_input_type():
        input_type = GraphQLInputObjectType(
            name="InputType", fields={"int": GraphQLInputField(GraphQLInt)})

        schema = GraphQLSchema(types=[input_type])
        assert expect_printed_schema(schema) == dedent("""
            input InputType {
              int: Int
            }
            """)