From 3ca01d47142072e008f779b35d9fecb660ae32c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=9Clgen=20Sar=C4=B1kavak?= Date: Thu, 1 Jul 2021 18:33:11 +0300 Subject: [PATCH] Apply black (#69) * Add black to dev-env requirements * Apply black to everything --- dev-env-requirements.txt | 1 + graphene_django_optimizer/query.py | 51 +++--- graphene_django_optimizer/types.py | 3 +- graphene_django_optimizer/utils.py | 2 +- setup.py | 64 +++---- tests/graphql_utils.py | 6 +- tests/models.py | 14 +- tests/schema.py | 68 ++++---- tests/settings.py | 10 +- tests/test_field.py | 22 ++- tests/test_query.py | 264 ++++++++++++++++++----------- tests/test_relay.py | 99 ++++++----- tests/test_resolver.py | 97 ++++++----- tests/test_types.py | 60 ++++--- tests/test_utils.py | 4 +- 15 files changed, 449 insertions(+), 316 deletions(-) diff --git a/dev-env-requirements.txt b/dev-env-requirements.txt index 2ad8363..4f70c88 100644 --- a/dev-env-requirements.txt +++ b/dev-env-requirements.txt @@ -6,3 +6,4 @@ pytest-django==3.5.0 pytest-cov==2.7.1 flake8==3.7.7 mock==2.0.0 +black==21.6b0 diff --git a/graphene_django_optimizer/query.py b/graphene_django_optimizer/query.py index cafae40..057125a 100644 --- a/graphene_django_optimizer/query.py +++ b/graphene_django_optimizer/query.py @@ -47,7 +47,7 @@ class QueryOptimizer(object): def __init__(self, info, **options): self.root_info = info - self.disable_abort_only = options.pop('disable_abort_only', False) + self.disable_abort_only = options.pop("disable_abort_only", False) def optimize(self, queryset): info = self.root_info @@ -61,7 +61,7 @@ def optimize(self, queryset): def _get_type(self, field_def): a_type = field_def.type - while hasattr(a_type, 'of_type'): + while hasattr(a_type, "of_type"): a_type = a_type.of_type return a_type @@ -69,7 +69,7 @@ def _get_possible_types(self, graphql_type): if isinstance(graphql_type, (GraphQLInterfaceType, GraphQLUnionType)): return self.root_info.schema.get_possible_types(graphql_type) else: - return (graphql_type, ) + return (graphql_type,) def _get_base_model(self, graphql_types): models = tuple(t.graphene_type._meta.model for t in graphql_types) @@ -87,10 +87,10 @@ def handle_inline_fragment(self, selection, schema, possible_types, store): parent_model = self._get_base_model(possible_types) if not parent_model: continue - path_from_parent = _get_path_from_parent( - fragment_model._meta, parent_model) + path_from_parent = _get_path_from_parent(fragment_model._meta, parent_model) select_related_name = LOOKUP_SEP.join( - p.join_field.name for p in path_from_parent) + p.join_field.name for p in path_from_parent + ) if not select_related_name: continue fragment_store = self._optimize_gql_selections( @@ -124,8 +124,7 @@ def _optimize_gql_selections(self, field_type, field_ast): possible_types = self._get_possible_types(graphql_type) for selection in selection_set.selections: if isinstance(selection, InlineFragment): - self.handle_inline_fragment( - selection, schema, possible_types, store) + self.handle_inline_fragment(selection, schema, possible_types, store) else: name = selection.name.value if isinstance(selection, FragmentSpread): @@ -138,9 +137,9 @@ def _optimize_gql_selections(self, field_type, field_ast): graphene_type = possible_type.graphene_type # Check if graphene type is a relay connection or a relay edge - if hasattr(graphene_type._meta, 'node') or ( - hasattr(graphene_type, 'cursor') - and hasattr(graphene_type, 'node') + if hasattr(graphene_type._meta, "node") or ( + hasattr(graphene_type, "cursor") + and hasattr(graphene_type, "node") ): relay_store = self._optimize_gql_selections( self._get_type(selection_field_def), @@ -152,7 +151,7 @@ def _optimize_gql_selections(self, field_type, field_ast): except ImportError: store.abort_only_optimization() else: - model = getattr(graphene_type._meta, 'model', None) + model = getattr(graphene_type._meta, "model", None) if model and name not in optimized_fields_by_model: field_model = optimized_fields_by_model[name] = model if field_model == model: @@ -167,9 +166,11 @@ def _optimize_gql_selections(self, field_type, field_ast): def _optimize_field(self, store, model, selection, field_def, parent_type): optimized_by_name = self._optimize_field_by_name( - store, model, selection, field_def) + store, model, selection, field_def + ) optimized_by_hints = self._optimize_field_by_hints( - store, selection, field_def, parent_type) + store, selection, field_def, parent_type + ) optimized = optimized_by_name or optimized_by_hints if not optimized: store.abort_only_optimization() @@ -211,7 +212,7 @@ def _optimize_field_by_name(self, store, model, selection, field_def): return False def _get_optimization_hints(self, resolver): - return getattr(resolver, 'optimization_hints', None) + return getattr(resolver, "optimization_hints", None) def _get_value(self, info, value): if isinstance(value, Variable): @@ -267,7 +268,7 @@ def _get_name_from_resolver(self, resolver): if name_fn: return name_fn() if self._is_resolver_for_id_field(resolver): - return 'id' + return "id" elif isinstance(resolver, functools.partial): resolver_fn = resolver if resolver_fn.func != default_resolver: @@ -280,16 +281,19 @@ def _get_name_from_resolver(self, resolver): # No suitable instances found, default to first arg arg = resolver_fn.args[0] resolver_fn = arg - if isinstance(resolver_fn, functools.partial) and resolver_fn.func == default_resolver: + if ( + isinstance(resolver_fn, functools.partial) + and resolver_fn.func == default_resolver + ): return resolver_fn.args[0] if self._is_resolver_for_id_field(resolver_fn): - return 'id' + return "id" return resolver_fn def _is_resolver_for_id_field(self, resolver): resolve_id = DjangoObjectType.resolve_id # For python 2 unbound method: - if hasattr(resolve_id, 'im_func'): + if hasattr(resolve_id, "im_func"): resolve_id = resolve_id.im_func return resolver == resolve_id @@ -300,8 +304,9 @@ def _get_model_field_from_name(self, model, name): descriptor = model.__dict__.get(name) if not descriptor: return None - return getattr(descriptor, 'rel', None) \ - or getattr(descriptor, 'related', None) # Django < 1.9 + return getattr(descriptor, "rel", None) or getattr( + descriptor, "related", None + ) # Django < 1.9 def _is_foreign_key_id(self, model_field, name): return ( @@ -325,7 +330,7 @@ def _create_resolve_info(self, field_name, field_asts, return_type, parent_type) ) -class QueryOptimizerStore(): +class QueryOptimizerStore: def __init__(self, disable_abort_only=False): self.select_list = [] self.prefetch_list = [] @@ -402,7 +407,7 @@ def _get_path_from_parent(self, parent): model to the current model, or an empty list if parent is not a parent of the current model. """ - if hasattr(self, 'get_path_from_parent'): + if hasattr(self, "get_path_from_parent"): return self.get_path_from_parent(parent) if self.model is parent: return [] diff --git a/graphene_django_optimizer/types.py b/graphene_django_optimizer/types.py index 852182c..cffeba6 100644 --- a/graphene_django_optimizer/types.py +++ b/graphene_django_optimizer/types.py @@ -12,7 +12,8 @@ class Meta: def can_optimize_resolver(cls, resolver_info): return ( isinstance(resolver_info.return_type, GrapheneObjectType) - and resolver_info.return_type.graphene_type is cls) + and resolver_info.return_type.graphene_type is cls + ) @classmethod def get_queryset(cls, queryset, info): diff --git a/graphene_django_optimizer/utils.py b/graphene_django_optimizer/utils.py index fbace7e..d4232da 100644 --- a/graphene_django_optimizer/utils.py +++ b/graphene_django_optimizer/utils.py @@ -2,4 +2,4 @@ def is_iterable(obj): - return hasattr(obj, '__iter__') and not isinstance(obj, str) + return hasattr(obj, "__iter__") and not isinstance(obj, str) diff --git a/setup.py b/setup.py index cbfb8d3..50d6369 100755 --- a/setup.py +++ b/setup.py @@ -4,8 +4,8 @@ import sys from setuptools import setup -needs_pytest = {'pytest', 'test', 'ptr'}.intersection(sys.argv) -pytest_runner = ['pytest-runner >=4.0,<5dev'] if needs_pytest else [] +needs_pytest = {"pytest", "test", "ptr"}.intersection(sys.argv) +pytest_runner = ["pytest-runner >=4.0,<5dev"] if needs_pytest else [] def read(fname): @@ -13,37 +13,37 @@ def read(fname): setup( - name='graphene-django-optimizer', - version='0.8.0', - author='Tomás Fox', - author_email='tomas.c.fox@gmail.com', - description='Optimize database access inside graphene queries.', - license='MIT', - keywords='graphene django optimizer optimize graphql query prefetch select related', - url='https://github.com/tfoxy/graphene-django-optimizer', - packages=['graphene_django_optimizer'], + name="graphene-django-optimizer", + version="0.8.0", + author="Tomás Fox", + author_email="tomas.c.fox@gmail.com", + description="Optimize database access inside graphene queries.", + license="MIT", + keywords="graphene django optimizer optimize graphql query prefetch select related", + url="https://github.com/tfoxy/graphene-django-optimizer", + packages=["graphene_django_optimizer"], setup_requires=pytest_runner, - long_description=read('README.md'), - long_description_content_type='text/markdown', + long_description=read("README.md"), + long_description_content_type="text/markdown", classifiers=[ - 'Development Status :: 4 - Beta', - 'Environment :: Web Environment', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: MIT License', - 'Operating System :: OS Independent', - 'Programming Language :: Python', - 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.5', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Framework :: Django', - 'Framework :: Django :: 1.11', - 'Framework :: Django :: 2.0', - 'Framework :: Django :: 2.1', - 'Framework :: Django :: 2.2', - 'Framework :: Django :: 3.0', - 'Framework :: Django :: 3.1', + "Development Status :: 4 - Beta", + "Environment :: Web Environment", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 2.7", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.5", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Framework :: Django", + "Framework :: Django :: 1.11", + "Framework :: Django :: 2.0", + "Framework :: Django :: 2.1", + "Framework :: Django :: 2.2", + "Framework :: Django :: 3.0", + "Framework :: Django :: 3.1", ], ) diff --git a/tests/graphql_utils.py b/tests/graphql_utils.py index 1f1aff3..6b061e4 100644 --- a/tests/graphql_utils.py +++ b/tests/graphql_utils.py @@ -14,7 +14,7 @@ def create_execution_context(schema, request_string, variables=None): - source = Source(request_string, 'GraphQL request') + source = Source(request_string, "GraphQL request") document_ast = parse(source) return ExecutionContext( schema, @@ -35,7 +35,7 @@ def get_field_asts_from_execution_context(exe_context): type, exe_context.operation.selection_set, DefaultOrderedDict(list), - set() + set(), ) # field_asts = next(iter(fields.values())) field_asts = tuple(fields.values())[0] @@ -69,5 +69,5 @@ def create_resolve_info(schema, request_string, variables=None): root_value=exe_context.root_value, operation=exe_context.operation, variable_values=exe_context.variable_values, - context=context + context=context, ) diff --git a/tests/models.py b/tests/models.py index ede0f38..f6f2f87 100644 --- a/tests/models.py +++ b/tests/models.py @@ -3,11 +3,13 @@ class Item(models.Model): name = models.CharField(max_length=100, blank=True) - parent = models.ForeignKey('Item', on_delete=models.SET_NULL, null=True, related_name='children') - item = models.ForeignKey('Item', on_delete=models.SET_NULL, null=True) + parent = models.ForeignKey( + "Item", on_delete=models.SET_NULL, null=True, related_name="children" + ) + item = models.ForeignKey("Item", on_delete=models.SET_NULL, null=True) value = models.IntegerField(default=10) - item_type = 'simple' + item_type = "simple" @property def title(self): @@ -32,7 +34,7 @@ class RelatedItem(Item): class RelatedOneToManyItem(models.Model): name = models.CharField(max_length=100, blank=True) - item = models.ForeignKey(Item, on_delete=models.PROTECT, related_name='otm_items') + item = models.ForeignKey(Item, on_delete=models.PROTECT, related_name="otm_items") class ExtraDetailedItem(DetailedItem): @@ -49,4 +51,6 @@ class SomeOtherItem(models.Model): class OtherItem(models.Model): name = models.CharField(max_length=100, blank=True) - some_other_item = models.ForeignKey('SomeOtherItem', on_delete=models.PROTECT, null=False) + some_other_item = models.ForeignKey( + "SomeOtherItem", on_delete=models.PROTECT, null=False + ) diff --git a/tests/schema.py b/tests/schema.py index afbaa23..66ffd9a 100644 --- a/tests/schema.py +++ b/tests/schema.py @@ -21,11 +21,11 @@ def _prefetch_children(info, filter_input): if filter_input is None: filter_input = {} - gte = filter_input.get('value', {}).get('gte', 0) + gte = filter_input.get("value", {}).get("gte", 0) return Prefetch( - 'children', + "children", queryset=gql_optimizer.query(Item.objects.filter(value__gte=int(gte)), info), - to_attr='gql_custom_filtered_children', + to_attr="gql_custom_filtered_children", ) @@ -44,64 +44,64 @@ class ItemInterface(graphene.Interface): title = graphene.String() unoptimized_title = graphene.String() item_type = graphene.String() - father = graphene.Field('tests.schema.ItemType') - all_children = graphene.List('tests.schema.ItemType') + father = graphene.Field("tests.schema.ItemType") + all_children = graphene.List("tests.schema.ItemType") children_names = graphene.String() aux_children_names = graphene.String() filtered_children = graphene.List( - 'tests.schema.ItemType', + "tests.schema.ItemType", name=graphene.String(required=True), ) children_custom_filtered = gql_optimizer.field( - ConnectionField('tests.schema.ItemConnection', filter_input=ItemFilterInput()), + ConnectionField("tests.schema.ItemConnection", filter_input=ItemFilterInput()), prefetch_related=_prefetch_children, ) def resolve_foo(root, info): - return 'bar' + return "bar" @gql_optimizer.resolver_hints( - model_field=lambda: 'children', + model_field=lambda: "children", ) def resolve_children_names(root, info): - return ' '.join(item.name for item in root.children.all()) + return " ".join(item.name for item in root.children.all()) @gql_optimizer.resolver_hints( - prefetch_related='children', + prefetch_related="children", ) def resolve_aux_children_names(root, info): - return ' '.join(item.name for item in root.children.all()) + return " ".join(item.name for item in root.children.all()) @gql_optimizer.resolver_hints( prefetch_related=lambda info, name: Prefetch( - 'children', + "children", queryset=gql_optimizer.query(Item.objects.filter(name=name), info), - to_attr='gql_filtered_children_' + name, + to_attr="gql_filtered_children_" + name, ), ) def resolve_filtered_children(root, info, name): - return getattr(root, 'gql_filtered_children_' + name) + return getattr(root, "gql_filtered_children_" + name) def resolve_children_custom_filtered(root, info, *_args): - return getattr(root, 'gql_custom_filtered_children') + return getattr(root, "gql_custom_filtered_children") class BaseItemType(OptimizedDjangoObjectType): title = gql_optimizer.field( graphene.String(), - only='name', + only="name", ) father = gql_optimizer.field( - graphene.Field('tests.schema.ItemType'), - model_field='parent', + graphene.Field("tests.schema.ItemType"), + model_field="parent", ) - relay_all_children = DjangoConnectionField('tests.schema.ItemNode') + relay_all_children = DjangoConnectionField("tests.schema.ItemNode") class Meta: model = Item @gql_optimizer.resolver_hints( - model_field='children', + model_field="children", ) def resolve_relay_all_children(root, info, **kwargs): return root.children.all() @@ -110,7 +110,10 @@ def resolve_relay_all_children(root, info, **kwargs): class ItemNode(BaseItemType): class Meta: model = Item - interfaces = (graphene.relay.Node, ItemInterface, ) + interfaces = ( + graphene.relay.Node, + ItemInterface, + ) class SomeOtherItemType(OptimizedDjangoObjectType): @@ -126,7 +129,7 @@ class Meta: class ItemType(BaseItemType): class Meta: model = Item - interfaces = (ItemInterface, ) + interfaces = (ItemInterface,) class ItemConnection(graphene.relay.Connection): @@ -147,13 +150,13 @@ class Meta: class RelatedItemType(ItemType): class Meta: model = RelatedItem - interfaces = (ItemInterface, ) + interfaces = (ItemInterface,) class ExtraDetailedItemType(DetailedItemType): class Meta: model = ExtraDetailedItem - interfaces = (ItemInterface, ) + interfaces = (ItemInterface,) class RelatedOneToManyItemType(OptimizedDjangoObjectType): @@ -164,23 +167,21 @@ class Meta: class UnrelatedModelType(OptimizedDjangoObjectType): class Meta: model = UnrelatedModel - interfaces = (DetailedInterface, ) + interfaces = (DetailedInterface,) class DummyItemMutation(graphene.Mutation): - item = graphene.Field( - ItemNode, description='The retrieved item.', required=False) + item = graphene.Field(ItemNode, description="The retrieved item.", required=False) class Arguments: - item_id = graphene.ID(description='The ID of the item.') + item_id = graphene.ID(description="The ID of the item.") class Meta: - description = 'A dummy mutation that retrieves a given item node.' + description = "A dummy mutation that retrieves a given item node." @staticmethod def mutate(info, item_id): - return graphene.Node.get_node_from_global_id( - info, item_id, only_type=ItemNode) + return graphene.Node.get_node_from_global_id(info, item_id, only_type=ItemNode) class Query(graphene.ObjectType): @@ -200,4 +201,5 @@ def resolve_other_items(root, info): schema = graphene.Schema( - query=Query, types=(UnrelatedModelType, ), mutation=DummyItemMutation) + query=Query, types=(UnrelatedModelType,), mutation=DummyItemMutation +) diff --git a/tests/settings.py b/tests/settings.py index cc1b7e5..6be0283 100644 --- a/tests/settings.py +++ b/tests/settings.py @@ -1,9 +1,7 @@ -INSTALLED_APPS = ( - 'tests', -) +INSTALLED_APPS = ("tests",) DATABASES = { - 'default': { - 'ENGINE': 'django.db.backends.sqlite3', + "default": { + "ENGINE": "django.db.backends.sqlite3", }, } -SECRET_KEY = 'dummy' +SECRET_KEY = "dummy" diff --git a/tests/test_field.py b/tests/test_field.py index 0d27ab6..d7a8957 100644 --- a/tests/test_field.py +++ b/tests/test_field.py @@ -9,7 +9,9 @@ def test_should_optimize_non_django_field_if_it_has_an_optimization_hint_in_the_field(): - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items(name: "bar") { id @@ -19,23 +21,27 @@ def test_should_optimize_non_django_field_if_it_has_an_optimization_hint_in_the_ } } } - ''') - qs = Item.objects.filter(name='bar') + """, + ) + qs = Item.objects.filter(name="bar") items = gql_optimizer.query(qs, info) - optimized_items = qs.select_related('parent') + optimized_items = qs.select_related("parent") assert_query_equality(items, optimized_items) def test_should_optimize_with_only_hint(): - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items(name: "foo") { id title } } - ''') - qs = Item.objects.filter(name='foo') + """, + ) + qs = Item.objects.filter(name="foo") items = gql_optimizer.query(qs, info) - optimized_items = qs.only('id', 'name') + optimized_items = qs.only("id", "name") assert_query_equality(items, optimized_items) diff --git a/tests/test_query.py b/tests/test_query.py index 8a7ca07..a821ec5 100644 --- a/tests/test_query.py +++ b/tests/test_query.py @@ -19,7 +19,9 @@ def test_should_reduce_number_of_queries_by_using_select_related(): # parent = Item.objects.create(name='foo') # Item.objects.create(name='bar', parent=parent) - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items(name: "bar") { id @@ -29,10 +31,11 @@ def test_should_reduce_number_of_queries_by_using_select_related(): } } } - ''') - qs = Item.objects.filter(name='bar') + """, + ) + qs = Item.objects.filter(name="bar") items = gql_optimizer.query(qs, info) - optimized_items = qs.select_related('parent') + optimized_items = qs.select_related("parent") assert_query_equality(items, optimized_items) @@ -40,7 +43,9 @@ def test_should_reduce_number_of_queries_by_using_select_related(): def test_should_reduce_number_of_queries_by_using_prefetch_related(): # parent = Item.objects.create(name='foo') # Item.objects.create(name='bar', parent=parent) - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items(name: "foo") { id @@ -51,27 +56,31 @@ def test_should_reduce_number_of_queries_by_using_prefetch_related(): } } } - ''') - qs = Item.objects.filter(name='foo') + """, + ) + qs = Item.objects.filter(name="foo") items = gql_optimizer.query(qs, info) - optimized_items = qs.prefetch_related('children') + optimized_items = qs.prefetch_related("children") assert_query_equality(items, optimized_items) # @pytest.mark.django_db def test_should_optimize_scalar_model_fields(): # Item.objects.create(name='foo') - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items(name: "foo") { id name } } - ''') - qs = Item.objects.filter(name='foo') + """, + ) + qs = Item.objects.filter(name="foo") items = gql_optimizer.query(qs, info) - optimized_items = qs.only('id', 'name') + optimized_items = qs.only("id", "name") assert_query_equality(items, optimized_items) @@ -79,32 +88,38 @@ def test_should_optimize_scalar_model_fields(): def test_should_optimize_scalar_foreign_key_model_fields(): # parent = Item.objects.create(name='foo') # Item.objects.create(name='bar', parent=parent) - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items(name: "bar") { id parentId } } - ''') - qs = Item.objects.filter(name='bar') + """, + ) + qs = Item.objects.filter(name="bar") items = gql_optimizer.query(qs, info) - optimized_items = qs.only('id', 'parent_id') + optimized_items = qs.only("id", "parent_id") assert_query_equality(items, optimized_items) # @pytest.mark.django_db def test_should_not_try_to_optimize_non_model_fields(): # Item.objects.create(name='foo') - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items(name: "foo") { id foo } } - ''') - qs = Item.objects.filter(name='foo') + """, + ) + qs = Item.objects.filter(name="foo") items = gql_optimizer.query(qs, info) optimized_items = qs assert_query_equality(items, optimized_items) @@ -113,15 +128,18 @@ def test_should_not_try_to_optimize_non_model_fields(): # @pytest.mark.django_db def test_should_not_try_to_optimize_non_field_model_fields(): # Item.objects.create(name='foo') - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items(name: "foo") { id unoptimizedTitle } } - ''') - qs = Item.objects.filter(name='foo') + """, + ) + qs = Item.objects.filter(name="foo") items = gql_optimizer.query(qs, info) optimized_items = qs assert_query_equality(items, optimized_items) @@ -129,17 +147,20 @@ def test_should_not_try_to_optimize_non_field_model_fields(): def test_should_try_to_optimize_non_field_model_fields_when_disabling_abort_only(): # Item.objects.create(name='foo') - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items(name: "foo") { id unoptimizedTitle } } - ''') - qs = Item.objects.filter(name='foo') + """, + ) + qs = Item.objects.filter(name="foo") items = gql_optimizer.query(qs, info, disable_abort_only=True) - optimized_items = qs.only('id') + optimized_items = qs.only("id") assert_query_equality(items, optimized_items) @@ -147,7 +168,9 @@ def test_should_try_to_optimize_non_field_model_fields_when_disabling_abort_only def test_should_optimize_when_using_fragments(): # parent = Item.objects.create(name='foo') # Item.objects.create(name='bar', parent=parent) - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items(name: "bar") { ...ItemFragment @@ -159,10 +182,11 @@ def test_should_optimize_when_using_fragments(): id } } - ''') - qs = Item.objects.filter(name='bar') + """, + ) + qs = Item.objects.filter(name="bar") items = gql_optimizer.query(qs, info) - optimized_items = qs.select_related('parent').only('id', 'parent__id') + optimized_items = qs.select_related("parent").only("id", "parent__id") assert_query_equality(items, optimized_items) @@ -170,7 +194,9 @@ def test_should_optimize_when_using_fragments(): def test_should_prefetch_field_with_camel_case_name(): # item = Item.objects.create(name='foo') # Item.objects.create(name='bar', item=item) - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items(name: "foo") { id @@ -181,10 +207,11 @@ def test_should_prefetch_field_with_camel_case_name(): } } } - ''') - qs = Item.objects.filter(name='foo') + """, + ) + qs = Item.objects.filter(name="foo") items = gql_optimizer.query(qs, info) - optimized_items = qs.prefetch_related('item_set') + optimized_items = qs.prefetch_related("item_set") assert_query_equality(items, optimized_items) @@ -193,7 +220,9 @@ def test_should_select_nested_related_fields(): # parent = Item.objects.create(name='foo') # parent = Item.objects.create(name='bar', parent=parent) # Item.objects.create(name='foobar', parent=parent) - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items(name: "foobar") { id @@ -206,10 +235,11 @@ def test_should_select_nested_related_fields(): } } } - ''') - qs = Item.objects.filter(name='foobar') + """, + ) + qs = Item.objects.filter(name="foobar") items = gql_optimizer.query(qs, info) - optimized_items = qs.select_related('parent__parent') + optimized_items = qs.select_related("parent__parent") assert_query_equality(items, optimized_items) @@ -218,7 +248,9 @@ def test_should_prefetch_nested_related_fields(): # parent = Item.objects.create(name='foo') # parent = Item.objects.create(name='bar', parent=parent) # Item.objects.create(name='foobar', parent=parent) - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items(name: "foo") { id @@ -233,10 +265,11 @@ def test_should_prefetch_nested_related_fields(): } } } - ''') - qs = Item.objects.filter(name='foo') + """, + ) + qs = Item.objects.filter(name="foo") items = gql_optimizer.query(qs, info) - optimized_items = qs.prefetch_related('children__children') + optimized_items = qs.prefetch_related("children__children") assert_query_equality(items, optimized_items) @@ -245,7 +278,9 @@ def test_should_prefetch_nested_select_related_field(): # parent = Item.objects.create(name='foo') # item = Item.objects.create(name='foobar') # Item.objects.create(name='bar', parent=parent, item=item) - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items(name: "foo") { id @@ -259,11 +294,12 @@ def test_should_prefetch_nested_select_related_field(): } } } - ''') - qs = Item.objects.filter(name='foo') + """, + ) + qs = Item.objects.filter(name="foo") items = gql_optimizer.query(qs, info) optimized_items = qs.prefetch_related( - Prefetch('children', queryset=Item.objects.select_related('item')), + Prefetch("children", queryset=Item.objects.select_related("item")), ) assert_query_equality(items, optimized_items) @@ -273,7 +309,9 @@ def test_should_select_nested_prefetch_related_field(): # parent = Item.objects.create(name='foo') # Item.objects.create(name='bar', parent=parent) # Item.objects.create(name='foobar', item=parent) - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items(name: "foobar") { id @@ -287,10 +325,11 @@ def test_should_select_nested_prefetch_related_field(): } } } - ''') - qs = Item.objects.filter(name='foobar') + """, + ) + qs = Item.objects.filter(name="foobar") items = gql_optimizer.query(qs, info) - optimized_items = qs.select_related('item').prefetch_related('item__children') + optimized_items = qs.select_related("item").prefetch_related("item__children") assert_query_equality(items, optimized_items) @@ -300,7 +339,9 @@ def test_should_select_nested_prefetch_and_select_related_fields(): # item = Item.objects.create(name='bar_item') # Item.objects.create(name='bar', parent=parent, item=item) # Item.objects.create(name='foobar', item=parent) - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items(name: "foobar") { id @@ -317,11 +358,12 @@ def test_should_select_nested_prefetch_and_select_related_fields(): } } } - ''') - qs = Item.objects.filter(name='foobar') + """, + ) + qs = Item.objects.filter(name="foobar") items = gql_optimizer.query(qs, info) - optimized_items = qs.select_related('item').prefetch_related( - Prefetch('item__children', queryset=Item.objects.select_related('item')), + optimized_items = qs.select_related("item").prefetch_related( + Prefetch("item__children", queryset=Item.objects.select_related("item")), ) assert_query_equality(items, optimized_items) @@ -330,7 +372,9 @@ def test_should_select_nested_prefetch_and_select_related_fields(): def test_should_fetch_fields_of_related_field(): # parent = Item.objects.create(name='foo') # Item.objects.create(name='bar', parent=parent) - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items(name: "bar") { id @@ -339,10 +383,11 @@ def test_should_fetch_fields_of_related_field(): } } } - ''') - qs = Item.objects.filter(name='bar') + """, + ) + qs = Item.objects.filter(name="bar") items = gql_optimizer.query(qs, info) - optimized_items = qs.select_related('parent').only('id', 'parent__id') + optimized_items = qs.select_related("parent").only("id", "parent__id") assert_query_equality(items, optimized_items) @@ -350,7 +395,9 @@ def test_should_fetch_fields_of_related_field(): def test_should_fetch_fields_of_prefetched_field(): # parent = Item.objects.create(name='foo') # Item.objects.create(name='bar', parent=parent) - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items(name: "foo") { id @@ -360,11 +407,12 @@ def test_should_fetch_fields_of_prefetched_field(): } } } - ''') - qs = Item.objects.filter(name='foo') + """, + ) + qs = Item.objects.filter(name="foo") items = gql_optimizer.query(qs, info) optimized_items = qs.prefetch_related( - Prefetch('children', queryset=Item.objects.only('id', 'parent__id')), + Prefetch("children", queryset=Item.objects.only("id", "parent__id")), ) assert_query_equality(items, optimized_items) @@ -373,7 +421,9 @@ def test_should_fetch_fields_of_prefetched_field(): def test_should_fetch_child_model_field_for_interface_field(): # Item.objects.create(name='foo') # ExtraDetailedItem.objects.create(name='foo', extra_detail='test') - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items(name: "foo") { id @@ -382,42 +432,44 @@ def test_should_fetch_child_model_field_for_interface_field(): } } } - ''') - qs = Item.objects.filter(name='foo') + """, + ) + qs = Item.objects.filter(name="foo") items = gql_optimizer.query(qs, info) - optimized_items = ( - qs - .select_related('detaileditem__extradetaileditem') - .only('id', 'detaileditem__extradetaileditem__extra_detail') + optimized_items = qs.select_related("detaileditem__extradetaileditem").only( + "id", "detaileditem__extradetaileditem__extra_detail" ) assert_query_equality(items, optimized_items) -@pytest.mark.skip(reason='will be tested in the future') +@pytest.mark.skip(reason="will be tested in the future") # @pytest.mark.django_db def test_should_fetch_field_of_child_model_when_parent_has_no_optimized_field(): # Item.objects.create(name='foo') # DetailedItem.objects.create(name='foo', item_type='test') - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items(name: "foo") { id item_type } } - ''') - qs = Item.objects.filter(name='foo') + """, + ) + qs = Item.objects.filter(name="foo") items = gql_optimizer.query(qs, info) - optimized_items = ( - qs - .select_related('detaileditem') - .only('id', 'detaileditem__item_type') + optimized_items = qs.select_related("detaileditem").only( + "id", "detaileditem__item_type" ) assert_query_equality(items, optimized_items) def test_should_fetch_field_inside_interface_fragment(): - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items(name: "foo") { id @@ -426,19 +478,20 @@ def test_should_fetch_field_inside_interface_fragment(): } } } - ''') - qs = Item.objects.filter(name='foo') + """, + ) + qs = Item.objects.filter(name="foo") items = gql_optimizer.query(qs, info) - optimized_items = ( - qs - .select_related('detaileditem') - .only('id', 'detaileditem__detail') + optimized_items = qs.select_related("detaileditem").only( + "id", "detaileditem__detail" ) assert_query_equality(items, optimized_items) def test_should_use_nested_prefetch_related_while_also_selecting_only_required_fields(): - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items(name: "foo") { children { @@ -448,16 +501,17 @@ def test_should_use_nested_prefetch_related_while_also_selecting_only_required_f } } } - ''') - qs = Item.objects.filter(name='foo') + """, + ) + qs = Item.objects.filter(name="foo") items = gql_optimizer.query(qs, info) optimized_items = qs.prefetch_related( Prefetch( - 'children', - queryset=Item.objects.only('id', 'parent_id').prefetch_related( + "children", + queryset=Item.objects.only("id", "parent_id").prefetch_related( Prefetch( - 'children', - queryset=Item.objects.only('id', 'parent_id'), + "children", + queryset=Item.objects.only("id", "parent_id"), ) ), ), @@ -467,7 +521,9 @@ def test_should_use_nested_prefetch_related_while_also_selecting_only_required_f @pytest.mark.django_db def test_should_check_reverse_relations_add_foreign_key(): - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items { otmItems { @@ -475,22 +531,25 @@ def test_should_check_reverse_relations_add_foreign_key(): } } } - ''') + """, + ) qs = Item.objects.all() items = gql_optimizer.query(qs, info) optimized_items = qs.prefetch_related( Prefetch( - 'otm_items', - queryset=RelatedOneToManyItem.objects.only('id', 'item_id'), + "otm_items", + queryset=RelatedOneToManyItem.objects.only("id", "item_id"), ), ) assert_query_equality(items, optimized_items) # When the query is not optimized, there will be an additional queries for i in range(3): - the_item = Item.objects.create(name='foo') + the_item = Item.objects.create(name="foo") for k in range(3): - RelatedOneToManyItem.objects.create(name='bar{}{}'.format(i, k), item=the_item) + RelatedOneToManyItem.objects.create( + name="bar{}{}".format(i, k), item=the_item + ) with CaptureQueriesContext(connection) as expected_query_capture: for i in items: @@ -508,15 +567,18 @@ def test_should_check_reverse_relations_add_foreign_key(): # @pytest.mark.django_db def test_should_only_use_the_only_and_not_select_related(): - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { otherItems { id name } } - ''') + """, + ) qs = OtherItem.objects.all() items = gql_optimizer.query(qs, info) - optimized_items = qs.only('id', 'name') + optimized_items = qs.only("id", "name") assert_query_equality(items, optimized_items) diff --git a/tests/test_relay.py b/tests/test_relay.py index 1de193f..1e003f4 100644 --- a/tests/test_relay.py +++ b/tests/test_relay.py @@ -12,8 +12,9 @@ @pytest.mark.django_db def test_should_return_valid_result_in_a_relay_query(): - Item.objects.create(id=7, name='foo') - result = schema.execute(''' + Item.objects.create(id=7, name="foo") + result = schema.execute( + """ query { relayItems { edges { @@ -25,15 +26,21 @@ def test_should_return_valid_result_in_a_relay_query(): } } } - ''') + """ + ) assert not result.errors - assert result.data['relayItems']['edges'][0]['node']['id'] == 'SXRlbU5vZGU6Nw==' - assert result.data['relayItems']['edges'][0]['node']['parentId'] == 'SXRlbU5vZGU6Tm9uZQ==' - assert result.data['relayItems']['edges'][0]['node']['name'] == 'foo' + assert result.data["relayItems"]["edges"][0]["node"]["id"] == "SXRlbU5vZGU6Nw==" + assert ( + result.data["relayItems"]["edges"][0]["node"]["parentId"] + == "SXRlbU5vZGU6Tm9uZQ==" + ) + assert result.data["relayItems"]["edges"][0]["node"]["name"] == "foo" def test_should_reduce_number_of_queries_in_relay_schema_by_using_select_related(): - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { relayItems { edges { @@ -47,15 +54,18 @@ def test_should_reduce_number_of_queries_in_relay_schema_by_using_select_related } } } - ''') - qs = Item.objects.filter(name='bar') + """, + ) + qs = Item.objects.filter(name="bar") items = gql_optimizer.query(qs, info) - optimized_items = qs.select_related('parent') + optimized_items = qs.select_related("parent") assert_query_equality(items, optimized_items) def test_should_reduce_number_of_queries_in_relay_schema_by_using_prefetch_related(): - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { relayItems { edges { @@ -70,10 +80,11 @@ def test_should_reduce_number_of_queries_in_relay_schema_by_using_prefetch_relat } } } - ''') - qs = Item.objects.filter(name='foo') + """, + ) + qs = Item.objects.filter(name="foo") items = gql_optimizer.query(qs, info) - optimized_items = qs.prefetch_related('children') + optimized_items = qs.prefetch_related("children") assert_query_equality(items, optimized_items) @@ -85,7 +96,9 @@ def test_should_optimize_query_by_only_requesting_id_field(): # When the ConnectionField is used, it will throw the following error: # Expected value of type "ItemNode" but got: Item_Deferred_item_id_parent_id. return - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { relayItems { edges { @@ -95,19 +108,21 @@ def test_should_optimize_query_by_only_requesting_id_field(): } } } - ''') - qs = Item.objects.filter(name='foo') + """, + ) + qs = Item.objects.filter(name="foo") items = gql_optimizer.query(qs, info) - optimized_items = qs.only('id') + optimized_items = qs.only("id") assert_query_equality(items, optimized_items) @pytest.mark.django_db def test_should_work_fine_with_page_info_field(): - Item.objects.create(id=7, name='foo') - Item.objects.create(id=13, name='bar') - Item.objects.create(id=17, name='foobar') - result = schema.execute(''' + Item.objects.create(id=7, name="foo") + Item.objects.create(id=13, name="bar") + Item.objects.create(id=17, name="foobar") + result = schema.execute( + """ query { relayItems(first: 2) { pageInfo { @@ -120,17 +135,19 @@ def test_should_work_fine_with_page_info_field(): } } } - ''') + """ + ) assert not result.errors - assert result.data['relayItems']['pageInfo']['hasNextPage'] is True + assert result.data["relayItems"]["pageInfo"]["hasNextPage"] is True @pytest.mark.django_db def test_should_work_fine_with_page_info_field_below_edges_field_when_only_optimization_is_aborted(): - Item.objects.create(id=7, name='foo') - Item.objects.create(id=13, name='bar') - Item.objects.create(id=17, name='foobar') - result = schema.execute(''' + Item.objects.create(id=7, name="foo") + Item.objects.create(id=13, name="bar") + Item.objects.create(id=17, name="foobar") + result = schema.execute( + """ query { relayItems(first: 2) { edges { @@ -144,17 +161,19 @@ def test_should_work_fine_with_page_info_field_below_edges_field_when_only_optim } } } - ''') + """ + ) assert not result.errors - assert result.data['relayItems']['pageInfo']['hasNextPage'] is True + assert result.data["relayItems"]["pageInfo"]["hasNextPage"] is True @pytest.mark.django_db def test_should_resolve_nested_variables(): - item_1 = Item.objects.create(id=7, name='foo') - item_1.children.create(id=8, name='bar') - variables = {'itemsFirst': 1, 'childrenFirst': 1} - result = schema.execute(''' + item_1 = Item.objects.create(id=7, name="foo") + item_1.children.create(id=8, name="bar") + variables = {"itemsFirst": 1, "childrenFirst": 1} + result = schema.execute( + """ query Query($itemsFirst: Int!, $childrenFirst: Int!) { relayItems(first: $itemsFirst) { edges { @@ -171,11 +190,13 @@ def test_should_resolve_nested_variables(): } } } - ''', variables=variables) + """, + variables=variables, + ) assert not result.errors - item_edges = result.data['relayItems']['edges'] + item_edges = result.data["relayItems"]["edges"] assert len(item_edges) == 1 - child_edges = item_edges[0]['node']['relayAllChildren']['edges'][0] + child_edges = item_edges[0]["node"]["relayAllChildren"]["edges"][0] assert len(child_edges) == 1 - assert child_edges['node']['id'] == 'SXRlbU5vZGU6OA==' - assert child_edges['node']['parentId'] == 'SXRlbU5vZGU6Nw==' + assert child_edges["node"]["id"] == "SXRlbU5vZGU6OA==" + assert child_edges["node"]["parentId"] == "SXRlbU5vZGU6Nw==" diff --git a/tests/test_resolver.py b/tests/test_resolver.py index f55b108..7a063a4 100644 --- a/tests/test_resolver.py +++ b/tests/test_resolver.py @@ -16,7 +16,9 @@ def test_should_optimize_non_django_field_if_it_has_an_optimization_hint_in_the_ # parent = Item.objects.create(name='foo') # Item.objects.create(name='bar', parent=parent) # Item.objects.create(name='foobar', parent=parent) - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items(name: "foo") { id @@ -24,13 +26,14 @@ def test_should_optimize_non_django_field_if_it_has_an_optimization_hint_in_the_ childrenNames } } - ''') - qs = Item.objects.filter(name='foo') + """, + ) + qs = Item.objects.filter(name="foo") items = gql_optimizer.query(qs, info) optimized_items = qs.prefetch_related( Prefetch( - 'children', - queryset=Item.objects.only('id', 'parent_id'), + "children", + queryset=Item.objects.only("id", "parent_id"), ), ) assert_query_equality(items, optimized_items) @@ -41,7 +44,9 @@ def test_should_optimize_with_prefetch_related_as_a_string(): # parent = Item.objects.create(name='foo') # Item.objects.create(name='bar', parent=parent) # Item.objects.create(name='foobar', parent=parent) - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items(name: "foo") { id @@ -49,10 +54,11 @@ def test_should_optimize_with_prefetch_related_as_a_string(): auxChildrenNames } } - ''') - qs = Item.objects.filter(name='foo') + """, + ) + qs = Item.objects.filter(name="foo") items = gql_optimizer.query(qs, info) - optimized_items = qs.prefetch_related('children') + optimized_items = qs.prefetch_related("children") assert_query_equality(items, optimized_items) @@ -60,7 +66,9 @@ def test_should_optimize_with_prefetch_related_as_a_function(): # parent = Item.objects.create(name='foo') # Item.objects.create(name='bar', parent=parent) # Item.objects.create(name='foobar', parent=parent) - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items(name: "foo") { id @@ -71,20 +79,21 @@ def test_should_optimize_with_prefetch_related_as_a_function(): } } } - ''') - qs = Item.objects.filter(name='foo') + """, + ) + qs = Item.objects.filter(name="foo") items = gql_optimizer.query(qs, info) optimized_items = qs.prefetch_related( Prefetch( - 'children', - queryset=Item.objects.filter(name='bar'), - to_attr='gql_filtered_children_bar', + "children", + queryset=Item.objects.filter(name="bar"), + to_attr="gql_filtered_children_bar", ), ) assert_query_equality(items, optimized_items) -QUERY_CONNECTION_NESTED_INPUT_OBJECT = ''' +QUERY_CONNECTION_NESTED_INPUT_OBJECT = """ query($filters: ItemFilterInput) { items(name: "foo") { id @@ -99,13 +108,16 @@ def test_should_optimize_with_prefetch_related_as_a_function(): } } } -''' +""" -@pytest.mark.parametrize("variables, expected_gte", [ - ({"filters": {'value': {'gte': 11}}}, 11), - ({}, 0), -]) +@pytest.mark.parametrize( + "variables, expected_gte", + [ + ({"filters": {"value": {"gte": 11}}}, 11), + ({}, 0), + ], +) @pytest.mark.django_db def test_should_optimize_with_prefetch_related_as_a_function_with_object_input( variables, expected_gte @@ -120,9 +132,9 @@ def test_should_optimize_with_prefetch_related_as_a_function_with_object_input( optimized_items = Item.objects.prefetch_related( Prefetch( - 'children', - queryset=Item.objects.only('id', 'value').filter(value__gte=expected_gte), - to_attr='gql_custom_filtered_children', + "children", + queryset=Item.objects.only("id", "value").filter(value__gte=expected_gte), + to_attr="gql_custom_filtered_children", ), ) @@ -132,10 +144,11 @@ def test_should_optimize_with_prefetch_related_as_a_function_with_object_input( @pytest.mark.django_db def test_should_return_valid_result_with_prefetch_related_as_a_function(): - parent = Item.objects.create(id=1, name='foo') - Item.objects.create(id=2, name='bar', parent=parent) - Item.objects.create(id=3, name='foobar', parent=parent) - result = schema.execute(''' + parent = Item.objects.create(id=1, name="foo") + Item.objects.create(id=2, name="bar", parent=parent) + Item.objects.create(id=3, name="foobar", parent=parent) + result = schema.execute( + """ query { items(name: "foo") { id @@ -147,18 +160,22 @@ def test_should_return_valid_result_with_prefetch_related_as_a_function(): } } } - ''') + """ + ) assert not result.errors - assert result.data['items'][0]['filteredChildren'][0]['id'] == 'SXRlbVR5cGU6Mg==' - assert result.data['items'][0]['filteredChildren'][0]['parentId'] == 'SXRlbVR5cGU6MQ==' + assert result.data["items"][0]["filteredChildren"][0]["id"] == "SXRlbVR5cGU6Mg==" + assert ( + result.data["items"][0]["filteredChildren"][0]["parentId"] == "SXRlbVR5cGU6MQ==" + ) @pytest.mark.django_db def test_should_return_valid_result_with_prefetch_related_as_a_function_using_variable(): - parent = Item.objects.create(id=1, name='foo') - Item.objects.create(id=2, name='bar', parent=parent) - Item.objects.create(id=3, name='foobar', parent=parent) - result = schema.execute(''' + parent = Item.objects.create(id=1, name="foo") + Item.objects.create(id=2, name="bar", parent=parent) + Item.objects.create(id=3, name="foobar", parent=parent) + result = schema.execute( + """ query Foo ($name: String!) { items(name: "foo") { id @@ -170,7 +187,11 @@ def test_should_return_valid_result_with_prefetch_related_as_a_function_using_va } } } - ''', variables={'name': 'bar'}) + """, + variables={"name": "bar"}, + ) assert not result.errors - assert result.data['items'][0]['filteredChildren'][0]['id'] == 'SXRlbVR5cGU6Mg==' - assert result.data['items'][0]['filteredChildren'][0]['parentId'] == 'SXRlbVR5cGU6MQ==' + assert result.data["items"][0]["filteredChildren"][0]["id"] == "SXRlbVR5cGU6Mg==" + assert ( + result.data["items"][0]["filteredChildren"][0]["parentId"] == "SXRlbVR5cGU6MQ==" + ) diff --git a/tests/test_types.py b/tests/test_types.py index 42b7b4e..345efd5 100644 --- a/tests/test_types.py +++ b/tests/test_types.py @@ -8,12 +8,13 @@ @pytest.mark.django_db -@patch('graphene_django_optimizer.types.query', - return_value=SomeOtherItem.objects) +@patch("graphene_django_optimizer.types.query", return_value=SomeOtherItem.objects) def test_should_optimize_the_single_node(mocked_optimizer): - SomeOtherItem.objects.create(pk=7, name='Hello') + SomeOtherItem.objects.create(pk=7, name="Hello") - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query ItemDetails { someOtherItems(id: $id) { id @@ -23,23 +24,26 @@ def test_should_optimize_the_single_node(mocked_optimizer): } } } - ''') + """, + ) - info.return_type = schema.get_type('SomeOtherItemType') + info.return_type = schema.get_type("SomeOtherItemType") result = SomeOtherItemType.get_node(info, 7) - assert result, 'Expected the item to be found and returned' - assert result.pk == 7, 'The item is not the correct one' + assert result, "Expected the item to be found and returned" + assert result.pk == 7, "The item is not the correct one" mocked_optimizer.assert_called_once_with(SomeOtherItem.objects, info) @pytest.mark.django_db -@patch('graphene_django_optimizer.types.query') +@patch("graphene_django_optimizer.types.query") def test_should_return_none_when_node_is_not_resolved(mocked_optimizer): SomeOtherItem.objects.create(id=7) - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { someOtherItems(id: $id) { id @@ -50,9 +54,10 @@ def test_should_return_none_when_node_is_not_resolved(mocked_optimizer): } } } - ''') + """, + ) - info.return_type = schema.get_type('SomeOtherItemType') + info.return_type = schema.get_type("SomeOtherItemType") qs = SomeOtherItem.objects mocked_optimizer.return_value = qs @@ -61,11 +66,13 @@ def test_should_return_none_when_node_is_not_resolved(mocked_optimizer): @pytest.mark.django_db -@patch('graphene_django_optimizer.types.query') +@patch("graphene_django_optimizer.types.query") def test_mutating_should_not_optimize(mocked_optimizer): Item.objects.create(id=7) - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query { items(id: $id) { id @@ -76,22 +83,24 @@ def test_mutating_should_not_optimize(mocked_optimizer): } } } - ''') + """, + ) - info.return_type = schema.get_type('SomeOtherItemType') - result = DummyItemMutation.mutate(info, to_global_id('ItemNode', 7)) + info.return_type = schema.get_type("SomeOtherItemType") + result = DummyItemMutation.mutate(info, to_global_id("ItemNode", 7)) assert result assert result.pk == 7 assert mocked_optimizer.call_count == 0 @pytest.mark.django_db -@patch('graphene_django_optimizer.types.query', - return_value=SomeOtherItem.objects) +@patch("graphene_django_optimizer.types.query", return_value=SomeOtherItem.objects) def test_should_optimize_the_queryset(mocked_optimizer): - SomeOtherItem.objects.create(pk=7, name='Hello') + SomeOtherItem.objects.create(pk=7, name="Hello") - info = create_resolve_info(schema, ''' + info = create_resolve_info( + schema, + """ query ItemDetails { someOtherItems(id: $id) { id @@ -101,13 +110,14 @@ def test_should_optimize_the_queryset(mocked_optimizer): } } } - ''') + """, + ) - info.return_type = schema.get_type('SomeOtherItemType') + info.return_type = schema.get_type("SomeOtherItemType") qs = SomeOtherItem.objects.filter(pk=7) result = SomeOtherItemType.get_queryset(qs, info).get() - assert result, 'Expected the item to be found and returned' - assert result.pk == 7, 'The item is not the correct one' + assert result, "Expected the item to be found and returned" + assert result.pk == 7, "The item is not the correct one" mocked_optimizer.assert_called_once_with(qs, info) diff --git a/tests/test_utils.py b/tests/test_utils.py index 18818c0..5f98995 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -3,7 +3,9 @@ def assert_query_equality(left_query, right_query): assert str(left_query.query) == str(right_query.query) - assert len(left_query._prefetch_related_lookups) == len(right_query._prefetch_related_lookups) + assert len(left_query._prefetch_related_lookups) == len( + right_query._prefetch_related_lookups + ) for (i, lookup) in enumerate(left_query._prefetch_related_lookups): right_lookup = right_query._prefetch_related_lookups[i] if isinstance(lookup, Prefetch) and isinstance(right_lookup, Prefetch):