Exemplo n.º 1
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),
        }
Exemplo n.º 2
0
def test_includes_nested_input_objects_in_the_map():
    NestedInputObject = GraphQLInputObjectType(
        name="NestedInputObject",
        fields={"value": GraphQLInputObjectField(GraphQLString)},
    )

    SomeInputObject = GraphQLInputObjectType(
        name="SomeInputObject",
        fields={"nested": GraphQLInputObjectField(NestedInputObject)},
    )

    SomeMutation = GraphQLObjectType(
        name="SomeMutation",
        fields={
            "mutateSomething":
            GraphQLField(type=BlogArticle,
                         args={"input": GraphQLArgument(SomeInputObject)})
        },
    )
    SomeSubscription = GraphQLObjectType(
        name="SomeSubscription",
        fields={
            "subscribeToSomething":
            GraphQLField(type=BlogArticle,
                         args={"input": GraphQLArgument(SomeInputObject)})
        },
    )

    schema = GraphQLSchema(query=BlogQuery,
                           mutation=SomeMutation,
                           subscription=SomeSubscription)

    assert schema.get_type_map()["NestedInputObject"] is NestedInputObject
Exemplo n.º 3
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),
        }
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.get_fields() == TestObject2.get_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.get_fields() == TestInputObject2.get_fields()

    assert input_fields == {
        'field1': GraphQLInputObjectField(GraphQLString),
        'field2': GraphQLInputObjectField(GraphQLString),
    }
Exemplo n.º 5
0
def test_includes_nested_input_objects_in_the_map():
    NestedInputObject = GraphQLInputObjectType(
        name='NestedInputObject',
        fields={'value': GraphQLInputObjectField(GraphQLString)})

    SomeInputObject = GraphQLInputObjectType(
        name='SomeInputObject',
        fields={'nested': GraphQLInputObjectField(NestedInputObject)})

    SomeMutation = GraphQLObjectType(
        name='SomeMutation',
        fields={
            'mutateSomething':
            GraphQLField(type=BlogArticle,
                         args={'input': GraphQLArgument(SomeInputObject)})
        })
    SomeSubscription = GraphQLObjectType(
        name='SomeSubscription',
        fields={
            'subscribeToSomething':
            GraphQLField(type=BlogArticle,
                         args={'input': GraphQLArgument(SomeInputObject)})
        })

    schema = GraphQLSchema(query=BlogQuery,
                           mutation=SomeMutation,
                           subscription=SomeSubscription)

    assert schema.get_type_map()['NestedInputObject'] is NestedInputObject
Exemplo n.º 6
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)
        }
Exemplo n.º 7
0
        def without_extensions():
            some_input_object = GraphQLInputObjectType(
                "SomeInputObject", {"someInputField": GraphQLInputField(dummy_type)}
            )

            assert some_input_object.extensions is None
            some_input_field = some_input_object.fields["someInputField"]
            assert some_input_field.extensions is None

            assert some_input_object.to_kwargs()["extensions"] is None
            assert some_input_field.to_kwargs()["extensions"] is None
    def prints_empty_types():
        schema = GraphQLSchema(
            types=[
                GraphQLEnumType("SomeEnum", cast(Dict[str, Any], {})),
                GraphQLInputObjectType("SomeInputObject", {}),
                GraphQLInterfaceType("SomeInterface", {}),
                GraphQLObjectType("SomeObject", {}),
                GraphQLUnionType("SomeUnion", []),
            ]
        )

        output = print_for_test(schema)
        assert output == dedent(
            """
            enum SomeEnum

            input SomeInputObject

            interface SomeInterface

            type SomeObject

            union SomeUnion
            """
        )
Exemplo n.º 9
0
 def accepts_an_input_object_type_with_input_type_as_field():
     # this is a shortcut syntax for simple input fields
     input_obj_type = GraphQLInputObjectType("SomeInputObject",
                                             {"f": GraphQLString})
     field = input_obj_type.fields["f"]
     assert isinstance(field, GraphQLInputField)
     assert field.type is GraphQLString
    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)
Exemplo n.º 11
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
            }
            """)
Exemplo n.º 12
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)
Exemplo n.º 13
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
            }
            """
        )
Exemplo n.º 14
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)
Exemplo n.º 15
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_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?"
            ]
Exemplo n.º 16
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={})}
         )
Exemplo n.º 17
0
 def rejects_an_input_object_type_with_resolvers():
     with raises(TypeError) as exc_info:
         # noinspection PyArgumentList
         GraphQLInputObjectType(
             'SomeInputObject',
             {'f': GraphQLInputField(GraphQLString, resolve=lambda: 0)})
     msg = str(exc_info.value)
     assert "got an unexpected keyword argument 'resolve'" in msg
     input_obj_type = GraphQLInputObjectType(
         'SomeInputObject',
         {'f': GraphQLField(GraphQLString, resolve=lambda: 0)})
     with raises(TypeError) as exc_info:
         if input_obj_type.fields:
             pass
     msg = str(exc_info.value)
     assert msg == ('SomeInputObject fields must be GraphQLInputField'
                    ' or input type objects.')
Exemplo n.º 18
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
Exemplo n.º 19
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
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)
                    },
                ),
            ),
            ('defaultNullInt',
             GraphQLField(GraphQLString,
                          args={
                              'intArg':
                              GraphQLArgument(GraphQLInt, default_value=None)
                          })),
            (
                "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)
Exemplo n.º 21
0
        def includes_nested_input_objects_in_the_map():
            NestedInputObject = GraphQLInputObjectType("NestedInputObject", {})
            SomeInputObject = GraphQLInputObjectType(
                "SomeInputObject",
                {"nested": GraphQLInputField(NestedInputObject)})

            schema = GraphQLSchema(
                GraphQLObjectType(
                    "Query",
                    {
                        "something":
                        GraphQLField(
                            GraphQLString,
                            {"input": GraphQLArgument(SomeInputObject)})
                    },
                ))
            assert schema.type_map["SomeInputObject"] is SomeInputObject
            assert schema.type_map["NestedInputObject"] is NestedInputObject
Exemplo n.º 22
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 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 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}]
Exemplo n.º 26
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)
Exemplo n.º 27
0
 def rejects_an_input_object_type_with_incorrect_fields_function():
     input_obj_type = GraphQLInputObjectType("SomeInputObject", lambda: [])
     with raises(TypeError) as exc_info:
         if input_obj_type.fields:
             pass
     msg = str(exc_info.value)
     assert msg == (
         "SomeInputObject fields must be a dict with field names as keys"
         " or a function which returns such an object.")
Exemplo n.º 28
0
    def internal_type(cls, schema):
        if cls._meta.abstract:
            raise Exception(
                "Abstract InputObjectTypes don't have a specific type.")

        return GraphQLInputObjectType(
            cls._meta.type_name,
            description=cls._meta.description,
            fields=partial(cls.fields_internal_types, schema),
        )
    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
            }
            """)
Exemplo n.º 30
0
    def prints_input_type():
        input_type = GraphQLInputObjectType(
            name="InputType", fields={"int": GraphQLInputField(GraphQLInt)})

        schema = GraphQLSchema(types=[input_type])
        output = print_for_test(schema)
        assert output == dedent("""
            input InputType {
              int: Int
            }
            """)
 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