def convert_using_parse_literal_from_a_custom_scalar_type():
        def pass_through_parse_literal(node, _vars=None):
            assert node.kind == "string_value"
            return node.value

        pass_through_scalar = GraphQLScalarType(
            "PassThroughScalar",
            parse_literal=pass_through_parse_literal,
            parse_value=lambda value: value,  # pragma: no cover
        )

        assert _value_from('"value"', pass_through_scalar) == "value"

        def throw_parse_literal(_node, _vars=None):
            raise RuntimeError("Test")

        throw_scalar = GraphQLScalarType(
            "ThrowScalar",
            parse_literal=throw_parse_literal,
            parse_value=lambda value: value,  # pragma: no cover
        )

        assert _value_from("value", throw_scalar) is Undefined

        return_undefined_scalar = GraphQLScalarType(
            "ReturnUndefinedScalar",
            parse_literal=lambda _node, _vars=None: Undefined,
            parse_value=lambda value: value,  # pragma: no cover
        )

        assert _value_from("value", return_undefined_scalar) is Undefined
示例#2
0
        def with_extensions():
            scalar_extensions = {"SomeScalarExt": "scalar"}
            some_scalar = GraphQLScalarType("SomeScalar",
                                            extensions=scalar_extensions)

            assert some_scalar.extensions is scalar_extensions
            assert some_scalar.to_kwargs()["extensions"] is scalar_extensions
    def converts_using_serialize_from_a_custom_scalar_type():
        pass_through_scalar = GraphQLScalarType(
            "PassThroughScalar", serialize=lambda value: value,
        )

        assert ast_from_value("value", pass_through_scalar) == StringValueNode(
            value="value"
        )

        return_null_scalar = GraphQLScalarType(
            "ReturnNullScalar", serialize=lambda value: None,
        )

        assert ast_from_value("value", return_null_scalar) is None

        class SomeClass:
            pass

        return_custom_class_scalar = GraphQLScalarType(
            "ReturnCustomClassScalar", serialize=lambda value: SomeClass(),
        )

        with raises(TypeError) as exc_info:
            ast_from_value("value", return_custom_class_scalar)
        msg = str(exc_info.value)
        assert msg == "Cannot convert value to AST: <SomeClass instance>."
示例#4
0
 def rejects_a_scalar_type_not_defining_serialize():
     with raises(TypeError) as exc_info:
         # noinspection PyArgumentList
         schema_with_field_type(GraphQLScalarType("SomeScalar"))
     msg = str(exc_info.value)
     assert "missing 1 required positional argument: 'serialize'" in msg
     with raises(TypeError) as exc_info:
         # noinspection PyTypeChecker
         schema_with_field_type(GraphQLScalarType("SomeScalar", None))
     msg = str(exc_info.value)
     assert msg == ("SomeScalar must provide 'serialize' function."
                    " If this custom Scalar is also used as an input type,"
                    " ensure 'parse_value' and 'parse_literal' functions"
                    " are also provided.")
def test_uses_built_in_scalars_when_possible():
    customScalar = GraphQLScalarType(
        name='CustomScalar',
        serialize=lambda: None
    )

    schema = GraphQLSchema(
        query=GraphQLObjectType(
            name='Scalars',
            fields=OrderedDict([
                ('int', GraphQLField(GraphQLInt)),
                ('float', GraphQLField(GraphQLFloat)),
                ('string', GraphQLField(GraphQLString)),
                ('boolean', GraphQLField(GraphQLBoolean)),
                ('id', GraphQLField(GraphQLID)),
                ('custom', GraphQLField(customScalar)),
            ])
        )
    )

    client_schema = _test_schema(schema)

    assert client_schema.get_type('Int') == GraphQLInt
    assert client_schema.get_type('Float') == GraphQLFloat
    assert client_schema.get_type('String') == GraphQLString
    assert client_schema.get_type('Boolean') == GraphQLBoolean
    assert client_schema.get_type('ID') == GraphQLID

    assert client_schema.get_type('CustomScalar') != customScalar
示例#6
0
 def accepts_a_scalar_type_defining_parse_value_and_parse_literal():
     assert GraphQLScalarType(
         "SomeScalar",
         serialize=lambda: None,
         parse_value=lambda: None,
         parse_literal=lambda: None,
     )
示例#7
0
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.'
    }]
