From 072c4a397caad6a8a2e5dc99c450f6e1c7812106 Mon Sep 17 00:00:00 2001 From: Kacppian Date: Fri, 6 Jul 2018 15:59:46 +0530 Subject: [PATCH 1/9] Removed asserts --- graphene/pyutils/version.py | 10 +++++-- graphene/relay/connection.py | 37 +++++++++++++++++--------- graphene/relay/mutation.py | 16 ++++++----- graphene/relay/node.py | 15 +++++++---- graphene/types/argument.py | 10 +++---- graphene/types/base.py | 3 ++- graphene/types/datetime.py | 24 ++++++++++------- graphene/types/dynamic.py | 5 +++- graphene/types/field.py | 24 ++++++++++------- graphene/types/mountedtype.py | 8 +++--- graphene/types/objecttype.py | 12 ++++++--- graphene/types/resolver.py | 3 ++- graphene/types/schema.py | 37 +++++++++++++++++--------- graphene/types/typemap.py | 50 ++++++++++++++++++++++++----------- graphene/types/union.py | 9 ++++--- graphene/types/uuid.py | 8 +++--- graphene/utils/annotate.py | 8 +++--- 17 files changed, 182 insertions(+), 97 deletions(-) diff --git a/graphene/pyutils/version.py b/graphene/pyutils/version.py index f2005442..633f4429 100644 --- a/graphene/pyutils/version.py +++ b/graphene/pyutils/version.py @@ -44,8 +44,14 @@ def get_complete_version(version=None): if version is None: from graphene import VERSION as version else: - assert len(version) == 5 - assert version[3] in ("alpha", "beta", "rc", "final") + if len(version) is not 5: + raise AssertionError( + "Version needs to be 5" + ) + if version[3] not in ('alpha', 'beta', 'rc', 'final'): + raise AssertionError( + "Release version is unkown" + ) return version diff --git a/graphene/relay/connection.py b/graphene/relay/connection.py index f23849f2..65d4dae2 100644 --- a/graphene/relay/connection.py +++ b/graphene/relay/connection.py @@ -46,12 +46,17 @@ class Connection(ObjectType): @classmethod def __init_subclass_with_meta__(cls, node=None, name=None, **options): _meta = ConnectionOptions(cls) - assert node, "You have to provide a node in {}.Meta".format(cls.__name__) - assert issubclass( - node, (Scalar, Enum, ObjectType, Interface, Union, NonNull) - ), ('Received incompatible node "{}" for Connection {}.').format( - node, cls.__name__ - ) + if not node: + raise AssertionError( + "You have to provide a node in {}.Meta" + .format(cls.__name__) + ) + + if not issubclass(node, (Scalar, Enum, ObjectType, Interface, Union, NonNull)): + raise AssertionError( + 'Received incompatible node "{}" for Connection {}.' + .format(node, cls.__name__) + ) base_name = re.sub("Connection$", "", name or cls.__name__) or node._meta.name if not name: @@ -107,9 +112,11 @@ class IterableConnectionField(Field): "Read more: https://github.com/graphql-python/graphene/blob/v2.0.0/UPGRADE-v2.0.md#node-connections" ) - assert issubclass(connection_type, Connection), ( - '{} type have to be a subclass of Connection. Received "{}".' - ).format(self.__class__.__name__, connection_type) + if not issubclass(connection_type, Connection): + raise AssertionError( + '{} type have to be a subclass of Connection. Received "{}".' + .format(self.__class__.__name__, connection_type) + ) return type @classmethod @@ -117,10 +124,14 @@ class IterableConnectionField(Field): if isinstance(resolved, connection_type): return resolved - assert isinstance(resolved, Iterable), ( - "Resolved value from the connection field have to be iterable or instance of {}. " - 'Received "{}"' - ).format(connection_type, resolved) + if not isinstance(resolved, Iterable): + raise AssertionError( + ''' + Resolved value from the connection field have to be iterable or instance of {}. + Received "{}" + ''' + .format(connection_type, resolved) + ) connection = connection_from_list( resolved, args, diff --git a/graphene/relay/mutation.py b/graphene/relay/mutation.py index 1b8b855e..72166317 100644 --- a/graphene/relay/mutation.py +++ b/graphene/relay/mutation.py @@ -18,8 +18,11 @@ class ClientIDMutation(Mutation): input_class = getattr(cls, "Input", None) base_name = re.sub("Payload$", "", name or cls.__name__) - assert not output, "Can't specify any output" - assert not arguments, "Can't specify any arguments" + if output: + raise AssertionError("Can't specify any output") + + if arguments: + raise AssertionError("Can't specify any arguments") bases = (InputObjectType,) if input_class: @@ -42,10 +45,11 @@ class ClientIDMutation(Mutation): ) mutate_and_get_payload = getattr(cls, "mutate_and_get_payload", None) if cls.mutate and cls.mutate.__func__ == ClientIDMutation.mutate.__func__: - assert mutate_and_get_payload, ( - "{name}.mutate_and_get_payload method is required" - " in a ClientIDMutation." - ).format(name=name or cls.__name__) + if not mutate_and_get_payload: + raise AssertionError( + "{name}.mutate_and_get_payload method is required in a ClientIDMutation." + .format(name=name or cls.__name__) + ) if not name: name = "{}Payload".format(base_name) diff --git a/graphene/relay/node.py b/graphene/relay/node.py index d9c4c0f6..6a4348a6 100644 --- a/graphene/relay/node.py +++ b/graphene/relay/node.py @@ -48,8 +48,11 @@ class GlobalID(Field): class NodeField(Field): - def __init__(self, node, type=False, deprecation_reason=None, name=None, **kwargs): - assert issubclass(node, Node), "NodeField can only operate in Nodes" + + def __init__(self, node, type=False, deprecation_reason=None, + name=None, **kwargs): + if not issubclass(node, Node): + raise AssertionError('NodeField can only operate in Nodes') self.node_type = node self.field_type = type @@ -98,9 +101,11 @@ class Node(AbstractNode): return None if only_type: - assert graphene_type == only_type, ("Must receive a {} id.").format( - only_type._meta.name - ) + if graphene_type != only_type: + raise AssertionError( + 'Must receive a {} id.' + .format(only_type._meta.name) + ) # We make sure the ObjectType implements the "Node" interface if cls not in graphene_type._meta.interfaces: diff --git a/graphene/types/argument.py b/graphene/types/argument.py index 9c75bcee..ebcd9caf 100644 --- a/graphene/types/argument.py +++ b/graphene/types/argument.py @@ -73,11 +73,11 @@ def to_arguments(args, extra_args=None): raise ValueError('Unknown argument "{}".'.format(default_name)) arg_name = default_name or arg.name - assert ( - arg_name not in arguments - ), 'More than one Argument have same name "{}".'.format( - arg_name - ) + if arg_name in arguments: + raise AssertionError( + 'More than one Argument have same name "{}".' + .format(arg_name) + ) arguments[arg_name] = arg return arguments diff --git a/graphene/types/base.py b/graphene/types/base.py index aa97ed22..1b4d4034 100644 --- a/graphene/types/base.py +++ b/graphene/types/base.py @@ -31,7 +31,8 @@ class BaseType(SubclassWithMeta): @classmethod def __init_subclass_with_meta__(cls, name=None, description=None, _meta=None): - assert "_meta" not in cls.__dict__, "Can't assign directly meta" + if "_meta" in cls.__dict__: + raise AssertionError("Can't assign meta directly") if not _meta: return _meta.name = name or cls.__name__ diff --git a/graphene/types/datetime.py b/graphene/types/datetime.py index 739032b0..bf294176 100644 --- a/graphene/types/datetime.py +++ b/graphene/types/datetime.py @@ -19,9 +19,11 @@ class Date(Scalar): def serialize(date): if isinstance(date, datetime.datetime): date = date.date() - assert isinstance( - date, datetime.date - ), 'Received not compatible date "{}"'.format(repr(date)) + if not isinstance(date, datetime.date): + raise AssertionError( + 'Received not compatible date "{}"' + .format(repr(date)) + ) return date.isoformat() @classmethod @@ -46,9 +48,11 @@ class DateTime(Scalar): @staticmethod def serialize(dt): - assert isinstance( - dt, (datetime.datetime, datetime.date) - ), 'Received not compatible datetime "{}"'.format(repr(dt)) + if not isinstance(dt, (datetime.datetime, datetime.date)): + raise AssertionError( + 'Received not compatible datetime "{}"' + .format(repr(dt)) + ) return dt.isoformat() @classmethod @@ -73,9 +77,11 @@ class Time(Scalar): @staticmethod def serialize(time): - assert isinstance( - time, datetime.time - ), 'Received not compatible time "{}"'.format(repr(time)) + if not isinstance(time, datetime.time): + raise AssertionError( + 'Received not compatible time "{}"' + .format(repr(time)) + ) return time.isoformat() @classmethod diff --git a/graphene/types/dynamic.py b/graphene/types/dynamic.py index 588c53bb..ef421b49 100644 --- a/graphene/types/dynamic.py +++ b/graphene/types/dynamic.py @@ -12,7 +12,10 @@ class Dynamic(MountedType): def __init__(self, type, with_schema=False, _creation_counter=None): super(Dynamic, self).__init__(_creation_counter=_creation_counter) - assert inspect.isfunction(type) or isinstance(type, partial) + if not (inspect.isfunction(type) or isinstance(type, partial)): + raise AssertionError( + 'type is expected to be a function or an instance of partial' + ) self.type = type self.with_schema = with_schema diff --git a/graphene/types/field.py b/graphene/types/field.py index a1428632..48025913 100644 --- a/graphene/types/field.py +++ b/graphene/types/field.py @@ -34,15 +34,21 @@ class Field(MountedType): **extra_args ): super(Field, self).__init__(_creation_counter=_creation_counter) - assert not args or isinstance(args, Mapping), ( - 'Arguments in a field have to be a mapping, received "{}".' - ).format(args) - assert not ( - source and resolver - ), "A Field cannot have a source and a resolver in at the same time." - assert not callable(default_value), ( - 'The default value can not be a function but received "{}".' - ).format(base_type(default_value)) + + if args and not isinstance(args, Mapping): + raise AssertionError( + 'Arguments in a field have to be a mapping, received "{}".' + .format(args) + ) + if source and resolver: + raise AssertionError( + 'A Field cannot have a source and a resolver in at the same time.' + ) + if callable(default_value): + raise AssertionError( + 'The default value can not be a function but received "{}".' + .format(base_type(default_value)) + ) if required: type = NonNull(type) diff --git a/graphene/types/mountedtype.py b/graphene/types/mountedtype.py index 6d0c8cf8..d6002a72 100644 --- a/graphene/types/mountedtype.py +++ b/graphene/types/mountedtype.py @@ -8,9 +8,11 @@ class MountedType(OrderedType): """ Mount the UnmountedType instance """ - assert isinstance(unmounted, UnmountedType), ("{} can't mount {}").format( - cls.__name__, repr(unmounted) - ) + if not isinstance(unmounted, UnmountedType): + raise AssertionError( + "{} can't mount {}" + .format(cls.__name__, repr(unmounted)) + ) return cls( unmounted.get_type(), diff --git a/graphene/types/objecttype.py b/graphene/types/objecttype.py index be4addb2..d58e5501 100644 --- a/graphene/types/objecttype.py +++ b/graphene/types/objecttype.py @@ -47,10 +47,14 @@ class ObjectType(BaseType): for base in reversed(cls.__mro__): fields.update(yank_fields_from_attrs(base.__dict__, _as=Field)) - assert not (possible_types and cls.is_type_of), ( - "{name}.Meta.possible_types will cause type collision with {name}.is_type_of. " - "Please use one or other." - ).format(name=cls.__name__) + if possible_types and cls.is_type_of: + raise AssertionError( + ''' + {name}.Meta.possible_types will cause type collision with {name}.is_type_of. + Please use one or other. + ''' + .format(name=cls.__name__) + ) if _meta.fields: _meta.fields.update(fields) diff --git a/graphene/types/resolver.py b/graphene/types/resolver.py index 888aba8a..3b04acb6 100644 --- a/graphene/types/resolver.py +++ b/graphene/types/resolver.py @@ -11,7 +11,8 @@ default_resolver = attr_resolver def set_default_resolver(resolver): global default_resolver - assert callable(resolver), "Received non-callable resolver." + if not callable(resolver): + raise AssertionError('Received non-callable resolver.') default_resolver = resolver diff --git a/graphene/types/schema.py b/graphene/types/schema.py index a885c88a..21c90de5 100644 --- a/graphene/types/schema.py +++ b/graphene/types/schema.py @@ -20,9 +20,11 @@ def assert_valid_root_type(_type): return is_graphene_objecttype = inspect.isclass(_type) and issubclass(_type, ObjectType) is_graphql_objecttype = isinstance(_type, GraphQLObjectType) - assert is_graphene_objecttype or is_graphql_objecttype, ( - "Type {} is not a valid ObjectType." - ).format(_type) + if not (is_graphene_objecttype or is_graphql_objecttype): + raise AssertionError( + "Type {} is not a valid ObjectType." + .format(_type) + ) class Schema(GraphQLSchema): @@ -53,11 +55,11 @@ class Schema(GraphQLSchema): if directives is None: directives = [GraphQLIncludeDirective, GraphQLSkipDirective] - assert all( - isinstance(d, GraphQLDirective) for d in directives - ), "Schema directives must be List[GraphQLDirective] if provided but got: {}.".format( - directives - ) + if not all(isinstance(d, GraphQLDirective) for d in directives): + raise AssertionError( + 'Schema directives must be List[GraphQLDirective] if provided but got: {}.' + .format(directives) + ) self._directives = directives self.build_typemap() @@ -79,7 +81,10 @@ class Schema(GraphQLSchema): """ _type = super(Schema, self).get_type(type_name) if _type is None: - raise AttributeError('Type "{}" not found in the Schema'.format(type_name)) + raise AttributeError( + 'Type "{}" not found in the Schema' + .format(type_name) + ) if isinstance(_type, GrapheneGraphQLType): return _type.graphene_type return _type @@ -91,10 +96,16 @@ class Schema(GraphQLSchema): return _type if is_graphene_type(_type): graphql_type = self.get_type(_type._meta.name) - assert graphql_type, "Type {} not found in this schema.".format( - _type._meta.name - ) - assert graphql_type.graphene_type == _type + if not graphql_type: + raise AssertionError( + "Type {} not found in this schema." + .format(_type._meta.name) + ) + if graphql_type.graphene_type != _type: + raise AssertionError( + 'The type {} does not match with the associated graphene type {}.' + .format(_type, graphql_type.graphene_type) + ) return graphql_type raise Exception("{} is not a valid GraphQL type.".format(_type)) diff --git a/graphene/types/typemap.py b/graphene/types/typemap.py index dce04445..f79dae6f 100644 --- a/graphene/types/typemap.py +++ b/graphene/types/typemap.py @@ -60,10 +60,16 @@ def resolve_type(resolve_type_func, map, type_name, root, info): if inspect.isclass(_type) and issubclass(_type, ObjectType): graphql_type = map.get(_type._meta.name) - assert graphql_type, "Can't find type {} in schema".format(_type._meta.name) - assert graphql_type.graphene_type == _type, ( - "The type {} does not match with the associated graphene type {}." - ).format(_type, graphql_type.graphene_type) + if not graphql_type: + raise AssertionError( + "Can't find type {} in schema" + .format(_type._meta.name) + ) + if graphql_type.graphene_type != _type: + raise AssertionError( + 'The type {} does not match with the associated graphene type {}.' + .format(_type, graphql_type.graphene_type) + ) return graphql_type return _type @@ -94,9 +100,11 @@ class TypeMap(GraphQLTypeMap): if type._meta.name in map: _type = map[type._meta.name] if isinstance(_type, GrapheneGraphQLType): - assert _type.graphene_type == type, ( - "Found different types with the same name in the schema: {}, {}." - ).format(_type.graphene_type, type) + if _type.graphene_type is not type: + raise AssertionError( + 'Found different types with the same name in the schema: {}, {}.' + .format(_type.graphene_type, type) + ) return map if issubclass(type, ObjectType): @@ -173,9 +181,11 @@ class TypeMap(GraphQLTypeMap): if type._meta.name in map: _type = map[type._meta.name] if isinstance(_type, GrapheneGraphQLType): - assert _type.graphene_type == type, ( - "Found different types with the same name in the schema: {}, {}." - ).format(_type.graphene_type, type) + if _type.graphene_type != type: + raise AssertionError( + 'Found different types with the same name in the schema: {}, {}.' + .format(_type.graphene_type, type) + ) return _type def interfaces(): @@ -183,7 +193,11 @@ class TypeMap(GraphQLTypeMap): for interface in type._meta.interfaces: self.graphene_reducer(map, interface) internal_type = map[interface._meta.name] - assert internal_type.graphene_type == interface + if internal_type.graphene_type != interface: + raise AssertionError( + 'Found different types with the same name in the schema: {}, {}.' + .format(internal_type.graphene_type, interface) + ) interfaces.append(internal_type) return interfaces @@ -207,9 +221,11 @@ class TypeMap(GraphQLTypeMap): if type._meta.name in map: _type = map[type._meta.name] if isinstance(_type, GrapheneInterfaceType): - assert _type.graphene_type == type, ( - "Found different types with the same name in the schema: {}, {}." - ).format(_type.graphene_type, type) + if _type.graphene_type != type: + raise AssertionError( + 'Found different types with the same name in the schema: {}, {}.' + .format(_type.graphene_type, type) + ) return _type _resolve_type = None @@ -248,7 +264,11 @@ class TypeMap(GraphQLTypeMap): for objecttype in type._meta.types: self.graphene_reducer(map, objecttype) internal_type = map[objecttype._meta.name] - assert internal_type.graphene_type == objecttype + if internal_type.graphql_type != objecttype: + raise AssertionError( + "Found different types with the same name in the schema: {}, {}." + .format(internal_type.graphql_type, objecttype) + ) union_types.append(internal_type) return union_types diff --git a/graphene/types/union.py b/graphene/types/union.py index dc207e8e..b4a7b84e 100644 --- a/graphene/types/union.py +++ b/graphene/types/union.py @@ -23,10 +23,11 @@ class Union(UnmountedType, BaseType): @classmethod def __init_subclass_with_meta__(cls, types=None, **options): - assert ( - isinstance(types, (list, tuple)) and len(types) > 0 - ), "Must provide types for Union {name}.".format(name=cls.__name__) - + if not (isinstance(types, (list, tuple)) and len(types) > 0): + raise AssertionError( + "Must provide types for Union {name}." + .format(name=cls.__name__) + ) _meta = UnionOptions(cls) _meta.types = types super(Union, cls).__init_subclass_with_meta__(_meta=_meta, **options) diff --git a/graphene/types/uuid.py b/graphene/types/uuid.py index abb8f110..d7cff7b7 100644 --- a/graphene/types/uuid.py +++ b/graphene/types/uuid.py @@ -14,9 +14,11 @@ class UUID(Scalar): def serialize(uuid): if isinstance(uuid, str): uuid = _UUID(uuid) - assert isinstance(uuid, _UUID), "Expected UUID instance, received {}".format( - uuid - ) + if not isinstance(uuid, _UUID): + raise AssertionError( + "Expected UUID instance, received {}" + .format(uuid) + ) return str(uuid) @staticmethod diff --git a/graphene/utils/annotate.py b/graphene/utils/annotate.py index 43a26ef6..e63e21d1 100644 --- a/graphene/utils/annotate.py +++ b/graphene/utils/annotate.py @@ -22,9 +22,11 @@ def annotate(_func=None, _trigger_warning=True, **annotations): # We make sure the annotations are valid for key, value in annotations.items(): - assert key in func_signature.parameters, ( - 'The key {key} is not a function parameter in the function "{func_name}".' - ).format(key=key, func_name=func_name(_func)) + if not key in func_signature.parameters: + raise AssertionError( + 'The key {key} is not a function parameter in the function "{func_name}".' + .format(key=key, func_name=func_name(_func)) + ) func_annotations = getattr(_func, "__annotations__", None) if func_annotations is None: From c2e0a4161766c3a19964885a6a655d3bfdc34ebe Mon Sep 17 00:00:00 2001 From: Kacppian Date: Sun, 8 Jul 2018 18:56:43 +0530 Subject: [PATCH 2/9] comparing multiline string --- graphene/types/tests/test_objecttype.py | 13 ++++++++----- graphene/types/typemap.py | 4 ++-- graphene/utils/subclass_with_meta.py | 12 ++++++++---- 3 files changed, 18 insertions(+), 11 deletions(-) diff --git a/graphene/types/tests/test_objecttype.py b/graphene/types/tests/test_objecttype.py index 2acb578f..d2ae4ade 100644 --- a/graphene/types/tests/test_objecttype.py +++ b/graphene/types/tests/test_objecttype.py @@ -7,6 +7,7 @@ from ..scalars import String from ..schema import Schema from ..structures import NonNull from ..unmountedtype import UnmountedType +import re class MyType(Interface): @@ -228,11 +229,13 @@ def test_objecttype_with_possible_types_and_is_type_of_should_raise(): def is_type_of(cls, root, context, info): return False - assert str(excinfo.value) == ( - "MyObjectType.Meta.possible_types will cause type collision with " - "MyObjectType.is_type_of. Please use one or other." - ) - + assertion_message = ''' + MyObjectType.Meta.possible_types will cause type collision with MyObjectType.is_type_of. + Please use one or other. + ''' + space_removed_excinfo = str(excinfo.value).replace(" ", "") + space_removed_assertion_message = assertion_message.replace(" ", "") + assert space_removed_assertion_message == space_removed_excinfo def test_objecttype_no_fields_output(): class User(ObjectType): diff --git a/graphene/types/typemap.py b/graphene/types/typemap.py index f79dae6f..b0aca624 100644 --- a/graphene/types/typemap.py +++ b/graphene/types/typemap.py @@ -264,10 +264,10 @@ class TypeMap(GraphQLTypeMap): for objecttype in type._meta.types: self.graphene_reducer(map, objecttype) internal_type = map[objecttype._meta.name] - if internal_type.graphql_type != objecttype: + if internal_type.graphene_type != objecttype: raise AssertionError( "Found different types with the same name in the schema: {}, {}." - .format(internal_type.graphql_type, objecttype) + .format(internal_type.graphene_type, objecttype) ) union_types.append(internal_type) return union_types diff --git a/graphene/utils/subclass_with_meta.py b/graphene/utils/subclass_with_meta.py index 01fc5375..b6dc0553 100644 --- a/graphene/utils/subclass_with_meta.py +++ b/graphene/utils/subclass_with_meta.py @@ -42,10 +42,14 @@ class SubclassWithMeta(six.with_metaclass(SubclassWithMeta_Meta)): abstract = options.pop("abstract", False) if abstract: - assert not options, ( - "Abstract types can only contain the abstract attribute. " - "Received: abstract, {option_keys}" - ).format(option_keys=", ".join(options.keys())) + if options: + raise AssertionError( + ''' + Abstract types can only contain the abstract attribute. + Received: abstract, {option_keys} + ''' + .format(option_keys=', '.join(options.keys())) + ) else: super_class = super(cls, cls) if hasattr(super_class, "__init_subclass_with_meta__"): From e88b050694c7f9e353ad0e6d94ce05450c21503e Mon Sep 17 00:00:00 2001 From: Kacppian Date: Mon, 9 Jul 2018 14:44:30 +0530 Subject: [PATCH 3/9] minor tweaks --- graphene/pyutils/version.py | 10 +++----- graphene/relay/connection.py | 20 ++++++++------- graphene/relay/mutation.py | 5 ++-- graphene/relay/node.py | 9 +++---- graphene/types/argument.py | 3 +-- graphene/types/datetime.py | 13 +++------- graphene/types/dynamic.py | 2 +- graphene/types/field.py | 10 ++++---- graphene/types/mountedtype.py | 5 ++-- graphene/types/objecttype.py | 7 +++--- graphene/types/resolver.py | 2 +- graphene/types/schema.py | 23 +++++++---------- graphene/types/tests/test_objecttype.py | 6 ++--- graphene/types/typemap.py | 33 ++++++++++++++----------- graphene/types/union.py | 3 +-- graphene/types/uuid.py | 5 +--- graphene/utils/annotate.py | 7 +++--- graphene/utils/subclass_with_meta.py | 7 +++--- 18 files changed, 78 insertions(+), 92 deletions(-) diff --git a/graphene/pyutils/version.py b/graphene/pyutils/version.py index 633f4429..ab177e12 100644 --- a/graphene/pyutils/version.py +++ b/graphene/pyutils/version.py @@ -45,13 +45,9 @@ def get_complete_version(version=None): from graphene import VERSION as version else: if len(version) is not 5: - raise AssertionError( - "Version needs to be 5" - ) - if version[3] not in ('alpha', 'beta', 'rc', 'final'): - raise AssertionError( - "Release version is unkown" - ) + raise AssertionError("Version needs to be 5") + if version[3] not in ("alpha", "beta", "rc", "final"): + raise AssertionError("Release version is unkown") return version diff --git a/graphene/relay/connection.py b/graphene/relay/connection.py index 65d4dae2..3f58fdbf 100644 --- a/graphene/relay/connection.py +++ b/graphene/relay/connection.py @@ -48,14 +48,14 @@ class Connection(ObjectType): _meta = ConnectionOptions(cls) if not node: raise AssertionError( - "You have to provide a node in {}.Meta" - .format(cls.__name__) + "You have to provide a node in {}.Meta".format(cls.__name__) ) if not issubclass(node, (Scalar, Enum, ObjectType, Interface, Union, NonNull)): raise AssertionError( - 'Received incompatible node "{}" for Connection {}.' - .format(node, cls.__name__) + 'Received incompatible node "{}" for Connection {}.'.format( + node, cls.__name__ + ) ) base_name = re.sub("Connection$", "", name or cls.__name__) or node._meta.name @@ -114,8 +114,9 @@ class IterableConnectionField(Field): if not issubclass(connection_type, Connection): raise AssertionError( - '{} type have to be a subclass of Connection. Received "{}".' - .format(self.__class__.__name__, connection_type) + '{} type have to be a subclass of Connection. Received "{}".'.format( + self.__class__.__name__, connection_type + ) ) return type @@ -126,11 +127,12 @@ class IterableConnectionField(Field): if not isinstance(resolved, Iterable): raise AssertionError( - ''' + """ Resolved value from the connection field have to be iterable or instance of {}. Received "{}" - ''' - .format(connection_type, resolved) + """.format( + connection_type, resolved + ) ) connection = connection_from_list( resolved, diff --git a/graphene/relay/mutation.py b/graphene/relay/mutation.py index 72166317..211ee44f 100644 --- a/graphene/relay/mutation.py +++ b/graphene/relay/mutation.py @@ -47,8 +47,9 @@ class ClientIDMutation(Mutation): if cls.mutate and cls.mutate.__func__ == ClientIDMutation.mutate.__func__: if not mutate_and_get_payload: raise AssertionError( - "{name}.mutate_and_get_payload method is required in a ClientIDMutation." - .format(name=name or cls.__name__) + "{name}.mutate_and_get_payload method is required in a ClientIDMutation.".format( + name=name or cls.__name__ + ) ) if not name: diff --git a/graphene/relay/node.py b/graphene/relay/node.py index 6a4348a6..44020ae3 100644 --- a/graphene/relay/node.py +++ b/graphene/relay/node.py @@ -48,11 +48,9 @@ class GlobalID(Field): class NodeField(Field): - - def __init__(self, node, type=False, deprecation_reason=None, - name=None, **kwargs): + def __init__(self, node, type=False, deprecation_reason=None, name=None, **kwargs): if not issubclass(node, Node): - raise AssertionError('NodeField can only operate in Nodes') + raise AssertionError("NodeField can only operate in Nodes") self.node_type = node self.field_type = type @@ -103,8 +101,7 @@ class Node(AbstractNode): if only_type: if graphene_type != only_type: raise AssertionError( - 'Must receive a {} id.' - .format(only_type._meta.name) + "Must receive a {} id.".format(only_type._meta.name) ) # We make sure the ObjectType implements the "Node" interface diff --git a/graphene/types/argument.py b/graphene/types/argument.py index ebcd9caf..326e173d 100644 --- a/graphene/types/argument.py +++ b/graphene/types/argument.py @@ -75,8 +75,7 @@ def to_arguments(args, extra_args=None): arg_name = default_name or arg.name if arg_name in arguments: raise AssertionError( - 'More than one Argument have same name "{}".' - .format(arg_name) + 'More than one Argument have same name "{}".'.format(arg_name) ) arguments[arg_name] = arg diff --git a/graphene/types/datetime.py b/graphene/types/datetime.py index bf294176..3aa38c98 100644 --- a/graphene/types/datetime.py +++ b/graphene/types/datetime.py @@ -20,10 +20,7 @@ class Date(Scalar): if isinstance(date, datetime.datetime): date = date.date() if not isinstance(date, datetime.date): - raise AssertionError( - 'Received not compatible date "{}"' - .format(repr(date)) - ) + raise AssertionError('Received not compatible date "{}"'.format(repr(date))) return date.isoformat() @classmethod @@ -50,8 +47,7 @@ class DateTime(Scalar): def serialize(dt): if not isinstance(dt, (datetime.datetime, datetime.date)): raise AssertionError( - 'Received not compatible datetime "{}"' - .format(repr(dt)) + 'Received not compatible datetime "{}"'.format(repr(dt)) ) return dt.isoformat() @@ -78,10 +74,7 @@ class Time(Scalar): @staticmethod def serialize(time): if not isinstance(time, datetime.time): - raise AssertionError( - 'Received not compatible time "{}"' - .format(repr(time)) - ) + raise AssertionError('Received not compatible time "{}"'.format(repr(time))) return time.isoformat() @classmethod diff --git a/graphene/types/dynamic.py b/graphene/types/dynamic.py index ef421b49..d7747644 100644 --- a/graphene/types/dynamic.py +++ b/graphene/types/dynamic.py @@ -14,7 +14,7 @@ class Dynamic(MountedType): super(Dynamic, self).__init__(_creation_counter=_creation_counter) if not (inspect.isfunction(type) or isinstance(type, partial)): raise AssertionError( - 'type is expected to be a function or an instance of partial' + "type is expected to be a function or an instance of partial" ) self.type = type self.with_schema = with_schema diff --git a/graphene/types/field.py b/graphene/types/field.py index 48025913..a42d131a 100644 --- a/graphene/types/field.py +++ b/graphene/types/field.py @@ -37,17 +37,17 @@ class Field(MountedType): if args and not isinstance(args, Mapping): raise AssertionError( - 'Arguments in a field have to be a mapping, received "{}".' - .format(args) + 'Arguments in a field have to be a mapping, received "{}".'.format(args) ) if source and resolver: raise AssertionError( - 'A Field cannot have a source and a resolver in at the same time.' + "A Field cannot have a source and a resolver in at the same time." ) if callable(default_value): raise AssertionError( - 'The default value can not be a function but received "{}".' - .format(base_type(default_value)) + 'The default value can not be a function but received "{}".'.format( + base_type(default_value) + ) ) if required: diff --git a/graphene/types/mountedtype.py b/graphene/types/mountedtype.py index d6002a72..fc4efb85 100644 --- a/graphene/types/mountedtype.py +++ b/graphene/types/mountedtype.py @@ -10,9 +10,8 @@ class MountedType(OrderedType): """ if not isinstance(unmounted, UnmountedType): raise AssertionError( - "{} can't mount {}" - .format(cls.__name__, repr(unmounted)) - ) + "{} can't mount {}".format(cls.__name__, repr(unmounted)) + ) return cls( unmounted.get_type(), diff --git a/graphene/types/objecttype.py b/graphene/types/objecttype.py index d58e5501..2be97358 100644 --- a/graphene/types/objecttype.py +++ b/graphene/types/objecttype.py @@ -49,11 +49,12 @@ class ObjectType(BaseType): if possible_types and cls.is_type_of: raise AssertionError( - ''' + """ {name}.Meta.possible_types will cause type collision with {name}.is_type_of. Please use one or other. - ''' - .format(name=cls.__name__) + """.format( + name=cls.__name__ + ) ) if _meta.fields: diff --git a/graphene/types/resolver.py b/graphene/types/resolver.py index 3b04acb6..d9151b2a 100644 --- a/graphene/types/resolver.py +++ b/graphene/types/resolver.py @@ -12,7 +12,7 @@ default_resolver = attr_resolver def set_default_resolver(resolver): global default_resolver if not callable(resolver): - raise AssertionError('Received non-callable resolver.') + raise AssertionError("Received non-callable resolver.") default_resolver = resolver diff --git a/graphene/types/schema.py b/graphene/types/schema.py index 21c90de5..9250f86d 100644 --- a/graphene/types/schema.py +++ b/graphene/types/schema.py @@ -21,10 +21,7 @@ def assert_valid_root_type(_type): is_graphene_objecttype = inspect.isclass(_type) and issubclass(_type, ObjectType) is_graphql_objecttype = isinstance(_type, GraphQLObjectType) if not (is_graphene_objecttype or is_graphql_objecttype): - raise AssertionError( - "Type {} is not a valid ObjectType." - .format(_type) - ) + raise AssertionError("Type {} is not a valid ObjectType.".format(_type)) class Schema(GraphQLSchema): @@ -57,8 +54,9 @@ class Schema(GraphQLSchema): if not all(isinstance(d, GraphQLDirective) for d in directives): raise AssertionError( - 'Schema directives must be List[GraphQLDirective] if provided but got: {}.' - .format(directives) + "Schema directives must be List[GraphQLDirective] if provided but got: {}.".format( + directives + ) ) self._directives = directives self.build_typemap() @@ -81,10 +79,7 @@ class Schema(GraphQLSchema): """ _type = super(Schema, self).get_type(type_name) if _type is None: - raise AttributeError( - 'Type "{}" not found in the Schema' - .format(type_name) - ) + raise AttributeError('Type "{}" not found in the Schema'.format(type_name)) if isinstance(_type, GrapheneGraphQLType): return _type.graphene_type return _type @@ -98,13 +93,13 @@ class Schema(GraphQLSchema): graphql_type = self.get_type(_type._meta.name) if not graphql_type: raise AssertionError( - "Type {} not found in this schema." - .format(_type._meta.name) + "Type {} not found in this schema.".format(_type._meta.name) ) if graphql_type.graphene_type != _type: raise AssertionError( - 'The type {} does not match with the associated graphene type {}.' - .format(_type, graphql_type.graphene_type) + "The type {} does not match with the associated graphene type {}.".format( + _type, graphql_type.graphene_type + ) ) return graphql_type raise Exception("{} is not a valid GraphQL type.".format(_type)) diff --git a/graphene/types/tests/test_objecttype.py b/graphene/types/tests/test_objecttype.py index d2ae4ade..d7cdd992 100644 --- a/graphene/types/tests/test_objecttype.py +++ b/graphene/types/tests/test_objecttype.py @@ -7,7 +7,6 @@ from ..scalars import String from ..schema import Schema from ..structures import NonNull from ..unmountedtype import UnmountedType -import re class MyType(Interface): @@ -229,14 +228,15 @@ def test_objecttype_with_possible_types_and_is_type_of_should_raise(): def is_type_of(cls, root, context, info): return False - assertion_message = ''' + assertion_message = """ MyObjectType.Meta.possible_types will cause type collision with MyObjectType.is_type_of. Please use one or other. - ''' + """ space_removed_excinfo = str(excinfo.value).replace(" ", "") space_removed_assertion_message = assertion_message.replace(" ", "") assert space_removed_assertion_message == space_removed_excinfo + def test_objecttype_no_fields_output(): class User(ObjectType): name = String() diff --git a/graphene/types/typemap.py b/graphene/types/typemap.py index b0aca624..f34cd50e 100644 --- a/graphene/types/typemap.py +++ b/graphene/types/typemap.py @@ -62,13 +62,13 @@ def resolve_type(resolve_type_func, map, type_name, root, info): graphql_type = map.get(_type._meta.name) if not graphql_type: raise AssertionError( - "Can't find type {} in schema" - .format(_type._meta.name) + "Can't find type {} in schema".format(_type._meta.name) ) if graphql_type.graphene_type != _type: raise AssertionError( - 'The type {} does not match with the associated graphene type {}.' - .format(_type, graphql_type.graphene_type) + "The type {} does not match with the associated graphene type {}.".format( + _type, graphql_type.graphene_type + ) ) return graphql_type @@ -102,8 +102,9 @@ class TypeMap(GraphQLTypeMap): if isinstance(_type, GrapheneGraphQLType): if _type.graphene_type is not type: raise AssertionError( - 'Found different types with the same name in the schema: {}, {}.' - .format(_type.graphene_type, type) + "Found different types with the same name in the schema: {}, {}.".format( + _type.graphene_type, type + ) ) return map @@ -183,8 +184,9 @@ class TypeMap(GraphQLTypeMap): if isinstance(_type, GrapheneGraphQLType): if _type.graphene_type != type: raise AssertionError( - 'Found different types with the same name in the schema: {}, {}.' - .format(_type.graphene_type, type) + "Found different types with the same name in the schema: {}, {}.".format( + _type.graphene_type, type + ) ) return _type @@ -195,8 +197,9 @@ class TypeMap(GraphQLTypeMap): internal_type = map[interface._meta.name] if internal_type.graphene_type != interface: raise AssertionError( - 'Found different types with the same name in the schema: {}, {}.' - .format(internal_type.graphene_type, interface) + "Found different types with the same name in the schema: {}, {}.".format( + internal_type.graphene_type, interface + ) ) interfaces.append(internal_type) return interfaces @@ -223,8 +226,9 @@ class TypeMap(GraphQLTypeMap): if isinstance(_type, GrapheneInterfaceType): if _type.graphene_type != type: raise AssertionError( - 'Found different types with the same name in the schema: {}, {}.' - .format(_type.graphene_type, type) + "Found different types with the same name in the schema: {}, {}.".format( + _type.graphene_type, type + ) ) return _type @@ -266,8 +270,9 @@ class TypeMap(GraphQLTypeMap): internal_type = map[objecttype._meta.name] if internal_type.graphene_type != objecttype: raise AssertionError( - "Found different types with the same name in the schema: {}, {}." - .format(internal_type.graphene_type, objecttype) + "Found different types with the same name in the schema: {}, {}.".format( + internal_type.graphene_type, objecttype + ) ) union_types.append(internal_type) return union_types diff --git a/graphene/types/union.py b/graphene/types/union.py index b4a7b84e..1c14fd71 100644 --- a/graphene/types/union.py +++ b/graphene/types/union.py @@ -25,8 +25,7 @@ class Union(UnmountedType, BaseType): def __init_subclass_with_meta__(cls, types=None, **options): if not (isinstance(types, (list, tuple)) and len(types) > 0): raise AssertionError( - "Must provide types for Union {name}." - .format(name=cls.__name__) + "Must provide types for Union {name}.".format(name=cls.__name__) ) _meta = UnionOptions(cls) _meta.types = types diff --git a/graphene/types/uuid.py b/graphene/types/uuid.py index d7cff7b7..84089a2d 100644 --- a/graphene/types/uuid.py +++ b/graphene/types/uuid.py @@ -15,10 +15,7 @@ class UUID(Scalar): if isinstance(uuid, str): uuid = _UUID(uuid) if not isinstance(uuid, _UUID): - raise AssertionError( - "Expected UUID instance, received {}" - .format(uuid) - ) + raise AssertionError("Expected UUID instance, received {}".format(uuid)) return str(uuid) @staticmethod diff --git a/graphene/utils/annotate.py b/graphene/utils/annotate.py index e63e21d1..18dcd881 100644 --- a/graphene/utils/annotate.py +++ b/graphene/utils/annotate.py @@ -22,10 +22,11 @@ def annotate(_func=None, _trigger_warning=True, **annotations): # We make sure the annotations are valid for key, value in annotations.items(): - if not key in func_signature.parameters: + if func_signature.parameters.get(key, None) is None: raise AssertionError( - 'The key {key} is not a function parameter in the function "{func_name}".' - .format(key=key, func_name=func_name(_func)) + 'The key {key} is not a function parameter in the function "{func_name}".'.format( + key=key, func_name=func_name(_func) + ) ) func_annotations = getattr(_func, "__annotations__", None) diff --git a/graphene/utils/subclass_with_meta.py b/graphene/utils/subclass_with_meta.py index b6dc0553..2889862f 100644 --- a/graphene/utils/subclass_with_meta.py +++ b/graphene/utils/subclass_with_meta.py @@ -44,11 +44,12 @@ class SubclassWithMeta(six.with_metaclass(SubclassWithMeta_Meta)): if abstract: if options: raise AssertionError( - ''' + """ Abstract types can only contain the abstract attribute. Received: abstract, {option_keys} - ''' - .format(option_keys=', '.join(options.keys())) + """.format( + option_keys=", ".join(options.keys()) + ) ) else: super_class = super(cls, cls) From 11a3fe901a606d3bbb2bcf6cec14a54b77372e92 Mon Sep 17 00:00:00 2001 From: Kacppian Date: Thu, 12 Jul 2018 19:25:25 +0530 Subject: [PATCH 4/9] DRY-ed up --- graphene/pyutils/version.py | 14 +++-- graphene/relay/connection.py | 31 ++++++----- graphene/relay/mutation.py | 4 +- graphene/relay/node.py | 19 ++++--- graphene/types/argument.py | 10 ++-- graphene/types/base.py | 8 ++- graphene/types/datetime.py | 23 +++++--- graphene/types/dynamic.py | 10 ++-- graphene/types/field.py | 29 +++++----- graphene/types/mountedtype.py | 9 +-- graphene/types/objecttype.py | 20 ++++--- graphene/types/resolver.py | 9 ++- graphene/types/schema.py | 41 +++++++------- graphene/types/typemap.py | 83 ++++++++++++++-------------- graphene/types/union.py | 11 ++-- graphene/types/uuid.py | 8 ++- graphene/utils/annotate.py | 13 +++-- graphene/utils/comparison_helper.py | 3 + graphene/utils/subclass_with_meta.py | 13 ++--- 19 files changed, 201 insertions(+), 157 deletions(-) create mode 100644 graphene/utils/comparison_helper.py diff --git a/graphene/pyutils/version.py b/graphene/pyutils/version.py index ab177e12..111e2bc6 100644 --- a/graphene/pyutils/version.py +++ b/graphene/pyutils/version.py @@ -3,6 +3,7 @@ from __future__ import unicode_literals import datetime import os import subprocess +from .comparison_helper import raise_assertion_if_true def get_version(version=None): @@ -44,11 +45,14 @@ def get_complete_version(version=None): if version is None: from graphene import VERSION as version else: - if len(version) is not 5: - raise AssertionError("Version needs to be 5") - if version[3] not in ("alpha", "beta", "rc", "final"): - raise AssertionError("Release version is unkown") - + raise_assertion_if_true( + condition=len(version) is not 5, + message="Version needs to be 5" + ) + raise_assertion_if_true( + condition=version[3] not in ("alpha", "beta", "rc", "final"), + message="Release version is unkown" + ) return version diff --git a/graphene/relay/connection.py b/graphene/relay/connection.py index 3f58fdbf..9993fab8 100644 --- a/graphene/relay/connection.py +++ b/graphene/relay/connection.py @@ -9,6 +9,7 @@ from ..types import Boolean, Enum, Int, Interface, List, NonNull, Scalar, String from ..types.field import Field from ..types.objecttype import ObjectType, ObjectTypeOptions from .node import is_node +from ..utils.comparison_helper import raise_assertion_if_true class PageInfo(ObjectType): @@ -46,16 +47,20 @@ class Connection(ObjectType): @classmethod def __init_subclass_with_meta__(cls, node=None, name=None, **options): _meta = ConnectionOptions(cls) - if not node: - raise AssertionError( - "You have to provide a node in {}.Meta".format(cls.__name__) + + error_message = "You have to provide a node in {}.Meta".format(cls.__name__) + raise_assertion_if_true( + condition=not node, + message=error_message ) - if not issubclass(node, (Scalar, Enum, ObjectType, Interface, Union, NonNull)): - raise AssertionError( - 'Received incompatible node "{}" for Connection {}.'.format( - node, cls.__name__ - ) + error_message = 'Received incompatible node "{}" for Connection {}.'.format( + node, cls.__name__ + ) + condition = not issubclass(node, (Scalar, Enum, ObjectType, Interface, Union, NonNull)) + raise_assertion_if_true( + condition=condition, + message=error_message ) base_name = re.sub("Connection$", "", name or cls.__name__) or node._meta.name @@ -112,11 +117,11 @@ class IterableConnectionField(Field): "Read more: https://github.com/graphql-python/graphene/blob/v2.0.0/UPGRADE-v2.0.md#node-connections" ) - if not issubclass(connection_type, Connection): - raise AssertionError( - '{} type have to be a subclass of Connection. Received "{}".'.format( - self.__class__.__name__, connection_type - ) + error_message = '{} type have to be a subclass of Connection. Received "{}".' + .format(self.__class__.__name__, connection_type) + raise_assertion_if_true( + condition= not issubclass(connection_type, Connection), + message=error_message ) return type diff --git a/graphene/relay/mutation.py b/graphene/relay/mutation.py index 211ee44f..e1734b00 100644 --- a/graphene/relay/mutation.py +++ b/graphene/relay/mutation.py @@ -5,6 +5,7 @@ from promise import Promise, is_thenable from ..types import Field, InputObjectType, String from ..types.mutation import Mutation +from ..utils.comparison_helper import raise_assertion_if_true class ClientIDMutation(Mutation): @@ -18,8 +19,7 @@ class ClientIDMutation(Mutation): input_class = getattr(cls, "Input", None) base_name = re.sub("Payload$", "", name or cls.__name__) - if output: - raise AssertionError("Can't specify any output") + raise_assertion_if_true(condition=output, message="Can't specify any output") if arguments: raise AssertionError("Can't specify any arguments") diff --git a/graphene/relay/node.py b/graphene/relay/node.py index 44020ae3..74cb2fa7 100644 --- a/graphene/relay/node.py +++ b/graphene/relay/node.py @@ -7,6 +7,9 @@ from graphql_relay import from_global_id, to_global_id from ..types import ID, Field, Interface, ObjectType from ..types.interface import InterfaceOptions from ..types.utils import get_type +from ..utils.comparison_helper import raise_assertion_if_true + + def is_node(objecttype): @@ -49,8 +52,10 @@ class GlobalID(Field): class NodeField(Field): def __init__(self, node, type=False, deprecation_reason=None, name=None, **kwargs): - if not issubclass(node, Node): - raise AssertionError("NodeField can only operate in Nodes") + raise_assertion_if_true( + condition= not issubclass(node, Node), + message="NodeField can only operate in Nodes" + ) self.node_type = node self.field_type = type @@ -98,12 +103,10 @@ class Node(AbstractNode): except Exception: return None - if only_type: - if graphene_type != only_type: - raise AssertionError( - "Must receive a {} id.".format(only_type._meta.name) - ) - + raise_assertion_if_true( + condition=only_type and (graphene_type is not only_type), + message="Must receive a {} id.".format(only_type._meta.name) + ) # We make sure the ObjectType implements the "Node" interface if cls not in graphene_type._meta.interfaces: return None diff --git a/graphene/types/argument.py b/graphene/types/argument.py index 326e173d..cf296feb 100644 --- a/graphene/types/argument.py +++ b/graphene/types/argument.py @@ -5,7 +5,7 @@ from .dynamic import Dynamic from .mountedtype import MountedType from .structures import NonNull from .utils import get_type - +from ..utils.comparison_helper import raise_assertion_if_true class Argument(MountedType): def __init__( @@ -73,10 +73,10 @@ def to_arguments(args, extra_args=None): raise ValueError('Unknown argument "{}".'.format(default_name)) arg_name = default_name or arg.name - if arg_name in arguments: - raise AssertionError( - 'More than one Argument have same name "{}".'.format(arg_name) - ) + raise_assertion_if_true( + condition=arg_name in arguments, + message='More than one Argument have same name "{}".'.format(arg_name) + ) arguments[arg_name] = arg return arguments diff --git a/graphene/types/base.py b/graphene/types/base.py index 1b4d4034..462e815e 100644 --- a/graphene/types/base.py +++ b/graphene/types/base.py @@ -1,6 +1,6 @@ from ..utils.subclass_with_meta import SubclassWithMeta from ..utils.trim_docstring import trim_docstring - +from ..utils.comparison_helper import raise_assertion_if_true class BaseOptions(object): name = None # type: str @@ -31,8 +31,10 @@ class BaseType(SubclassWithMeta): @classmethod def __init_subclass_with_meta__(cls, name=None, description=None, _meta=None): - if "_meta" in cls.__dict__: - raise AssertionError("Can't assign meta directly") + raise_assertion_if_true( + condition="_meta" in cls.__dict__, + message="Can't assign meta directly" + ) if not _meta: return _meta.name = name or cls.__name__ diff --git a/graphene/types/datetime.py b/graphene/types/datetime.py index 3aa38c98..4fea4f5d 100644 --- a/graphene/types/datetime.py +++ b/graphene/types/datetime.py @@ -6,7 +6,7 @@ from aniso8601 import parse_date, parse_datetime, parse_time from graphql.language import ast from .scalars import Scalar - +from ..utils.comparison_helper import raise_assertion_if_true class Date(Scalar): """ @@ -19,8 +19,10 @@ class Date(Scalar): def serialize(date): if isinstance(date, datetime.datetime): date = date.date() - if not isinstance(date, datetime.date): - raise AssertionError('Received not compatible date "{}"'.format(repr(date))) + raise_assertion_if_true( + condition=not isinstance(date, datetime.date), + message='Received not compatible date "{}"'.format(repr(date)) + ) return date.isoformat() @classmethod @@ -45,10 +47,11 @@ class DateTime(Scalar): @staticmethod def serialize(dt): - if not isinstance(dt, (datetime.datetime, datetime.date)): - raise AssertionError( - 'Received not compatible datetime "{}"'.format(repr(dt)) - ) + + raise_assertion_if_true( + condition=not isinstance(dt, (datetime.datetime, datetime.date)), + message='Received not compatible datetime "{}"'.format(repr(dt)) + ) return dt.isoformat() @classmethod @@ -73,8 +76,10 @@ class Time(Scalar): @staticmethod def serialize(time): - if not isinstance(time, datetime.time): - raise AssertionError('Received not compatible time "{}"'.format(repr(time))) + raise_assertion_if_true( + condition= not isinstance(time, datetime.time), + message='Received not compatible time "{}"'.format(repr(time)) + ) return time.isoformat() @classmethod diff --git a/graphene/types/dynamic.py b/graphene/types/dynamic.py index d7747644..b7248105 100644 --- a/graphene/types/dynamic.py +++ b/graphene/types/dynamic.py @@ -3,6 +3,8 @@ from functools import partial from .mountedtype import MountedType +from ..utils.comparison_helper import raise_assertion_if_true + class Dynamic(MountedType): """ @@ -12,10 +14,10 @@ class Dynamic(MountedType): def __init__(self, type, with_schema=False, _creation_counter=None): super(Dynamic, self).__init__(_creation_counter=_creation_counter) - if not (inspect.isfunction(type) or isinstance(type, partial)): - raise AssertionError( - "type is expected to be a function or an instance of partial" - ) + raise_assertion_if_true( + condition=not (inspect.isfunction(type) or isinstance(type, partial)), + message="type is expected to be a function or an instance of partial" + ) self.type = type self.with_schema = with_schema diff --git a/graphene/types/field.py b/graphene/types/field.py index a42d131a..8112709e 100644 --- a/graphene/types/field.py +++ b/graphene/types/field.py @@ -7,6 +7,7 @@ from .mountedtype import MountedType from .structures import NonNull from .unmountedtype import UnmountedType from .utils import get_type +from ..utils.comparison_helper import raise_assertion_if_true base_type = type @@ -35,20 +36,20 @@ class Field(MountedType): ): super(Field, self).__init__(_creation_counter=_creation_counter) - if args and not isinstance(args, Mapping): - raise AssertionError( - 'Arguments in a field have to be a mapping, received "{}".'.format(args) - ) - if source and resolver: - raise AssertionError( - "A Field cannot have a source and a resolver in at the same time." - ) - if callable(default_value): - raise AssertionError( - 'The default value can not be a function but received "{}".'.format( - base_type(default_value) - ) - ) + raise_assertion_if_true( + condition=args and not isinstance(args, Mapping), + message='Arguments in a field have to be a mapping, received "{}".'.format(args) + ) + + raise_assertion_if_true( + condition=source and resolver, + message="A Field cannot have a source and a resolver in at the same time." + ) + + raise_assertion_if_true( + condition=callable(default_value), + message='The default value can not be a function but received "{}".'.format(base_type(default_value) + ) if required: type = NonNull(type) diff --git a/graphene/types/mountedtype.py b/graphene/types/mountedtype.py index fc4efb85..385c4c5b 100644 --- a/graphene/types/mountedtype.py +++ b/graphene/types/mountedtype.py @@ -1,6 +1,7 @@ from ..utils.orderedtype import OrderedType from .unmountedtype import UnmountedType +from ..utils.comparison_helper import raise_assertion_if_true class MountedType(OrderedType): @classmethod @@ -8,10 +9,10 @@ class MountedType(OrderedType): """ Mount the UnmountedType instance """ - if not isinstance(unmounted, UnmountedType): - raise AssertionError( - "{} can't mount {}".format(cls.__name__, repr(unmounted)) - ) + raise_assertion_if_true( + condition=not isinstance(unmounted, UnmountedType), + message="{} can't mount {}".format(cls.__name__, repr(unmounted) + ) return cls( unmounted.get_type(), diff --git a/graphene/types/objecttype.py b/graphene/types/objecttype.py index 2be97358..2a9f7871 100644 --- a/graphene/types/objecttype.py +++ b/graphene/types/objecttype.py @@ -5,6 +5,8 @@ from .field import Field from .interface import Interface from .utils import yank_fields_from_attrs +from ..utils.comparison_helper import raise_assertion_if_true + # For static type checking with Mypy MYPY = False if MYPY: @@ -47,15 +49,15 @@ class ObjectType(BaseType): for base in reversed(cls.__mro__): fields.update(yank_fields_from_attrs(base.__dict__, _as=Field)) - if possible_types and cls.is_type_of: - raise AssertionError( - """ - {name}.Meta.possible_types will cause type collision with {name}.is_type_of. - Please use one or other. - """.format( - name=cls.__name__ - ) - ) + error_message = """ + {name}.Meta.possible_types will cause type collision with {name}.is_type_of. + Please use one or other. + """.format(name=cls.__name__) + + raise_assertion_if_true( + condition=possible_types and cls.is_type_of, + message=error_message + ) if _meta.fields: _meta.fields.update(fields) diff --git a/graphene/types/resolver.py b/graphene/types/resolver.py index d9151b2a..ab21d379 100644 --- a/graphene/types/resolver.py +++ b/graphene/types/resolver.py @@ -1,3 +1,5 @@ +from ..utils.comparison_helper import raise_assertion_if_true + def attr_resolver(attname, default_value, root, info, **args): return getattr(root, attname, default_value) @@ -11,8 +13,11 @@ default_resolver = attr_resolver def set_default_resolver(resolver): global default_resolver - if not callable(resolver): - raise AssertionError("Received non-callable resolver.") + + raise_assertion_if_true( + condition=not callable(resolver), + message="Received non-callable resolver." + ) default_resolver = resolver diff --git a/graphene/types/schema.py b/graphene/types/schema.py index 9250f86d..b3886725 100644 --- a/graphene/types/schema.py +++ b/graphene/types/schema.py @@ -13,15 +13,17 @@ from graphql.utils.schema_printer import print_schema from .definitions import GrapheneGraphQLType from .objecttype import ObjectType from .typemap import TypeMap, is_graphene_type - +from ..utils.comparison_helper import raise_assertion_if_true def assert_valid_root_type(_type): if _type is None: return is_graphene_objecttype = inspect.isclass(_type) and issubclass(_type, ObjectType) is_graphql_objecttype = isinstance(_type, GraphQLObjectType) - if not (is_graphene_objecttype or is_graphql_objecttype): - raise AssertionError("Type {} is not a valid ObjectType.".format(_type)) + raise_assertion_if_true( + condition=not (is_graphene_objecttype or is_graphql_objecttype), + message="Type {} is not a valid ObjectType.".format(_type) + ) class Schema(GraphQLSchema): @@ -52,12 +54,10 @@ class Schema(GraphQLSchema): if directives is None: directives = [GraphQLIncludeDirective, GraphQLSkipDirective] - if not all(isinstance(d, GraphQLDirective) for d in directives): - raise AssertionError( - "Schema directives must be List[GraphQLDirective] if provided but got: {}.".format( - directives - ) - ) + raise_assertion_if_true( + condition=not all(isinstance(d, GraphQLDirective) for d in directives), + message="Schema directives must be List[GraphQLDirective] if provided but got: {}.".format(directives) + ) self._directives = directives self.build_typemap() @@ -91,16 +91,19 @@ class Schema(GraphQLSchema): return _type if is_graphene_type(_type): graphql_type = self.get_type(_type._meta.name) - if not graphql_type: - raise AssertionError( - "Type {} not found in this schema.".format(_type._meta.name) - ) - if graphql_type.graphene_type != _type: - raise AssertionError( - "The type {} does not match with the associated graphene type {}.".format( - _type, graphql_type.graphene_type - ) - ) + + raise_assertion_if_true( + condition=not graphql_type, + message="Type {} not found in this schema.".format(_type._meta.name) + ) + + error_message = "The type {} does not match with the associated graphene type {}." + .format(_type, graphql_type.graphene_type) + raise_assertion_if_true( + condition=graphql_type.graphene_type is not _type, + message=error_message + ) + return graphql_type raise Exception("{} is not a valid GraphQL type.".format(_type)) diff --git a/graphene/types/typemap.py b/graphene/types/typemap.py index f34cd50e..c83b3d54 100644 --- a/graphene/types/typemap.py +++ b/graphene/types/typemap.py @@ -40,6 +40,7 @@ from .scalars import ID, Boolean, Float, Int, Scalar, String from .structures import List, NonNull from .union import Union from .utils import get_field_as +from ..utils.comparison_helper import raise_assertion_if_true def is_graphene_type(_type): @@ -60,16 +61,18 @@ def resolve_type(resolve_type_func, map, type_name, root, info): if inspect.isclass(_type) and issubclass(_type, ObjectType): graphql_type = map.get(_type._meta.name) - if not graphql_type: - raise AssertionError( - "Can't find type {} in schema".format(_type._meta.name) - ) - if graphql_type.graphene_type != _type: - raise AssertionError( - "The type {} does not match with the associated graphene type {}.".format( - _type, graphql_type.graphene_type - ) - ) + raise_assertion_if_true( + condition=not graphql_type, + message="Can't find type {} in schema".format(_type._meta.name) + ) + + error_message = "The type {} does not match with the associated graphene type {}." + .format( _type, graphql_type.graphene_type) + raise_assertion_if_true( + condition=graphql_type.graphene_type is not _type, + message=error_message + ) + return graphql_type return _type @@ -100,12 +103,12 @@ class TypeMap(GraphQLTypeMap): if type._meta.name in map: _type = map[type._meta.name] if isinstance(_type, GrapheneGraphQLType): - if _type.graphene_type is not type: - raise AssertionError( - "Found different types with the same name in the schema: {}, {}.".format( - _type.graphene_type, type - ) - ) + error_message = "Found different types with the same name in the schema: {}, {}." + .format(_type.graphene_type, type) + raise_assertion_if_true( + condition=_type.graphene_type is not type, + message=error_message + ) return map if issubclass(type, ObjectType): @@ -182,12 +185,12 @@ class TypeMap(GraphQLTypeMap): if type._meta.name in map: _type = map[type._meta.name] if isinstance(_type, GrapheneGraphQLType): - if _type.graphene_type != type: - raise AssertionError( - "Found different types with the same name in the schema: {}, {}.".format( - _type.graphene_type, type - ) - ) + error_message = "Found different types with the same name in the schema: {}, {}." + .format(_type.graphene_type, type) + raise_assertion_if_true( + condition=_type.graphene_type is not type, + message=error_message + ) return _type def interfaces(): @@ -195,12 +198,12 @@ class TypeMap(GraphQLTypeMap): for interface in type._meta.interfaces: self.graphene_reducer(map, interface) internal_type = map[interface._meta.name] - if internal_type.graphene_type != interface: - raise AssertionError( - "Found different types with the same name in the schema: {}, {}.".format( - internal_type.graphene_type, interface - ) - ) + error_message = "Found different types with the same name in the schema: {}, {}." + .format(internal_type.graphene_type, interface) + raise_assertion_if_true( + condition=internal_type.graphene_type is not interface, + message=error_message + ) interfaces.append(internal_type) return interfaces @@ -224,12 +227,12 @@ class TypeMap(GraphQLTypeMap): if type._meta.name in map: _type = map[type._meta.name] if isinstance(_type, GrapheneInterfaceType): - if _type.graphene_type != type: - raise AssertionError( - "Found different types with the same name in the schema: {}, {}.".format( - _type.graphene_type, type - ) - ) + error_message = "Found different types with the same name in the schema: {}, {}." + .format(_type.graphene_type, type) + raise_assertion_if_true( + condition= _type.graphene_type is not type, + message=error_message + ) return _type _resolve_type = None @@ -268,12 +271,12 @@ class TypeMap(GraphQLTypeMap): for objecttype in type._meta.types: self.graphene_reducer(map, objecttype) internal_type = map[objecttype._meta.name] - if internal_type.graphene_type != objecttype: - raise AssertionError( - "Found different types with the same name in the schema: {}, {}.".format( - internal_type.graphene_type, objecttype - ) - ) + error_message = "Found different types with the same name in the schema: {}, {}." + .format(internal_type.graphene_type, objecttype) + raise_assertion_if_true( + condition=internal_type.graphene_type is not objecttype, + message=error_message + ) union_types.append(internal_type) return union_types diff --git a/graphene/types/union.py b/graphene/types/union.py index 1c14fd71..1c0459ef 100644 --- a/graphene/types/union.py +++ b/graphene/types/union.py @@ -1,6 +1,8 @@ from .base import BaseOptions, BaseType from .unmountedtype import UnmountedType +from ..utils.comparison_helper import raise_assertion_if_true + # For static type checking with Mypy MYPY = False if MYPY: @@ -23,10 +25,11 @@ class Union(UnmountedType, BaseType): @classmethod def __init_subclass_with_meta__(cls, types=None, **options): - if not (isinstance(types, (list, tuple)) and len(types) > 0): - raise AssertionError( - "Must provide types for Union {name}.".format(name=cls.__name__) - ) + + raise_assertion_if_true( + condition=not (isinstance(types, (list, tuple)) and len(types) > 0, + message="Must provide types for Union {name}.".format(name=cls.__name__) + ) _meta = UnionOptions(cls) _meta.types = types super(Union, cls).__init_subclass_with_meta__(_meta=_meta, **options) diff --git a/graphene/types/uuid.py b/graphene/types/uuid.py index 84089a2d..7b944b8a 100644 --- a/graphene/types/uuid.py +++ b/graphene/types/uuid.py @@ -5,7 +5,7 @@ from uuid import UUID as _UUID from graphql.language import ast from .scalars import Scalar - +from ..utils.comparison_helper import raise_assertion_if_true class UUID(Scalar): """UUID""" @@ -14,8 +14,10 @@ class UUID(Scalar): def serialize(uuid): if isinstance(uuid, str): uuid = _UUID(uuid) - if not isinstance(uuid, _UUID): - raise AssertionError("Expected UUID instance, received {}".format(uuid)) + raise_assertion_if_true( + condition=not isinstance(uuid, _UUID), + message="Expected UUID instance, received {}".format(uuid) + ) return str(uuid) @staticmethod diff --git a/graphene/utils/annotate.py b/graphene/utils/annotate.py index 18dcd881..1b6eaa95 100644 --- a/graphene/utils/annotate.py +++ b/graphene/utils/annotate.py @@ -2,6 +2,7 @@ import six from ..pyutils.compat import func_name, signature from .deprecated import warn_deprecation +from .comparison_helper import raise_assertion_if_true def annotate(_func=None, _trigger_warning=True, **annotations): @@ -22,11 +23,13 @@ def annotate(_func=None, _trigger_warning=True, **annotations): # We make sure the annotations are valid for key, value in annotations.items(): - if func_signature.parameters.get(key, None) is None: - raise AssertionError( - 'The key {key} is not a function parameter in the function "{func_name}".'.format( - key=key, func_name=func_name(_func) - ) + func_param = func_signature.parameters.get(key, None) + assertion_message = 'The key {key} is not a function parameter in the function "{func_name}".' + .format(key=key, func_name=func_name(_func) + + raise_assertion_if_true( + condition=func_param is None, + message=assertion_message ) func_annotations = getattr(_func, "__annotations__", None) diff --git a/graphene/utils/comparison_helper.py b/graphene/utils/comparison_helper.py new file mode 100644 index 00000000..14e8ddd2 --- /dev/null +++ b/graphene/utils/comparison_helper.py @@ -0,0 +1,3 @@ +def raise_assertion_if_true(condition=None, message=None): + if condition: + raise AssertionError(message) \ No newline at end of file diff --git a/graphene/utils/subclass_with_meta.py b/graphene/utils/subclass_with_meta.py index 2889862f..56b00a3f 100644 --- a/graphene/utils/subclass_with_meta.py +++ b/graphene/utils/subclass_with_meta.py @@ -41,16 +41,13 @@ class SubclassWithMeta(six.with_metaclass(SubclassWithMeta_Meta)): options = dict(meta_options, **_meta_props) abstract = options.pop("abstract", False) - if abstract: - if options: - raise AssertionError( - """ + error_message = """ Abstract types can only contain the abstract attribute. Received: abstract, {option_keys} - """.format( - option_keys=", ".join(options.keys()) - ) - ) + """.format(option_keys=", ".join(options.keys()) + + raise_assertion_if_true(condition=options and abstract, message=error_message) + else: super_class = super(cls, cls) if hasattr(super_class, "__init_subclass_with_meta__"): From b09e4cb6de65cfa289eb03bed5987e3888506f41 Mon Sep 17 00:00:00 2001 From: Kacppian Date: Thu, 12 Jul 2018 19:32:16 +0530 Subject: [PATCH 5/9] changed function name --- graphene/pyutils/version.py | 8 ++++---- graphene/relay/connection.py | 10 +++++----- graphene/relay/mutation.py | 4 ++-- graphene/relay/node.py | 6 +++--- graphene/types/argument.py | 4 ++-- graphene/types/base.py | 4 ++-- graphene/types/datetime.py | 8 ++++---- graphene/types/dynamic.py | 4 ++-- graphene/types/field.py | 8 ++++---- graphene/types/mountedtype.py | 4 ++-- graphene/types/objecttype.py | 4 ++-- graphene/types/resolver.py | 4 ++-- graphene/types/schema.py | 10 +++++----- graphene/types/typemap.py | 16 ++++++++-------- graphene/types/union.py | 4 ++-- graphene/types/uuid.py | 4 ++-- graphene/utils/annotate.py | 4 ++-- graphene/utils/comparison_helper.py | 2 +- graphene/utils/subclass_with_meta.py | 4 ++-- 19 files changed, 56 insertions(+), 56 deletions(-) diff --git a/graphene/pyutils/version.py b/graphene/pyutils/version.py index 111e2bc6..a922659b 100644 --- a/graphene/pyutils/version.py +++ b/graphene/pyutils/version.py @@ -3,7 +3,7 @@ from __future__ import unicode_literals import datetime import os import subprocess -from .comparison_helper import raise_assertion_if_true +from .comparison_helper import raise_assertion_if def get_version(version=None): @@ -45,11 +45,11 @@ def get_complete_version(version=None): if version is None: from graphene import VERSION as version else: - raise_assertion_if_true( - condition=len(version) is not 5, + raise_assertion_if( + condition=len(version) is not 5, message="Version needs to be 5" ) - raise_assertion_if_true( + raise_assertion_if( condition=version[3] not in ("alpha", "beta", "rc", "final"), message="Release version is unkown" ) diff --git a/graphene/relay/connection.py b/graphene/relay/connection.py index 9993fab8..01dacab3 100644 --- a/graphene/relay/connection.py +++ b/graphene/relay/connection.py @@ -9,7 +9,7 @@ from ..types import Boolean, Enum, Int, Interface, List, NonNull, Scalar, String from ..types.field import Field from ..types.objecttype import ObjectType, ObjectTypeOptions from .node import is_node -from ..utils.comparison_helper import raise_assertion_if_true +from ..utils.comparison_helper import raise_assertion_if class PageInfo(ObjectType): @@ -49,8 +49,8 @@ class Connection(ObjectType): _meta = ConnectionOptions(cls) error_message = "You have to provide a node in {}.Meta".format(cls.__name__) - raise_assertion_if_true( - condition=not node, + raise_assertion_if( + condition=not node, message=error_message ) @@ -58,7 +58,7 @@ class Connection(ObjectType): node, cls.__name__ ) condition = not issubclass(node, (Scalar, Enum, ObjectType, Interface, Union, NonNull)) - raise_assertion_if_true( + raise_assertion_if( condition=condition, message=error_message ) @@ -119,7 +119,7 @@ class IterableConnectionField(Field): error_message = '{} type have to be a subclass of Connection. Received "{}".' .format(self.__class__.__name__, connection_type) - raise_assertion_if_true( + raise_assertion_if( condition= not issubclass(connection_type, Connection), message=error_message ) diff --git a/graphene/relay/mutation.py b/graphene/relay/mutation.py index e1734b00..bad16785 100644 --- a/graphene/relay/mutation.py +++ b/graphene/relay/mutation.py @@ -5,7 +5,7 @@ from promise import Promise, is_thenable from ..types import Field, InputObjectType, String from ..types.mutation import Mutation -from ..utils.comparison_helper import raise_assertion_if_true +from ..utils.comparison_helper import raise_assertion_if class ClientIDMutation(Mutation): @@ -19,7 +19,7 @@ class ClientIDMutation(Mutation): input_class = getattr(cls, "Input", None) base_name = re.sub("Payload$", "", name or cls.__name__) - raise_assertion_if_true(condition=output, message="Can't specify any output") + raise_assertion_if(condition=output, message="Can't specify any output") if arguments: raise AssertionError("Can't specify any arguments") diff --git a/graphene/relay/node.py b/graphene/relay/node.py index 74cb2fa7..5dd494f7 100644 --- a/graphene/relay/node.py +++ b/graphene/relay/node.py @@ -7,7 +7,7 @@ from graphql_relay import from_global_id, to_global_id from ..types import ID, Field, Interface, ObjectType from ..types.interface import InterfaceOptions from ..types.utils import get_type -from ..utils.comparison_helper import raise_assertion_if_true +from ..utils.comparison_helper import raise_assertion_if @@ -52,7 +52,7 @@ class GlobalID(Field): class NodeField(Field): def __init__(self, node, type=False, deprecation_reason=None, name=None, **kwargs): - raise_assertion_if_true( + raise_assertion_if( condition= not issubclass(node, Node), message="NodeField can only operate in Nodes" ) @@ -103,7 +103,7 @@ class Node(AbstractNode): except Exception: return None - raise_assertion_if_true( + raise_assertion_if( condition=only_type and (graphene_type is not only_type), message="Must receive a {} id.".format(only_type._meta.name) ) diff --git a/graphene/types/argument.py b/graphene/types/argument.py index cf296feb..46ff62e7 100644 --- a/graphene/types/argument.py +++ b/graphene/types/argument.py @@ -5,7 +5,7 @@ from .dynamic import Dynamic from .mountedtype import MountedType from .structures import NonNull from .utils import get_type -from ..utils.comparison_helper import raise_assertion_if_true +from ..utils.comparison_helper import raise_assertion_if class Argument(MountedType): def __init__( @@ -73,7 +73,7 @@ def to_arguments(args, extra_args=None): raise ValueError('Unknown argument "{}".'.format(default_name)) arg_name = default_name or arg.name - raise_assertion_if_true( + raise_assertion_if( condition=arg_name in arguments, message='More than one Argument have same name "{}".'.format(arg_name) ) diff --git a/graphene/types/base.py b/graphene/types/base.py index 462e815e..86321a60 100644 --- a/graphene/types/base.py +++ b/graphene/types/base.py @@ -1,6 +1,6 @@ from ..utils.subclass_with_meta import SubclassWithMeta from ..utils.trim_docstring import trim_docstring -from ..utils.comparison_helper import raise_assertion_if_true +from ..utils.comparison_helper import raise_assertion_if class BaseOptions(object): name = None # type: str @@ -31,7 +31,7 @@ class BaseType(SubclassWithMeta): @classmethod def __init_subclass_with_meta__(cls, name=None, description=None, _meta=None): - raise_assertion_if_true( + raise_assertion_if( condition="_meta" in cls.__dict__, message="Can't assign meta directly" ) diff --git a/graphene/types/datetime.py b/graphene/types/datetime.py index 4fea4f5d..03e1bf17 100644 --- a/graphene/types/datetime.py +++ b/graphene/types/datetime.py @@ -6,7 +6,7 @@ from aniso8601 import parse_date, parse_datetime, parse_time from graphql.language import ast from .scalars import Scalar -from ..utils.comparison_helper import raise_assertion_if_true +from ..utils.comparison_helper import raise_assertion_if class Date(Scalar): """ @@ -19,7 +19,7 @@ class Date(Scalar): def serialize(date): if isinstance(date, datetime.datetime): date = date.date() - raise_assertion_if_true( + raise_assertion_if( condition=not isinstance(date, datetime.date), message='Received not compatible date "{}"'.format(repr(date)) ) @@ -48,7 +48,7 @@ class DateTime(Scalar): @staticmethod def serialize(dt): - raise_assertion_if_true( + raise_assertion_if( condition=not isinstance(dt, (datetime.datetime, datetime.date)), message='Received not compatible datetime "{}"'.format(repr(dt)) ) @@ -76,7 +76,7 @@ class Time(Scalar): @staticmethod def serialize(time): - raise_assertion_if_true( + raise_assertion_if( condition= not isinstance(time, datetime.time), message='Received not compatible time "{}"'.format(repr(time)) ) diff --git a/graphene/types/dynamic.py b/graphene/types/dynamic.py index b7248105..dd279600 100644 --- a/graphene/types/dynamic.py +++ b/graphene/types/dynamic.py @@ -3,7 +3,7 @@ from functools import partial from .mountedtype import MountedType -from ..utils.comparison_helper import raise_assertion_if_true +from ..utils.comparison_helper import raise_assertion_if class Dynamic(MountedType): @@ -14,7 +14,7 @@ class Dynamic(MountedType): def __init__(self, type, with_schema=False, _creation_counter=None): super(Dynamic, self).__init__(_creation_counter=_creation_counter) - raise_assertion_if_true( + raise_assertion_if( condition=not (inspect.isfunction(type) or isinstance(type, partial)), message="type is expected to be a function or an instance of partial" ) diff --git a/graphene/types/field.py b/graphene/types/field.py index 8112709e..683c70d1 100644 --- a/graphene/types/field.py +++ b/graphene/types/field.py @@ -7,7 +7,7 @@ from .mountedtype import MountedType from .structures import NonNull from .unmountedtype import UnmountedType from .utils import get_type -from ..utils.comparison_helper import raise_assertion_if_true +from ..utils.comparison_helper import raise_assertion_if base_type = type @@ -36,17 +36,17 @@ class Field(MountedType): ): super(Field, self).__init__(_creation_counter=_creation_counter) - raise_assertion_if_true( + raise_assertion_if( condition=args and not isinstance(args, Mapping), message='Arguments in a field have to be a mapping, received "{}".'.format(args) ) - raise_assertion_if_true( + raise_assertion_if( condition=source and resolver, message="A Field cannot have a source and a resolver in at the same time." ) - raise_assertion_if_true( + raise_assertion_if( condition=callable(default_value), message='The default value can not be a function but received "{}".'.format(base_type(default_value) ) diff --git a/graphene/types/mountedtype.py b/graphene/types/mountedtype.py index 385c4c5b..49b887cf 100644 --- a/graphene/types/mountedtype.py +++ b/graphene/types/mountedtype.py @@ -1,7 +1,7 @@ from ..utils.orderedtype import OrderedType from .unmountedtype import UnmountedType -from ..utils.comparison_helper import raise_assertion_if_true +from ..utils.comparison_helper import raise_assertion_if class MountedType(OrderedType): @classmethod @@ -9,7 +9,7 @@ class MountedType(OrderedType): """ Mount the UnmountedType instance """ - raise_assertion_if_true( + raise_assertion_if( condition=not isinstance(unmounted, UnmountedType), message="{} can't mount {}".format(cls.__name__, repr(unmounted) ) diff --git a/graphene/types/objecttype.py b/graphene/types/objecttype.py index 2a9f7871..847c83f6 100644 --- a/graphene/types/objecttype.py +++ b/graphene/types/objecttype.py @@ -5,7 +5,7 @@ from .field import Field from .interface import Interface from .utils import yank_fields_from_attrs -from ..utils.comparison_helper import raise_assertion_if_true +from ..utils.comparison_helper import raise_assertion_if # For static type checking with Mypy MYPY = False @@ -54,7 +54,7 @@ class ObjectType(BaseType): Please use one or other. """.format(name=cls.__name__) - raise_assertion_if_true( + raise_assertion_if( condition=possible_types and cls.is_type_of, message=error_message ) diff --git a/graphene/types/resolver.py b/graphene/types/resolver.py index ab21d379..a050b17e 100644 --- a/graphene/types/resolver.py +++ b/graphene/types/resolver.py @@ -1,4 +1,4 @@ -from ..utils.comparison_helper import raise_assertion_if_true +from ..utils.comparison_helper import raise_assertion_if def attr_resolver(attname, default_value, root, info, **args): return getattr(root, attname, default_value) @@ -14,7 +14,7 @@ default_resolver = attr_resolver def set_default_resolver(resolver): global default_resolver - raise_assertion_if_true( + raise_assertion_if( condition=not callable(resolver), message="Received non-callable resolver." ) diff --git a/graphene/types/schema.py b/graphene/types/schema.py index b3886725..b106ad36 100644 --- a/graphene/types/schema.py +++ b/graphene/types/schema.py @@ -13,14 +13,14 @@ from graphql.utils.schema_printer import print_schema from .definitions import GrapheneGraphQLType from .objecttype import ObjectType from .typemap import TypeMap, is_graphene_type -from ..utils.comparison_helper import raise_assertion_if_true +from ..utils.comparison_helper import raise_assertion_if def assert_valid_root_type(_type): if _type is None: return is_graphene_objecttype = inspect.isclass(_type) and issubclass(_type, ObjectType) is_graphql_objecttype = isinstance(_type, GraphQLObjectType) - raise_assertion_if_true( + raise_assertion_if( condition=not (is_graphene_objecttype or is_graphql_objecttype), message="Type {} is not a valid ObjectType.".format(_type) ) @@ -54,7 +54,7 @@ class Schema(GraphQLSchema): if directives is None: directives = [GraphQLIncludeDirective, GraphQLSkipDirective] - raise_assertion_if_true( + raise_assertion_if( condition=not all(isinstance(d, GraphQLDirective) for d in directives), message="Schema directives must be List[GraphQLDirective] if provided but got: {}.".format(directives) ) @@ -92,14 +92,14 @@ class Schema(GraphQLSchema): if is_graphene_type(_type): graphql_type = self.get_type(_type._meta.name) - raise_assertion_if_true( + raise_assertion_if( condition=not graphql_type, message="Type {} not found in this schema.".format(_type._meta.name) ) error_message = "The type {} does not match with the associated graphene type {}." .format(_type, graphql_type.graphene_type) - raise_assertion_if_true( + raise_assertion_if( condition=graphql_type.graphene_type is not _type, message=error_message ) diff --git a/graphene/types/typemap.py b/graphene/types/typemap.py index c83b3d54..72044877 100644 --- a/graphene/types/typemap.py +++ b/graphene/types/typemap.py @@ -40,7 +40,7 @@ from .scalars import ID, Boolean, Float, Int, Scalar, String from .structures import List, NonNull from .union import Union from .utils import get_field_as -from ..utils.comparison_helper import raise_assertion_if_true +from ..utils.comparison_helper import raise_assertion_if def is_graphene_type(_type): @@ -61,14 +61,14 @@ def resolve_type(resolve_type_func, map, type_name, root, info): if inspect.isclass(_type) and issubclass(_type, ObjectType): graphql_type = map.get(_type._meta.name) - raise_assertion_if_true( + raise_assertion_if( condition=not graphql_type, message="Can't find type {} in schema".format(_type._meta.name) ) error_message = "The type {} does not match with the associated graphene type {}." .format( _type, graphql_type.graphene_type) - raise_assertion_if_true( + raise_assertion_if( condition=graphql_type.graphene_type is not _type, message=error_message ) @@ -105,7 +105,7 @@ class TypeMap(GraphQLTypeMap): if isinstance(_type, GrapheneGraphQLType): error_message = "Found different types with the same name in the schema: {}, {}." .format(_type.graphene_type, type) - raise_assertion_if_true( + raise_assertion_if( condition=_type.graphene_type is not type, message=error_message ) @@ -187,7 +187,7 @@ class TypeMap(GraphQLTypeMap): if isinstance(_type, GrapheneGraphQLType): error_message = "Found different types with the same name in the schema: {}, {}." .format(_type.graphene_type, type) - raise_assertion_if_true( + raise_assertion_if( condition=_type.graphene_type is not type, message=error_message ) @@ -200,7 +200,7 @@ class TypeMap(GraphQLTypeMap): internal_type = map[interface._meta.name] error_message = "Found different types with the same name in the schema: {}, {}." .format(internal_type.graphene_type, interface) - raise_assertion_if_true( + raise_assertion_if( condition=internal_type.graphene_type is not interface, message=error_message ) @@ -229,7 +229,7 @@ class TypeMap(GraphQLTypeMap): if isinstance(_type, GrapheneInterfaceType): error_message = "Found different types with the same name in the schema: {}, {}." .format(_type.graphene_type, type) - raise_assertion_if_true( + raise_assertion_if( condition= _type.graphene_type is not type, message=error_message ) @@ -273,7 +273,7 @@ class TypeMap(GraphQLTypeMap): internal_type = map[objecttype._meta.name] error_message = "Found different types with the same name in the schema: {}, {}." .format(internal_type.graphene_type, objecttype) - raise_assertion_if_true( + raise_assertion_if( condition=internal_type.graphene_type is not objecttype, message=error_message ) diff --git a/graphene/types/union.py b/graphene/types/union.py index 1c0459ef..0122382e 100644 --- a/graphene/types/union.py +++ b/graphene/types/union.py @@ -1,7 +1,7 @@ from .base import BaseOptions, BaseType from .unmountedtype import UnmountedType -from ..utils.comparison_helper import raise_assertion_if_true +from ..utils.comparison_helper import raise_assertion_if # For static type checking with Mypy MYPY = False @@ -26,7 +26,7 @@ class Union(UnmountedType, BaseType): @classmethod def __init_subclass_with_meta__(cls, types=None, **options): - raise_assertion_if_true( + raise_assertion_if( condition=not (isinstance(types, (list, tuple)) and len(types) > 0, message="Must provide types for Union {name}.".format(name=cls.__name__) ) diff --git a/graphene/types/uuid.py b/graphene/types/uuid.py index 7b944b8a..1f06cbf9 100644 --- a/graphene/types/uuid.py +++ b/graphene/types/uuid.py @@ -5,7 +5,7 @@ from uuid import UUID as _UUID from graphql.language import ast from .scalars import Scalar -from ..utils.comparison_helper import raise_assertion_if_true +from ..utils.comparison_helper import raise_assertion_if class UUID(Scalar): """UUID""" @@ -14,7 +14,7 @@ class UUID(Scalar): def serialize(uuid): if isinstance(uuid, str): uuid = _UUID(uuid) - raise_assertion_if_true( + raise_assertion_if( condition=not isinstance(uuid, _UUID), message="Expected UUID instance, received {}".format(uuid) ) diff --git a/graphene/utils/annotate.py b/graphene/utils/annotate.py index 1b6eaa95..39b91eeb 100644 --- a/graphene/utils/annotate.py +++ b/graphene/utils/annotate.py @@ -2,7 +2,7 @@ import six from ..pyutils.compat import func_name, signature from .deprecated import warn_deprecation -from .comparison_helper import raise_assertion_if_true +from .comparison_helper import raise_assertion_if def annotate(_func=None, _trigger_warning=True, **annotations): @@ -27,7 +27,7 @@ def annotate(_func=None, _trigger_warning=True, **annotations): assertion_message = 'The key {key} is not a function parameter in the function "{func_name}".' .format(key=key, func_name=func_name(_func) - raise_assertion_if_true( + raise_assertion_if( condition=func_param is None, message=assertion_message ) diff --git a/graphene/utils/comparison_helper.py b/graphene/utils/comparison_helper.py index 14e8ddd2..4a087a7c 100644 --- a/graphene/utils/comparison_helper.py +++ b/graphene/utils/comparison_helper.py @@ -1,3 +1,3 @@ -def raise_assertion_if_true(condition=None, message=None): +def raise_assertion_if(condition=None, message=None): if condition: raise AssertionError(message) \ No newline at end of file diff --git a/graphene/utils/subclass_with_meta.py b/graphene/utils/subclass_with_meta.py index 56b00a3f..0546dc08 100644 --- a/graphene/utils/subclass_with_meta.py +++ b/graphene/utils/subclass_with_meta.py @@ -44,9 +44,9 @@ class SubclassWithMeta(six.with_metaclass(SubclassWithMeta_Meta)): error_message = """ Abstract types can only contain the abstract attribute. Received: abstract, {option_keys} - """.format(option_keys=", ".join(options.keys()) + """.format(option_keys=", ".join(options.keys()) - raise_assertion_if_true(condition=options and abstract, message=error_message) + raise_assertion_if(condition=options and abstract, message=error_message) else: super_class = super(cls, cls) From d4498c323265e9b08d28c952d151166dfe017cb0 Mon Sep 17 00:00:00 2001 From: Kacppian Date: Tue, 17 Jul 2018 22:58:06 +0530 Subject: [PATCH 6/9] reverting failing tests --- graphene/pyutils/version.py | 16 +++--- graphene/relay/connection.py | 31 +++++------ graphene/relay/mutation.py | 4 +- graphene/relay/node.py | 19 +++---- graphene/types/argument.py | 9 ++- graphene/types/base.py | 7 +-- graphene/types/datetime.py | 22 +++----- graphene/types/dynamic.py | 10 ++-- graphene/types/field.py | 29 +++++----- graphene/types/mountedtype.py | 9 ++- graphene/types/objecttype.py | 20 +++---- graphene/types/resolver.py | 9 +-- graphene/types/schema.py | 40 ++++++-------- graphene/types/typemap.py | 83 ++++++++++++++-------------- graphene/types/union.py | 11 ++-- graphene/types/uuid.py | 7 +-- graphene/utils/annotate.py | 13 ++--- graphene/utils/subclass_with_meta.py | 13 +++-- 18 files changed, 155 insertions(+), 197 deletions(-) diff --git a/graphene/pyutils/version.py b/graphene/pyutils/version.py index a922659b..9d33209f 100644 --- a/graphene/pyutils/version.py +++ b/graphene/pyutils/version.py @@ -3,7 +3,10 @@ from __future__ import unicode_literals import datetime import os import subprocess +<<<<<<< HEAD from .comparison_helper import raise_assertion_if +======= +>>>>>>> parent of 41dcbdc... DRY-ed up def get_version(version=None): @@ -45,14 +48,11 @@ def get_complete_version(version=None): if version is None: from graphene import VERSION as version else: - raise_assertion_if( - condition=len(version) is not 5, - message="Version needs to be 5" - ) - raise_assertion_if( - condition=version[3] not in ("alpha", "beta", "rc", "final"), - message="Release version is unkown" - ) + if len(version) is not 5: + raise AssertionError("Version needs to be 5") + if version[3] not in ("alpha", "beta", "rc", "final"): + raise AssertionError("Release version is unkown") + return version diff --git a/graphene/relay/connection.py b/graphene/relay/connection.py index 01dacab3..3f58fdbf 100644 --- a/graphene/relay/connection.py +++ b/graphene/relay/connection.py @@ -9,7 +9,6 @@ from ..types import Boolean, Enum, Int, Interface, List, NonNull, Scalar, String from ..types.field import Field from ..types.objecttype import ObjectType, ObjectTypeOptions from .node import is_node -from ..utils.comparison_helper import raise_assertion_if class PageInfo(ObjectType): @@ -47,20 +46,16 @@ class Connection(ObjectType): @classmethod def __init_subclass_with_meta__(cls, node=None, name=None, **options): _meta = ConnectionOptions(cls) - - error_message = "You have to provide a node in {}.Meta".format(cls.__name__) - raise_assertion_if( - condition=not node, - message=error_message + if not node: + raise AssertionError( + "You have to provide a node in {}.Meta".format(cls.__name__) ) - error_message = 'Received incompatible node "{}" for Connection {}.'.format( - node, cls.__name__ - ) - condition = not issubclass(node, (Scalar, Enum, ObjectType, Interface, Union, NonNull)) - raise_assertion_if( - condition=condition, - message=error_message + if not issubclass(node, (Scalar, Enum, ObjectType, Interface, Union, NonNull)): + raise AssertionError( + 'Received incompatible node "{}" for Connection {}.'.format( + node, cls.__name__ + ) ) base_name = re.sub("Connection$", "", name or cls.__name__) or node._meta.name @@ -117,11 +112,11 @@ class IterableConnectionField(Field): "Read more: https://github.com/graphql-python/graphene/blob/v2.0.0/UPGRADE-v2.0.md#node-connections" ) - error_message = '{} type have to be a subclass of Connection. Received "{}".' - .format(self.__class__.__name__, connection_type) - raise_assertion_if( - condition= not issubclass(connection_type, Connection), - message=error_message + if not issubclass(connection_type, Connection): + raise AssertionError( + '{} type have to be a subclass of Connection. Received "{}".'.format( + self.__class__.__name__, connection_type + ) ) return type diff --git a/graphene/relay/mutation.py b/graphene/relay/mutation.py index bad16785..211ee44f 100644 --- a/graphene/relay/mutation.py +++ b/graphene/relay/mutation.py @@ -5,7 +5,6 @@ from promise import Promise, is_thenable from ..types import Field, InputObjectType, String from ..types.mutation import Mutation -from ..utils.comparison_helper import raise_assertion_if class ClientIDMutation(Mutation): @@ -19,7 +18,8 @@ class ClientIDMutation(Mutation): input_class = getattr(cls, "Input", None) base_name = re.sub("Payload$", "", name or cls.__name__) - raise_assertion_if(condition=output, message="Can't specify any output") + if output: + raise AssertionError("Can't specify any output") if arguments: raise AssertionError("Can't specify any arguments") diff --git a/graphene/relay/node.py b/graphene/relay/node.py index 5dd494f7..44020ae3 100644 --- a/graphene/relay/node.py +++ b/graphene/relay/node.py @@ -7,9 +7,6 @@ from graphql_relay import from_global_id, to_global_id from ..types import ID, Field, Interface, ObjectType from ..types.interface import InterfaceOptions from ..types.utils import get_type -from ..utils.comparison_helper import raise_assertion_if - - def is_node(objecttype): @@ -52,10 +49,8 @@ class GlobalID(Field): class NodeField(Field): def __init__(self, node, type=False, deprecation_reason=None, name=None, **kwargs): - raise_assertion_if( - condition= not issubclass(node, Node), - message="NodeField can only operate in Nodes" - ) + if not issubclass(node, Node): + raise AssertionError("NodeField can only operate in Nodes") self.node_type = node self.field_type = type @@ -103,10 +98,12 @@ class Node(AbstractNode): except Exception: return None - raise_assertion_if( - condition=only_type and (graphene_type is not only_type), - message="Must receive a {} id.".format(only_type._meta.name) - ) + if only_type: + if graphene_type != only_type: + raise AssertionError( + "Must receive a {} id.".format(only_type._meta.name) + ) + # We make sure the ObjectType implements the "Node" interface if cls not in graphene_type._meta.interfaces: return None diff --git a/graphene/types/argument.py b/graphene/types/argument.py index 46ff62e7..97ff3b27 100644 --- a/graphene/types/argument.py +++ b/graphene/types/argument.py @@ -5,7 +5,6 @@ from .dynamic import Dynamic from .mountedtype import MountedType from .structures import NonNull from .utils import get_type -from ..utils.comparison_helper import raise_assertion_if class Argument(MountedType): def __init__( @@ -73,10 +72,10 @@ def to_arguments(args, extra_args=None): raise ValueError('Unknown argument "{}".'.format(default_name)) arg_name = default_name or arg.name - raise_assertion_if( - condition=arg_name in arguments, - message='More than one Argument have same name "{}".'.format(arg_name) - ) + if arg_name in arguments: + raise AssertionError( + 'More than one Argument have same name "{}".'.format(arg_name) + ) arguments[arg_name] = arg return arguments diff --git a/graphene/types/base.py b/graphene/types/base.py index 86321a60..6c71e599 100644 --- a/graphene/types/base.py +++ b/graphene/types/base.py @@ -1,6 +1,5 @@ from ..utils.subclass_with_meta import SubclassWithMeta from ..utils.trim_docstring import trim_docstring -from ..utils.comparison_helper import raise_assertion_if class BaseOptions(object): name = None # type: str @@ -31,10 +30,8 @@ class BaseType(SubclassWithMeta): @classmethod def __init_subclass_with_meta__(cls, name=None, description=None, _meta=None): - raise_assertion_if( - condition="_meta" in cls.__dict__, - message="Can't assign meta directly" - ) + if "_meta" in cls.__dict__: + raise AssertionError("Can't assign meta directly") if not _meta: return _meta.name = name or cls.__name__ diff --git a/graphene/types/datetime.py b/graphene/types/datetime.py index 03e1bf17..724bf31f 100644 --- a/graphene/types/datetime.py +++ b/graphene/types/datetime.py @@ -6,7 +6,6 @@ from aniso8601 import parse_date, parse_datetime, parse_time from graphql.language import ast from .scalars import Scalar -from ..utils.comparison_helper import raise_assertion_if class Date(Scalar): """ @@ -19,10 +18,8 @@ class Date(Scalar): def serialize(date): if isinstance(date, datetime.datetime): date = date.date() - raise_assertion_if( - condition=not isinstance(date, datetime.date), - message='Received not compatible date "{}"'.format(repr(date)) - ) + if not isinstance(date, datetime.date): + raise AssertionError('Received not compatible date "{}"'.format(repr(date))) return date.isoformat() @classmethod @@ -47,11 +44,10 @@ class DateTime(Scalar): @staticmethod def serialize(dt): - - raise_assertion_if( - condition=not isinstance(dt, (datetime.datetime, datetime.date)), - message='Received not compatible datetime "{}"'.format(repr(dt)) - ) + if not isinstance(dt, (datetime.datetime, datetime.date)): + raise AssertionError( + 'Received not compatible datetime "{}"'.format(repr(dt)) + ) return dt.isoformat() @classmethod @@ -76,10 +72,8 @@ class Time(Scalar): @staticmethod def serialize(time): - raise_assertion_if( - condition= not isinstance(time, datetime.time), - message='Received not compatible time "{}"'.format(repr(time)) - ) + if not isinstance(time, datetime.time): + raise AssertionError('Received not compatible time "{}"'.format(repr(time))) return time.isoformat() @classmethod diff --git a/graphene/types/dynamic.py b/graphene/types/dynamic.py index dd279600..d7747644 100644 --- a/graphene/types/dynamic.py +++ b/graphene/types/dynamic.py @@ -3,8 +3,6 @@ from functools import partial from .mountedtype import MountedType -from ..utils.comparison_helper import raise_assertion_if - class Dynamic(MountedType): """ @@ -14,10 +12,10 @@ class Dynamic(MountedType): def __init__(self, type, with_schema=False, _creation_counter=None): super(Dynamic, self).__init__(_creation_counter=_creation_counter) - raise_assertion_if( - condition=not (inspect.isfunction(type) or isinstance(type, partial)), - message="type is expected to be a function or an instance of partial" - ) + if not (inspect.isfunction(type) or isinstance(type, partial)): + raise AssertionError( + "type is expected to be a function or an instance of partial" + ) self.type = type self.with_schema = with_schema diff --git a/graphene/types/field.py b/graphene/types/field.py index 683c70d1..a42d131a 100644 --- a/graphene/types/field.py +++ b/graphene/types/field.py @@ -7,7 +7,6 @@ from .mountedtype import MountedType from .structures import NonNull from .unmountedtype import UnmountedType from .utils import get_type -from ..utils.comparison_helper import raise_assertion_if base_type = type @@ -36,20 +35,20 @@ class Field(MountedType): ): super(Field, self).__init__(_creation_counter=_creation_counter) - raise_assertion_if( - condition=args and not isinstance(args, Mapping), - message='Arguments in a field have to be a mapping, received "{}".'.format(args) - ) - - raise_assertion_if( - condition=source and resolver, - message="A Field cannot have a source and a resolver in at the same time." - ) - - raise_assertion_if( - condition=callable(default_value), - message='The default value can not be a function but received "{}".'.format(base_type(default_value) - ) + if args and not isinstance(args, Mapping): + raise AssertionError( + 'Arguments in a field have to be a mapping, received "{}".'.format(args) + ) + if source and resolver: + raise AssertionError( + "A Field cannot have a source and a resolver in at the same time." + ) + if callable(default_value): + raise AssertionError( + 'The default value can not be a function but received "{}".'.format( + base_type(default_value) + ) + ) if required: type = NonNull(type) diff --git a/graphene/types/mountedtype.py b/graphene/types/mountedtype.py index 49b887cf..fc4efb85 100644 --- a/graphene/types/mountedtype.py +++ b/graphene/types/mountedtype.py @@ -1,7 +1,6 @@ from ..utils.orderedtype import OrderedType from .unmountedtype import UnmountedType -from ..utils.comparison_helper import raise_assertion_if class MountedType(OrderedType): @classmethod @@ -9,10 +8,10 @@ class MountedType(OrderedType): """ Mount the UnmountedType instance """ - raise_assertion_if( - condition=not isinstance(unmounted, UnmountedType), - message="{} can't mount {}".format(cls.__name__, repr(unmounted) - ) + if not isinstance(unmounted, UnmountedType): + raise AssertionError( + "{} can't mount {}".format(cls.__name__, repr(unmounted)) + ) return cls( unmounted.get_type(), diff --git a/graphene/types/objecttype.py b/graphene/types/objecttype.py index 847c83f6..2be97358 100644 --- a/graphene/types/objecttype.py +++ b/graphene/types/objecttype.py @@ -5,8 +5,6 @@ from .field import Field from .interface import Interface from .utils import yank_fields_from_attrs -from ..utils.comparison_helper import raise_assertion_if - # For static type checking with Mypy MYPY = False if MYPY: @@ -49,15 +47,15 @@ class ObjectType(BaseType): for base in reversed(cls.__mro__): fields.update(yank_fields_from_attrs(base.__dict__, _as=Field)) - error_message = """ - {name}.Meta.possible_types will cause type collision with {name}.is_type_of. - Please use one or other. - """.format(name=cls.__name__) - - raise_assertion_if( - condition=possible_types and cls.is_type_of, - message=error_message - ) + if possible_types and cls.is_type_of: + raise AssertionError( + """ + {name}.Meta.possible_types will cause type collision with {name}.is_type_of. + Please use one or other. + """.format( + name=cls.__name__ + ) + ) if _meta.fields: _meta.fields.update(fields) diff --git a/graphene/types/resolver.py b/graphene/types/resolver.py index a050b17e..d9151b2a 100644 --- a/graphene/types/resolver.py +++ b/graphene/types/resolver.py @@ -1,5 +1,3 @@ -from ..utils.comparison_helper import raise_assertion_if - def attr_resolver(attname, default_value, root, info, **args): return getattr(root, attname, default_value) @@ -13,11 +11,8 @@ default_resolver = attr_resolver def set_default_resolver(resolver): global default_resolver - - raise_assertion_if( - condition=not callable(resolver), - message="Received non-callable resolver." - ) + if not callable(resolver): + raise AssertionError("Received non-callable resolver.") default_resolver = resolver diff --git a/graphene/types/schema.py b/graphene/types/schema.py index b106ad36..e54a13ca 100644 --- a/graphene/types/schema.py +++ b/graphene/types/schema.py @@ -13,17 +13,14 @@ from graphql.utils.schema_printer import print_schema from .definitions import GrapheneGraphQLType from .objecttype import ObjectType from .typemap import TypeMap, is_graphene_type -from ..utils.comparison_helper import raise_assertion_if def assert_valid_root_type(_type): if _type is None: return is_graphene_objecttype = inspect.isclass(_type) and issubclass(_type, ObjectType) is_graphql_objecttype = isinstance(_type, GraphQLObjectType) - raise_assertion_if( - condition=not (is_graphene_objecttype or is_graphql_objecttype), - message="Type {} is not a valid ObjectType.".format(_type) - ) + if not (is_graphene_objecttype or is_graphql_objecttype): + raise AssertionError("Type {} is not a valid ObjectType.".format(_type)) class Schema(GraphQLSchema): @@ -54,10 +51,12 @@ class Schema(GraphQLSchema): if directives is None: directives = [GraphQLIncludeDirective, GraphQLSkipDirective] - raise_assertion_if( - condition=not all(isinstance(d, GraphQLDirective) for d in directives), - message="Schema directives must be List[GraphQLDirective] if provided but got: {}.".format(directives) - ) + if not all(isinstance(d, GraphQLDirective) for d in directives): + raise AssertionError( + "Schema directives must be List[GraphQLDirective] if provided but got: {}.".format( + directives + ) + ) self._directives = directives self.build_typemap() @@ -91,19 +90,16 @@ class Schema(GraphQLSchema): return _type if is_graphene_type(_type): graphql_type = self.get_type(_type._meta.name) - - raise_assertion_if( - condition=not graphql_type, - message="Type {} not found in this schema.".format(_type._meta.name) - ) - - error_message = "The type {} does not match with the associated graphene type {}." - .format(_type, graphql_type.graphene_type) - raise_assertion_if( - condition=graphql_type.graphene_type is not _type, - message=error_message - ) - + if not graphql_type: + raise AssertionError( + "Type {} not found in this schema.".format(_type._meta.name) + ) + if graphql_type.graphene_type != _type: + raise AssertionError( + "The type {} does not match with the associated graphene type {}.".format( + _type, graphql_type.graphene_type + ) + ) return graphql_type raise Exception("{} is not a valid GraphQL type.".format(_type)) diff --git a/graphene/types/typemap.py b/graphene/types/typemap.py index 72044877..f34cd50e 100644 --- a/graphene/types/typemap.py +++ b/graphene/types/typemap.py @@ -40,7 +40,6 @@ from .scalars import ID, Boolean, Float, Int, Scalar, String from .structures import List, NonNull from .union import Union from .utils import get_field_as -from ..utils.comparison_helper import raise_assertion_if def is_graphene_type(_type): @@ -61,18 +60,16 @@ def resolve_type(resolve_type_func, map, type_name, root, info): if inspect.isclass(_type) and issubclass(_type, ObjectType): graphql_type = map.get(_type._meta.name) - raise_assertion_if( - condition=not graphql_type, - message="Can't find type {} in schema".format(_type._meta.name) - ) - - error_message = "The type {} does not match with the associated graphene type {}." - .format( _type, graphql_type.graphene_type) - raise_assertion_if( - condition=graphql_type.graphene_type is not _type, - message=error_message - ) - + if not graphql_type: + raise AssertionError( + "Can't find type {} in schema".format(_type._meta.name) + ) + if graphql_type.graphene_type != _type: + raise AssertionError( + "The type {} does not match with the associated graphene type {}.".format( + _type, graphql_type.graphene_type + ) + ) return graphql_type return _type @@ -103,12 +100,12 @@ class TypeMap(GraphQLTypeMap): if type._meta.name in map: _type = map[type._meta.name] if isinstance(_type, GrapheneGraphQLType): - error_message = "Found different types with the same name in the schema: {}, {}." - .format(_type.graphene_type, type) - raise_assertion_if( - condition=_type.graphene_type is not type, - message=error_message - ) + if _type.graphene_type is not type: + raise AssertionError( + "Found different types with the same name in the schema: {}, {}.".format( + _type.graphene_type, type + ) + ) return map if issubclass(type, ObjectType): @@ -185,12 +182,12 @@ class TypeMap(GraphQLTypeMap): if type._meta.name in map: _type = map[type._meta.name] if isinstance(_type, GrapheneGraphQLType): - error_message = "Found different types with the same name in the schema: {}, {}." - .format(_type.graphene_type, type) - raise_assertion_if( - condition=_type.graphene_type is not type, - message=error_message - ) + if _type.graphene_type != type: + raise AssertionError( + "Found different types with the same name in the schema: {}, {}.".format( + _type.graphene_type, type + ) + ) return _type def interfaces(): @@ -198,12 +195,12 @@ class TypeMap(GraphQLTypeMap): for interface in type._meta.interfaces: self.graphene_reducer(map, interface) internal_type = map[interface._meta.name] - error_message = "Found different types with the same name in the schema: {}, {}." - .format(internal_type.graphene_type, interface) - raise_assertion_if( - condition=internal_type.graphene_type is not interface, - message=error_message - ) + if internal_type.graphene_type != interface: + raise AssertionError( + "Found different types with the same name in the schema: {}, {}.".format( + internal_type.graphene_type, interface + ) + ) interfaces.append(internal_type) return interfaces @@ -227,12 +224,12 @@ class TypeMap(GraphQLTypeMap): if type._meta.name in map: _type = map[type._meta.name] if isinstance(_type, GrapheneInterfaceType): - error_message = "Found different types with the same name in the schema: {}, {}." - .format(_type.graphene_type, type) - raise_assertion_if( - condition= _type.graphene_type is not type, - message=error_message - ) + if _type.graphene_type != type: + raise AssertionError( + "Found different types with the same name in the schema: {}, {}.".format( + _type.graphene_type, type + ) + ) return _type _resolve_type = None @@ -271,12 +268,12 @@ class TypeMap(GraphQLTypeMap): for objecttype in type._meta.types: self.graphene_reducer(map, objecttype) internal_type = map[objecttype._meta.name] - error_message = "Found different types with the same name in the schema: {}, {}." - .format(internal_type.graphene_type, objecttype) - raise_assertion_if( - condition=internal_type.graphene_type is not objecttype, - message=error_message - ) + if internal_type.graphene_type != objecttype: + raise AssertionError( + "Found different types with the same name in the schema: {}, {}.".format( + internal_type.graphene_type, objecttype + ) + ) union_types.append(internal_type) return union_types diff --git a/graphene/types/union.py b/graphene/types/union.py index 0122382e..1c14fd71 100644 --- a/graphene/types/union.py +++ b/graphene/types/union.py @@ -1,8 +1,6 @@ from .base import BaseOptions, BaseType from .unmountedtype import UnmountedType -from ..utils.comparison_helper import raise_assertion_if - # For static type checking with Mypy MYPY = False if MYPY: @@ -25,11 +23,10 @@ class Union(UnmountedType, BaseType): @classmethod def __init_subclass_with_meta__(cls, types=None, **options): - - raise_assertion_if( - condition=not (isinstance(types, (list, tuple)) and len(types) > 0, - message="Must provide types for Union {name}.".format(name=cls.__name__) - ) + if not (isinstance(types, (list, tuple)) and len(types) > 0): + raise AssertionError( + "Must provide types for Union {name}.".format(name=cls.__name__) + ) _meta = UnionOptions(cls) _meta.types = types super(Union, cls).__init_subclass_with_meta__(_meta=_meta, **options) diff --git a/graphene/types/uuid.py b/graphene/types/uuid.py index 1f06cbf9..4d6fd316 100644 --- a/graphene/types/uuid.py +++ b/graphene/types/uuid.py @@ -5,7 +5,6 @@ from uuid import UUID as _UUID from graphql.language import ast from .scalars import Scalar -from ..utils.comparison_helper import raise_assertion_if class UUID(Scalar): """UUID""" @@ -14,10 +13,8 @@ class UUID(Scalar): def serialize(uuid): if isinstance(uuid, str): uuid = _UUID(uuid) - raise_assertion_if( - condition=not isinstance(uuid, _UUID), - message="Expected UUID instance, received {}".format(uuid) - ) + if not isinstance(uuid, _UUID): + raise AssertionError("Expected UUID instance, received {}".format(uuid)) return str(uuid) @staticmethod diff --git a/graphene/utils/annotate.py b/graphene/utils/annotate.py index 39b91eeb..18dcd881 100644 --- a/graphene/utils/annotate.py +++ b/graphene/utils/annotate.py @@ -2,7 +2,6 @@ import six from ..pyutils.compat import func_name, signature from .deprecated import warn_deprecation -from .comparison_helper import raise_assertion_if def annotate(_func=None, _trigger_warning=True, **annotations): @@ -23,13 +22,11 @@ def annotate(_func=None, _trigger_warning=True, **annotations): # We make sure the annotations are valid for key, value in annotations.items(): - func_param = func_signature.parameters.get(key, None) - assertion_message = 'The key {key} is not a function parameter in the function "{func_name}".' - .format(key=key, func_name=func_name(_func) - - raise_assertion_if( - condition=func_param is None, - message=assertion_message + if func_signature.parameters.get(key, None) is None: + raise AssertionError( + 'The key {key} is not a function parameter in the function "{func_name}".'.format( + key=key, func_name=func_name(_func) + ) ) func_annotations = getattr(_func, "__annotations__", None) diff --git a/graphene/utils/subclass_with_meta.py b/graphene/utils/subclass_with_meta.py index 0546dc08..2889862f 100644 --- a/graphene/utils/subclass_with_meta.py +++ b/graphene/utils/subclass_with_meta.py @@ -41,13 +41,16 @@ class SubclassWithMeta(six.with_metaclass(SubclassWithMeta_Meta)): options = dict(meta_options, **_meta_props) abstract = options.pop("abstract", False) - error_message = """ + if abstract: + if options: + raise AssertionError( + """ Abstract types can only contain the abstract attribute. Received: abstract, {option_keys} - """.format(option_keys=", ".join(options.keys()) - - raise_assertion_if(condition=options and abstract, message=error_message) - + """.format( + option_keys=", ".join(options.keys()) + ) + ) else: super_class = super(cls, cls) if hasattr(super_class, "__init_subclass_with_meta__"): From 9e53e543a15aad44c9f4761d6cf009b55c957786 Mon Sep 17 00:00:00 2001 From: Kacppian Date: Tue, 17 Jul 2018 22:59:43 +0530 Subject: [PATCH 7/9] forgot a conflict --- graphene/pyutils/version.py | 4 ---- graphene/types/argument.py | 1 + graphene/types/base.py | 1 + graphene/types/datetime.py | 1 + graphene/types/schema.py | 1 + graphene/types/uuid.py | 1 + graphene/utils/comparison_helper.py | 4 ++-- 7 files changed, 7 insertions(+), 6 deletions(-) diff --git a/graphene/pyutils/version.py b/graphene/pyutils/version.py index 9d33209f..ab177e12 100644 --- a/graphene/pyutils/version.py +++ b/graphene/pyutils/version.py @@ -3,10 +3,6 @@ from __future__ import unicode_literals import datetime import os import subprocess -<<<<<<< HEAD -from .comparison_helper import raise_assertion_if -======= ->>>>>>> parent of 41dcbdc... DRY-ed up def get_version(version=None): diff --git a/graphene/types/argument.py b/graphene/types/argument.py index 97ff3b27..326e173d 100644 --- a/graphene/types/argument.py +++ b/graphene/types/argument.py @@ -6,6 +6,7 @@ from .mountedtype import MountedType from .structures import NonNull from .utils import get_type + class Argument(MountedType): def __init__( self, diff --git a/graphene/types/base.py b/graphene/types/base.py index 6c71e599..1b4d4034 100644 --- a/graphene/types/base.py +++ b/graphene/types/base.py @@ -1,6 +1,7 @@ from ..utils.subclass_with_meta import SubclassWithMeta from ..utils.trim_docstring import trim_docstring + class BaseOptions(object): name = None # type: str description = None # type: str diff --git a/graphene/types/datetime.py b/graphene/types/datetime.py index 724bf31f..3aa38c98 100644 --- a/graphene/types/datetime.py +++ b/graphene/types/datetime.py @@ -7,6 +7,7 @@ from graphql.language import ast from .scalars import Scalar + class Date(Scalar): """ The `Date` scalar type represents a Date diff --git a/graphene/types/schema.py b/graphene/types/schema.py index e54a13ca..9250f86d 100644 --- a/graphene/types/schema.py +++ b/graphene/types/schema.py @@ -14,6 +14,7 @@ from .definitions import GrapheneGraphQLType from .objecttype import ObjectType from .typemap import TypeMap, is_graphene_type + def assert_valid_root_type(_type): if _type is None: return diff --git a/graphene/types/uuid.py b/graphene/types/uuid.py index 4d6fd316..84089a2d 100644 --- a/graphene/types/uuid.py +++ b/graphene/types/uuid.py @@ -6,6 +6,7 @@ from graphql.language import ast from .scalars import Scalar + class UUID(Scalar): """UUID""" diff --git a/graphene/utils/comparison_helper.py b/graphene/utils/comparison_helper.py index 4a087a7c..c0dc8242 100644 --- a/graphene/utils/comparison_helper.py +++ b/graphene/utils/comparison_helper.py @@ -1,3 +1,3 @@ def raise_assertion_if(condition=None, message=None): - if condition: - raise AssertionError(message) \ No newline at end of file + if condition: + raise AssertionError(message) From 2ce38844a27de4ab202b4af764a54a0c0477909f Mon Sep 17 00:00:00 2001 From: Kacppian Date: Sat, 28 Jul 2018 13:37:01 +0530 Subject: [PATCH 8/9] testing things out --- graphene/pyutils/version.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/graphene/pyutils/version.py b/graphene/pyutils/version.py index ab177e12..de329c43 100644 --- a/graphene/pyutils/version.py +++ b/graphene/pyutils/version.py @@ -3,6 +3,7 @@ from __future__ import unicode_literals import datetime import os import subprocess +from ..utils.comparison_helper import raise_assertion_if def get_version(version=None): @@ -44,10 +45,14 @@ def get_complete_version(version=None): if version is None: from graphene import VERSION as version else: - if len(version) is not 5: - raise AssertionError("Version needs to be 5") - if version[3] not in ("alpha", "beta", "rc", "final"): - raise AssertionError("Release version is unkown") + raise_assertion_if( + condition=len(version) is not 5, message="Version needs to be 5" + ) + + raise_assertion_if( + condition=version[3] not in ("alpha", "beta", "rc", "final"), + message="Release version is unkown", + ) return version From 863bfcf6b412b6fcac240f517113ae9bc0d10e61 Mon Sep 17 00:00:00 2001 From: Kacppian Date: Sat, 28 Jul 2018 15:30:08 +0530 Subject: [PATCH 9/9] minor changes --- graphene/relay/connection.py | 65 +++++++++++++++++++----------------- 1 file changed, 35 insertions(+), 30 deletions(-) diff --git a/graphene/relay/connection.py b/graphene/relay/connection.py index 3f58fdbf..c195ae42 100644 --- a/graphene/relay/connection.py +++ b/graphene/relay/connection.py @@ -9,6 +9,7 @@ from ..types import Boolean, Enum, Int, Interface, List, NonNull, Scalar, String from ..types.field import Field from ..types.objecttype import ObjectType, ObjectTypeOptions from .node import is_node +from ..utils.comparison_helper import raise_assertion_if class PageInfo(ObjectType): @@ -46,17 +47,18 @@ class Connection(ObjectType): @classmethod def __init_subclass_with_meta__(cls, node=None, name=None, **options): _meta = ConnectionOptions(cls) - if not node: - raise AssertionError( - "You have to provide a node in {}.Meta".format(cls.__name__) - ) + error_message = "You have to provide a node in {}.Meta".format(cls.__name__) + raise_assertion_if(condition=not node, message=error_message) - if not issubclass(node, (Scalar, Enum, ObjectType, Interface, Union, NonNull)): - raise AssertionError( - 'Received incompatible node "{}" for Connection {}.'.format( - node, cls.__name__ - ) - ) + error_message = 'Received incompatible node "{}" for Connection {}.'.format( + node, cls.__name__ + ) + raise_assertion_if( + condition=not issubclass( + node, (Scalar, Enum, ObjectType, Interface, Union, NonNull) + ), + error_message=error_message, + ) base_name = re.sub("Connection$", "", name or cls.__name__) or node._meta.name if not name: @@ -106,18 +108,20 @@ class IterableConnectionField(Field): if isinstance(type, NonNull): connection_type = type.of_type - if is_node(connection_type): - raise Exception( - "ConnectionField's now need a explicit ConnectionType for Nodes.\n" - "Read more: https://github.com/graphql-python/graphene/blob/v2.0.0/UPGRADE-v2.0.md#node-connections" - ) + error_message = """ + ConnectionField's now need a explicit ConnectionType for Nodes. + Read more: https://github.com/graphql-python/graphene/blob/v2.0.0/UPGRADE-v2.0.md#node-connections + """ + raise_assertion_if( + condition=is_node(connection_type), error_message=error_message + ) - if not issubclass(connection_type, Connection): - raise AssertionError( - '{} type have to be a subclass of Connection. Received "{}".'.format( - self.__class__.__name__, connection_type - ) - ) + error_message = '{} type have to be a subclass of Connection. Received "{}".'.format( + self.__class__.__name__, connection_type + ) + raise_assertion_if( + condition=not issubclass(connection_type, Connection), message=error_message + ) return type @classmethod @@ -125,15 +129,16 @@ class IterableConnectionField(Field): if isinstance(resolved, connection_type): return resolved - if not isinstance(resolved, Iterable): - raise AssertionError( - """ - Resolved value from the connection field have to be iterable or instance of {}. - Received "{}" - """.format( - connection_type, resolved - ) - ) + error_message = """ + Resolved value from the connection field have to be iterable or instance of {}. + Received "{}" + """.format( + connection_type, resolved + ) + raise_assertion_if( + condition=not isinstance(resolved, Iterable), message=error_message + ) + connection = connection_from_list( resolved, args,