Skip to content

Commit

Permalink
Change asserts to manually raising AssertionError
Browse files Browse the repository at this point in the history
  • Loading branch information
dsanders11 committed Apr 21, 2019
1 parent abff3d7 commit 5593f48
Show file tree
Hide file tree
Showing 20 changed files with 169 additions and 103 deletions.
36 changes: 24 additions & 12 deletions graphene/relay/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,18 @@ class Meta:
@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 isinstance(node, NonNull) or issubclass(
if not node:
raise AssertionError(
"You have to provide a node in {}.Meta".format(cls.__name__)
)
if not isinstance(node, NonNull) and not issubclass(
node, (Scalar, Enum, ObjectType, Interface, Union, NonNull)
), ('Received incompatible node "{}" for Connection {}.').format(
node, cls.__name__
)
):
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:
Expand Down Expand Up @@ -132,20 +138,26 @@ def type(self):
"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
def resolve_connection(cls, connection_type, args, resolved):
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,
Expand Down
17 changes: 11 additions & 6 deletions graphene/relay/mutation.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@ def __init_subclass_with_meta__(
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:
Expand All @@ -41,10 +43,13 @@ def __init_subclass_with_meta__(
)
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)
Expand Down
10 changes: 6 additions & 4 deletions graphene/relay/node.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ def get_resolver(self, parent_resolver):

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"
if not issubclass(node, Node):
raise AssertionError("NodeField can only operate in Nodes")
self.node_type = node
self.field_type = type

Expand Down Expand Up @@ -98,9 +99,10 @@ def get_node_from_global_id(cls, info, global_id, only_type=None):
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:
Expand Down
7 changes: 4 additions & 3 deletions graphene/types/argument.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,10 @@ 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
3 changes: 2 additions & 1 deletion graphene/types/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ def create_type(cls, class_name, **options):

@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 directly meta")
if not _meta:
return
_meta.name = name or cls.__name__
Expand Down
17 changes: 8 additions & 9 deletions graphene/types/datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,8 @@ 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
Expand Down Expand Up @@ -50,9 +49,10 @@ 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
Expand Down Expand Up @@ -80,9 +80,8 @@ 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
Expand Down
7 changes: 4 additions & 3 deletions graphene/types/decimal.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,10 @@ class Decimal(Scalar):
def serialize(dec):
if isinstance(dec, str):
dec = _Decimal(dec)
assert isinstance(dec, _Decimal), 'Received not compatible Decimal "{}"'.format(
repr(dec)
)
if not isinstance(dec, _Decimal):
raise AssertionError(
'Received not compatible Decimal "{}"'.format(repr(dec))
)
return str(dec)

@classmethod
Expand Down
3 changes: 2 additions & 1 deletion graphene/types/dynamic.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ 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) and not isinstance(type, partial):
raise AssertionError()
self.type = type
self.with_schema = with_schema

Expand Down
25 changes: 16 additions & 9 deletions graphene/types/field.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,22 @@ def __init__(
**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)
Expand Down
7 changes: 4 additions & 3 deletions graphene/types/mountedtype.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ def mounted(cls, unmounted): # noqa: N802
"""
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(),
Expand Down
3 changes: 2 additions & 1 deletion graphene/types/mutation.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ def __init_subclass_with_meta__(

if not resolver:
mutate = getattr(cls, "mutate", None)
assert mutate, "All mutations must define a mutate method in it"
if not mutate:
raise AssertionError("All mutations must define a mutate method in it")
resolver = get_unbound_function(mutate)

if _meta.fields:
Expand Down
21 changes: 14 additions & 7 deletions graphene/types/objecttype.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,18 +39,25 @@ def __init_subclass_with_meta__(
fields = OrderedDict()

for interface in interfaces:
assert issubclass(interface, Interface), (
'All interfaces of {} must be a subclass of Interface. Received "{}".'
).format(cls.__name__, interface)
if not issubclass(interface, Interface):
raise AssertionError(
(
"All interfaces of {} must be a subclass of Interface. "
'Received "{}".'
).format(cls.__name__, interface)
)
fields.update(interface._meta.fields)

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)
Expand Down
3 changes: 2 additions & 1 deletion graphene/types/resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ def dict_or_attr_resolver(attname, default_value, root, info, **args):

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


Expand Down
25 changes: 13 additions & 12 deletions graphene/types/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,8 @@ 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 and not is_graphql_objecttype:
raise AssertionError(("Type {} is not a valid ObjectType.").format(_type))


class Schema(GraphQLSchema):
Expand Down Expand Up @@ -53,11 +52,11 @@ def __init__(
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()

Expand Down Expand Up @@ -91,10 +90,12 @@ def get_graphql_type(self, _type):
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()
return graphql_type
raise Exception("{} is not a valid GraphQL type.".format(_type))

Expand Down
9 changes: 6 additions & 3 deletions graphene/types/structures.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,12 @@ class NonNull(Structure):

def __init__(self, *args, **kwargs):
super(NonNull, self).__init__(*args, **kwargs)
assert not isinstance(self._of_type, NonNull), (
"Can only create NonNull of a Nullable GraphQLType but got: {}."
).format(self._of_type)
if isinstance(self._of_type, NonNull):
raise AssertionError(
(
"Can only create NonNull of a Nullable GraphQLType but got: {}."
).format(self._of_type)
)

def __str__(self):
return "{}!".format(self.of_type)
Expand Down
Loading

0 comments on commit 5593f48

Please sign in to comment.