示例#8
0
        def reports_error_for_custom_scalar_that_returns_undefined():
            custom_scalar = GraphQLScalarType(
                "CustomScalar", parse_value=lambda value: Undefined
            )

            schema = GraphQLSchema(
                GraphQLObjectType(
                    "Query",
                    {
                        "invalidArg": GraphQLField(
                            GraphQLString, args={"arg": GraphQLArgument(custom_scalar)}
                        )
                    },
                )
            )

            assert_errors(
                "{ invalidArg(arg: 123) }",
                [
                    {
                        "message": "Expected value of type 'CustomScalar', found 123.",
                        "locations": [(1, 19)],
                    },
                ],
                schema=schema,
            )
    def fails_when_serialize_of_custom_scalar_does_not_return_a_value():
        custom_scalar = GraphQLScalarType(
            "CustomScalar",
            serialize=lambda _value: Undefined  # returns nothing
        )
        schema = GraphQLSchema(
            GraphQLObjectType(
                "Query",
                {
                    "customScalar":
                    GraphQLField(custom_scalar,
                                 resolve=lambda *_args: "CUSTOM_VALUE")
                },
            ))

        result = execute(schema, parse("{ customScalar }"))
        assert result == (
            {
                "customScalar": None
            },
            [{
                "message": "Expected a value of type 'CustomScalar'"
                " but received: 'CUSTOM_VALUE'",
                "locations": [(1, 3)],
                "path": ["customScalar"],
            }],
        )
    def describe_for_graphql_scalar():
        def _parse_value(input_dict):
            assert isinstance(input_dict, dict)
            error = input_dict.get("error")
            if error:
                raise error
            return input_dict.get("value")

        TestScalar = GraphQLScalarType("TestScalar", parse_value=_parse_value)

        def returns_no_error_for_valid_input():
            result = coerce_value({"value": 1}, TestScalar)
            assert expect_value(result) == 1

        def returns_no_error_for_null_result():
            result = coerce_value({"value": None}, TestScalar)
            assert expect_value(result) is None

        def returns_no_error_for_nan_result():
            result = coerce_value({"value": nan}, TestScalar)
            assert expect_value(result) is nan

        def returns_an_error_for_undefined_result():
            error = ValueError("Some error message")
            result = coerce_value({"error": error}, TestScalar)
            assert expect_errors(result) == [
                "Expected type TestScalar. Some error message"
            ]
    def can_use_client_schema_for_limited_execution():
        custom_scalar = GraphQLScalarType('CustomScalar',
                                          serialize=lambda: None)

        schema = GraphQLSchema(
            GraphQLObjectType(
                'Query', {
                    'foo':
                    GraphQLField(GraphQLString,
                                 args={
                                     'custom1': GraphQLArgument(custom_scalar),
                                     'custom2': GraphQLArgument(custom_scalar)
                                 })
                }))

        introspection = introspection_from_schema(schema)
        client_schema = build_client_schema(introspection)

        class Data:
            foo = 'bar'
            unused = 'value'

        result = graphql_sync(client_schema,
                              'query Limited($v: CustomScalar) {'
                              ' foo(custom1: 123, custom2: $v) }',
                              Data(),
                              variable_values={'v': 'baz'})

        assert result.data == {'foo': 'bar'}
示例#12
0
    def can_use_client_schema_for_limited_execution():
        custom_scalar = GraphQLScalarType("CustomScalar",
                                          serialize=lambda: None)

        schema = GraphQLSchema(
            GraphQLObjectType(
                "Query",
                {
                    "foo":
                    GraphQLField(
                        GraphQLString,
                        args={
                            "custom1": GraphQLArgument(custom_scalar),
                            "custom2": GraphQLArgument(custom_scalar),
                        },
                    )
                },
            ))

        introspection = introspection_from_schema(schema)
        client_schema = build_client_schema(introspection)

        class Data:
            foo = "bar"
            unused = "value"

        result = graphql_sync(
            client_schema,
            "query Limited($v: CustomScalar) { foo(custom1: 123, custom2: $v) }",
            Data(),
            variable_values={"v": "baz"},
        )

        assert result.data == {"foo": "bar"}
示例#13
0
    def uses_built_in_scalars_when_possible():
        custom_scalar = GraphQLScalarType("CustomScalar",
                                          serialize=lambda: None)

        schema = GraphQLSchema(
            GraphQLObjectType(
                "Scalars",
                {
                    "int": GraphQLField(GraphQLInt),
                    "float": GraphQLField(GraphQLFloat),
                    "string": GraphQLField(GraphQLString),
                    "boolean": GraphQLField(GraphQLBoolean),
                    "id": GraphQLField(GraphQLID),
                    "custom": GraphQLField(custom_scalar),
                },
            ))

        check_schema(schema)

        introspection = introspection_from_schema(schema)
        client_schema = build_client_schema(introspection)

        # Built-ins are used
        assert client_schema.get_type("Int") is GraphQLInt
        assert client_schema.get_type("Float") is GraphQLFloat
        assert client_schema.get_type("String") is GraphQLString
        assert client_schema.get_type("Boolean") is GraphQLBoolean
        assert client_schema.get_type("ID") is GraphQLID

        # Custom are built
        assert client_schema.get_type("CustomScalar") is not custom_scalar
