class TestListOfNotNullT_Promise_Array_T: # [T!] Promise<Array<T>> type = GraphQLList(GraphQLNonNull(GraphQLInt)) test_contains_value = check(resolved([1, 2]), {'data': { 'nest': { 'test': [1, 2] } }}) test_contains_null = check( resolved([1, None, 2]), { 'data': { 'nest': { 'test': None } }, 'errors': [{ 'locations': [{ 'column': 10, 'line': 1 }], 'message': 'Cannot return null for non-nullable field DataType.test.' }] }) test_returns_null = check(resolved(None), {'data': { 'nest': { 'test': None } }}) test_rejected = check( lambda: rejected(Exception('bad')), { 'data': { 'nest': { 'test': None } }, 'errors': [{ 'locations': [{ 'column': 10, 'line': 1 }], 'message': 'bad' }] })
class TestListOfNotNullT_Array_Promise_T: # [T!] Array<Promise<T>> type = GraphQLList(GraphQLNonNull(GraphQLInt)) test_contains_values = check([resolved(1), resolved(2)], {"data": { "nest": { "test": [1, 2] } }}) test_contains_null = check( [resolved(1), resolved(None), resolved(2)], { "data": { "nest": { "test": None } }, "errors": [{ "locations": [{ "column": 10, "line": 1 }], "path": ["nest", "test", 1], "message": "Cannot return null for non-nullable field DataType.test.", }], }, ) test_contains_reject = check( lambda: [resolved(1), rejected(GraphQLError("bad")), resolved(2)], { "data": { "nest": { "test": None } }, "errors": [{ "locations": [{ "column": 10, "line": 1 }], "path": ["nest", "test", 1], "message": "bad", }], }, )
def test_prints_list_non_null_string_field(): output = print_single_field_schema( GraphQLField((GraphQLList(GraphQLNonNull(GraphQLString)))) ) assert ( output == """ schema { query: Root } type Root { singleField: [String!] } """ )
def test_prohibits_putting_non_object_types_in_unions(): bad_union_types = [ GraphQLInt, GraphQLNonNull(GraphQLInt), GraphQLList(GraphQLInt), InterfaceType, UnionType, EnumType, InputObjectType ] for x in bad_union_types: with raises(Exception) as excinfo: GraphQLSchema(GraphQLObjectType('Root', fields={'union': GraphQLField(GraphQLUnionType('BadUnion', [x]))})) assert 'BadUnion may only contain Object types, it cannot contain: ' + str(x) + '.' \ == str(excinfo.value)
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 converts_boolean_values_to_asts(): assert ast_from_value(True, GraphQLBoolean) == BooleanValueNode(value=True) assert ast_from_value(False, GraphQLBoolean) == BooleanValueNode(value=False) assert ast_from_value(INVALID, GraphQLBoolean) is None assert ast_from_value(nan, GraphQLInt) is None assert ast_from_value(None, GraphQLBoolean) == NullValueNode() assert ast_from_value(0, GraphQLBoolean) == BooleanValueNode(value=False) assert ast_from_value(1, GraphQLBoolean) == BooleanValueNode(value=True) non_null_boolean = GraphQLNonNull(GraphQLBoolean) assert ast_from_value(0, non_null_boolean) == BooleanValueNode(value=False)
def heal_type(type_: GraphQLNamedType) -> GraphQLNamedType: # Unwrap the two known wrapper types if isinstance(type_, GraphQLList): type_ = GraphQLList(heal_type(type_.of_type)) elif isinstance(type_, GraphQLNonNull): type_ = GraphQLNonNull(heal_type(type_.of_type)) elif is_named_type(type_): # If a type annotation on a field or an argument or a union member is # any `GraphQLNamedType` with a `name`, then it must end up identical # to `schema.get_type(name)`, since `schema.type_map` is the source # of truth for all named schema types. named_type = cast(GraphQLNamedType, type_) official_type = schema.get_type(named_type.name) if official_type and named_type != official_type: return official_type return type_
class TestListOfNotNullT_Array_T: # [T!] Array<T> type = GraphQLList(GraphQLNonNull(GraphQLInt)) test_contains_values = check([1, 2], {"data": {"nest": {"test": [1, 2]}}}) test_contains_null = check( [1, None, 2], { "data": {"nest": {"test": None}}, "errors": [ { "locations": [{"column": 10, "line": 1}], "path": ["nest", "test", 1], "message": "Cannot return null for non-nullable field DataType.test.", } ], }, ) test_returns_null = check(None, {"data": {"nest": {"test": None}}})
class TestListOfNotNullT_Array_Promise_T: # [T!] Array<Promise<T>> type = GraphQLList(GraphQLNonNull(GraphQLInt)) test_contains_values = check([resolved(1), resolved(2)], {'data': {'nest': {'test': [1, 2]}}}) test_contains_null = check([resolved(1), resolved(None), resolved(2)], { 'data': {'nest': {'test': None}}, 'errors': [{'locations': [{'column': 10, 'line': 1}], 'path': ['nest', 'test', 1], 'message': 'Cannot return null for non-nullable field DataType.test.'}] }) test_contains_reject = check(lambda: [resolved(1), rejected(Exception('bad')), resolved(2)], { 'data': {'nest': {'test': None}}, 'errors': [{ 'locations': [{'column': 10, 'line': 1}], 'path': ['nest', 'test', 1], 'message': 'bad' }] })
def describe_for_graphql_non_null(): TestNonNull = GraphQLNonNull(GraphQLInt) def returns_non_error_for_non_null_value(): result = _coerce_value(1, TestNonNull) assert expect_value(result) == 1 def returns_an_error_for_undefined_value(): result = _coerce_value(INVALID, TestNonNull) assert expect_errors(result) == [ ("Expected non-nullable type Int! not to be None.", [], INVALID) ] def returns_an_error_for_null_value(): result = _coerce_value(None, TestNonNull) assert expect_errors(result) == [ ("Expected non-nullable type Int! not to be None.", [], None) ]
def rejects_a_union_type_with_non_object_member_types(): # invalid schema cannot be built with Python with raises(TypeError) as exc_info: build_schema( """ type Query { test: BadUnion } type TypeA { field: String } type TypeB { field: String } union BadUnion = | TypeA | String | TypeB """ ) msg = str(exc_info.value) assert msg == "BadUnion types must be GraphQLObjectType objects." bad_union_member_types = [ GraphQLString, GraphQLNonNull(SomeObjectType), GraphQLList(SomeObjectType), SomeInterfaceType, SomeUnionType, SomeEnumType, SomeInputObjectType, ] for member_type in bad_union_member_types: # invalid schema cannot be built with Python with raises(TypeError) as exc_info: schema_with_field_type( GraphQLUnionType("BadUnion", types=[member_type]) ) msg = str(exc_info.value) assert msg == "BadUnion types must be GraphQLObjectType objects."
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)
def global_id_field( type_name: str = None, id_fetcher: Callable[[Any, GraphQLResolveInfo], str] = None) -> GraphQLField: """ Creates the configuration for an id field on a node, using `to_global_id` to construct the ID from the provided typename. The type-specific ID is fetched by calling id_fetcher on the object, or if not provided, by accessing the `id` attribute of the object, or the `id` if the object is a dict. """ def resolve(obj: Any, info: GraphQLResolveInfo, **_args: Any) -> str: type_ = type_name or info.parent_type.name id_ = (id_fetcher(obj, info) if id_fetcher else (obj["id"] if isinstance(obj, dict) else obj.id)) return to_global_id(type_, id_) return GraphQLField(GraphQLNonNull(GraphQLID), description="The ID of an object", resolve=resolve)
def test_prints_string_field_with_non_null_int_arg(): output = print_single_field_schema( GraphQLField( type=GraphQLString, args={"argOne": GraphQLArgument(GraphQLNonNull(GraphQLInt))}, ) ) assert ( output == """ schema { query: Root } type Root { singleField(argOne: Int!): String } """ )
class TestListOfNotNullT_Array_T: # [T!] Array<T> type = GraphQLList(GraphQLNonNull(GraphQLInt)) test_contains_values = check([1, 2], {'data': {'nest': {'test': [1, 2]}}}) test_contains_null = check( [1, None, 2], { 'data': { 'nest': { 'test': None } }, 'errors': [{ 'locations': [{ 'column': 10, 'line': 1 }], 'message': 'Cannot return null for non-nullable field DataType.test.' }] }) test_returns_null = check(None, {'data': {'nest': {'test': None}}})
class Test_NotNullListOfT_Array_Promise_T: # [T]! Promise<Array<T>>> type = GraphQLNonNull(GraphQLList(GraphQLInt)) test_contains_values = check( [resolved(1), resolved(2)], {"data": {"nest": {"test": [1, 2]}}} ) test_contains_null = check( [resolved(1), resolved(None), resolved(2)], {"data": {"nest": {"test": [1, None, 2]}}}, ) test_contains_reject = check( lambda: [resolved(1), rejected(Exception("bad")), resolved(2)], { "data": {"nest": {"test": [1, None, 2]}}, "errors": [ { "locations": [{"column": 10, "line": 1}], "path": ["nest", "test", 1], "message": "bad", } ], }, )
def test_fails_on_a_very_deep_non_null(): schema = GraphQLSchema( query=GraphQLObjectType( name='Query', fields={ 'foo': GraphQLField( GraphQLList(GraphQLList(GraphQLList(GraphQLList( GraphQLList(GraphQLList(GraphQLList(GraphQLList( GraphQLNonNull(GraphQLString) )))) )))) ) } ) ) introspection = graphql(schema, introspection_query) with raises(Exception) as excinfo: build_client_schema(introspection.data) assert str(excinfo.value) == 'Decorated type deeper than introspection query.'
def describe_type_system_list_must_accept_only_types(): types = [ GraphQLString, ScalarType, ObjectType, UnionType, InterfaceType, EnumType, InputObjectType, GraphQLList(GraphQLString), GraphQLNonNull(GraphQLString) ] not_types = [{}, dict, str, object, None] @mark.parametrize('type_', types) def accepts_a_type_as_item_type_of_list(type_): assert GraphQLList(type_) @mark.parametrize('type_', not_types) def rejects_a_non_type_as_item_type_of_list(type_): with raises(TypeError) as exc_info: assert GraphQLList(type_) msg = str(exc_info.value) assert msg == ('Can only create a wrapper for a GraphQLType,' f' but got: {type_}.')
def converts_enum_values_according_to_input_coercion_rules(): test_enum = GraphQLEnumType( "TestColor", { "RED": 1, "GREEN": 2, "BLUE": 3, "NULL": None, "NAN": nan, "NO_CUSTOM_VALUE": Undefined, }, ) assert _value_from("RED", test_enum) == 1 assert _value_from("BLUE", test_enum) == 3 assert _value_from("YELLOW", test_enum) is Undefined assert _value_from("3", test_enum) is Undefined assert _value_from('"BLUE"', test_enum) is Undefined assert _value_from("null", test_enum) is None assert _value_from("NULL", test_enum) is None assert _value_from("NULL", GraphQLNonNull(test_enum)) is None assert isnan(_value_from("NAN", test_enum)) assert _value_from("NO_CUSTOM_VALUE", test_enum) is Undefined
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)
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)
def returns_true_for_required_input_field(): required_field = GraphQLInputField(GraphQLNonNull(GraphQLString)) assert is_required_input_field(required_field) is True
def returns_true_for_wrapped_types(): assert is_type(GraphQLNonNull(GraphQLString)) is True assert_type(GraphQLNonNull(GraphQLString))
def unwraps_deeply_wrapper_types(): assert (get_named_type( GraphQLNonNull(GraphQLList(GraphQLNonNull(ObjectType)))) is ObjectType)
def returns_true_for_required_arguments(): required_arg = GraphQLArgument(GraphQLNonNull(GraphQLString)) assert is_required_argument(required_arg) is True
def unwraps_wrapper_types(): assert get_named_type(GraphQLNonNull(ObjectType)) is ObjectType assert get_named_type(GraphQLList(ObjectType)) is ObjectType
def unwraps_non_null_type(): assert get_nullable_type(GraphQLNonNull(ObjectType)) is ObjectType
def returns_false_for_non_null_types(): assert is_nullable_type(GraphQLNonNull(ObjectType)) is False with raises(TypeError): assert_nullable_type(GraphQLNonNull(ObjectType))
def returns_true_for_list_of_non_null_types(): assert is_nullable_type(GraphQLList( GraphQLNonNull(ObjectType))) is True assert_nullable_type(GraphQLList(GraphQLNonNull(ObjectType)))
def returns_true_for_list_and_non_null_types(): assert is_wrapping_type(GraphQLList(ObjectType)) is True assert_wrapping_type(GraphQLList(ObjectType)) assert is_wrapping_type(GraphQLNonNull(ObjectType)) is True assert_wrapping_type(GraphQLNonNull(ObjectType))