def test_uses_built_in_scalars_when_possible():
    customScalar = GraphQLScalarType(name="CustomScalar",
                                     serialize=lambda: None)

    schema = GraphQLSchema(query=GraphQLObjectType(
        name="Scalars",
        fields=OrderedDict([
            ("int", GraphQLField(GraphQLInt)),
            ("float", GraphQLField(GraphQLFloat)),
            ("string", GraphQLField(GraphQLString)),
            ("boolean", GraphQLField(GraphQLBoolean)),
            ("id", GraphQLField(GraphQLID)),
            ("custom", GraphQLField(customScalar)),
        ]),
    ))

    client_schema = _test_schema(schema)

    assert client_schema.get_type("Int") == GraphQLInt
    assert client_schema.get_type("Float") == GraphQLFloat
    assert client_schema.get_type("String") == GraphQLString
    assert client_schema.get_type("Boolean") == GraphQLBoolean
    assert client_schema.get_type("ID") == GraphQLID

    assert client_schema.get_type("CustomScalar") != customScalar
    def prints_custom_scalar():
        odd_type = GraphQLScalarType(name="Odd")

        schema = GraphQLSchema(types=[odd_type])
        assert expect_printed_schema(schema) == dedent("""
            scalar Odd
            """)
    def uses_built_in_scalars_when_possible():
        custom_scalar = GraphQLScalarType('CustomScalar',
                                          serialize=lambda: None)

        schema = GraphQLSchema(
            GraphQLObjectType(
                'Scalars', {
                    'int': GraphQLField(GraphQLInt),
                    'float': GraphQLField(GraphQLFloat),
                    'string': GraphQLField(GraphQLString),
                    'boolean': GraphQLField(GraphQLBoolean),
                    'id': GraphQLField(GraphQLID),
                    'custom': GraphQLField(custom_scalar)
                }))

        check_schema(schema)

        introspection = introspection_from_schema(schema)
        client_schema = build_client_schema(introspection)

        # Built-ins are used
        assert client_schema.get_type('Int') is GraphQLInt
        assert client_schema.get_type('Float') is GraphQLFloat
        assert client_schema.get_type('String') is GraphQLString
        assert client_schema.get_type('Boolean') is GraphQLBoolean
        assert client_schema.get_type('ID') is GraphQLID

        # Custom are built
        assert client_schema.get_type('CustomScalar') is not custom_scalar
示例#17
0
        def reports_original_error_for_custom_scalar_which_throws():
            def parse_value(value):
                raise Exception(f"Invalid scalar is always invalid: {inspect(value)}")

            custom_scalar = GraphQLScalarType("Invalid", parse_value=parse_value)

            schema = GraphQLSchema(
                query=GraphQLObjectType(
                    "Query",
                    {
                        "invalidArg": GraphQLField(
                            GraphQLString, {"arg": GraphQLArgument(custom_scalar)}
                        )
                    },
                )
            )

            errors = assert_errors(
                "{ invalidArg(arg: 123) }",
                [
                    {
                        "message": "Expected value of type 'Invalid', found 123;"
                        " Invalid scalar is always invalid: 123",
                        "locations": [(1, 19)],
                    }
                ],
                schema=schema,
            )

            assert str(errors[0].original_error) == (
                "Invalid scalar is always invalid: 123"
            )
示例#18
0
 def accepts_a_scalar_type_defining_parse_value_and_parse_literal():
     schema_with_field_type(
         GraphQLScalarType(
             "SomeScalar",
             serialize=lambda: None,
             parse_value=lambda: None,
             parse_literal=lambda: None,
         ))
示例#19
0
 def rejects_a_scalar_type_defining_parse_literal_but_not_parse_value():
     with raises(TypeError) as exc_info:
         GraphQLScalarType("SomeScalar", lambda: None, parse_literal=lambda: None)
     msg = str(exc_info.value)
     assert msg == (
         "SomeScalar must provide both"
         " 'parse_value' and 'parse_literal' functions."
     )
示例#20
0
    def prints_custom_scalar():
        odd_type = GraphQLScalarType(name="Odd")

        schema = GraphQLSchema(types=[odd_type])
        output = print_for_test(schema)
        assert output == dedent("""
            scalar Odd
            """)
    def prints_custom_scalar_with_specified_by_url():
        foo_type = GraphQLScalarType(
            name="Foo", specified_by_url="https://example.com/foo_spec")

        schema = GraphQLSchema(types=[foo_type])
        assert expect_printed_schema(schema) == dedent("""
            scalar Foo @specifiedBy(url: "https://example.com/foo_spec")
            """)
示例#22
0
 def rejects_a_scalar_type_defining_parse_value_but_not_parse_literal():
     with raises(TypeError) as exc_info:
         schema_with_field_type(
             GraphQLScalarType('SomeScalar',
                               lambda: None,
                               parse_value=lambda: None))
     msg = str(exc_info.value)
     assert msg == ('SomeScalar must provide both'
                    " 'parse_value' and 'parse_literal' functions.")
示例#23
0
 def rejects_a_scalar_type_defining_serialize_with_incorrect_type():
     with raises(TypeError) as exc_info:
         # noinspection PyTypeChecker
         schema_with_field_type(GraphQLScalarType("SomeScalar", {}))
     msg = str(exc_info.value)
     assert msg == ("SomeScalar must provide 'serialize' function."
                    " If this custom Scalar is also used as an input type,"
                    " ensure 'parse_value' and 'parse_literal' functions"
                    " are also provided.")
 def _get_test_input_object(default_value):
     return GraphQLInputObjectType(
         "TestInputObject",
         {
             "foo":
             GraphQLInputField(GraphQLScalarType("TestScalar"),
                               default_value=default_value)
         },
     )
示例#25
0
    def internal_type(cls, schema):
        serialize = getattr(cls, 'serialize')
        parse_literal = getattr(cls, 'parse_literal')
        parse_value = getattr(cls, 'parse_value')

        return GraphQLScalarType(name=cls._meta.type_name,
                                 description=cls._meta.description,
                                 serialize=serialize,
                                 parse_value=parse_value,
                                 parse_literal=parse_literal)
示例#26
0
 def rejects_a_scalar_type_incorrectly_defining_parse_literal_and_value():
     with raises(TypeError) as exc_info:
         # noinspection PyTypeChecker
         schema_with_field_type(
             GraphQLScalarType("SomeScalar",
                               lambda: None,
                               parse_value={},
                               parse_literal={}))
     msg = str(exc_info.value)
     assert msg == ("SomeScalar must provide both"
                    " 'parse_value' and 'parse_literal' functions.")
示例#27
0
def test_prints_custom_scalar():
    OddType = GraphQLScalarType(name='Odd',
                                serialize=lambda v: v if v % 2 == 1 else None)

    Root = GraphQLObjectType(name='Root',
                             fields={'odd': GraphQLField(OddType)})

    Schema = GraphQLSchema(Root)
    output = print_for_test(Schema)

    assert output == '''
示例#28
0
def test_update_schema_scalars_scalar_not_found_in_schema():

    NotFoundScalar = GraphQLScalarType(
        name="abcd",
    )

    with pytest.raises(KeyError) as exc_info:
        update_schema_scalars(schema, [MoneyScalar, NotFoundScalar])

    exception = exc_info.value

    assert "Scalar 'abcd' not found in schema." in str(exception)
示例#29
0
    def preserves_the_order_of_user_provided_types():
        a_type = GraphQLObjectType(
            "A", {"sub": GraphQLField(GraphQLScalarType("ASub"))})
        z_type = GraphQLObjectType(
            "Z", {"sub": GraphQLField(GraphQLScalarType("ZSub"))})
        query_type = GraphQLObjectType(
            "Query",
            {
                "a": GraphQLField(a_type),
                "z": GraphQLField(z_type),
                "sub": GraphQLField(GraphQLScalarType("QuerySub")),
            },
        )
        schema = GraphQLSchema(query_type, types=[z_type, query_type, a_type])

        type_names = list(schema.type_map)
        assert type_names == [
            "Z",
            "ZSub",
            "Query",
            "QuerySub",
            "A",
            "ASub",
            "Boolean",
            "String",
            "__Schema",
            "__Type",
            "__TypeKind",
            "__Field",
            "__InputValue",
            "__EnumValue",
            "__Directive",
            "__DirectiveLocation",
        ]

        # Also check that this order is stable
        copy_schema = GraphQLSchema(**schema.to_kwargs())
        assert list(copy_schema.type_map) == type_names
示例#30
0
    def rejects_a_schema_which_redefines_a_built_in_type():
        FakeString = GraphQLScalarType('String', serialize=lambda: None)

        QueryType = GraphQLObjectType(
            'Query', {
                'normal': GraphQLField(GraphQLString),
                'fake': GraphQLField(FakeString)
            })

        with raises(TypeError) as exc_info:
            GraphQLSchema(QueryType)
        msg = str(exc_info.value)
        assert msg == ('Schema must contain unique named types'
                       f" but contains multiple types named 'String'.")