From add11cb9a62d094969c1accc2f356cd55fd9af4a Mon Sep 17 00:00:00 2001 From: Kien Dang Date: Sat, 5 Aug 2023 13:42:00 +0800 Subject: [PATCH 01/15] Use ruff in pre-commit --- .pre-commit-config.yaml | 12 +++------ .ruff.toml | 20 ++++++++++++++ examples/cookbook/cookbook/recipes/models.py | 4 ++- graphene_django/debug/middleware.py | 1 - graphene_django/filter/tests/conftest.py | 3 +-- graphene_django/filter/tests/test_fields.py | 6 ++--- .../filter/tests/test_range_filter.py | 2 -- graphene_django/filter/utils.py | 7 +++-- graphene_django/forms/tests/test_converter.py | 1 - graphene_django/forms/tests/test_mutation.py | 1 - .../tests/test_field_converter.py | 1 - .../rest_framework/tests/test_mutation.py | 2 +- graphene_django/tests/issues/test_520.py | 6 ----- graphene_django/tests/test_fields.py | 2 +- graphene_django/tests/test_get_queryset.py | 1 - graphene_django/tests/test_query.py | 26 +++++++++---------- graphene_django/tests/test_views.py | 9 ++++--- graphene_django/types.py | 5 ++-- 18 files changed, 58 insertions(+), 51 deletions(-) create mode 100644 .ruff.toml diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 14da2e86d..52e9b5420 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -15,16 +15,12 @@ repos: - --autofix - id: trailing-whitespace exclude: README.md -- repo: https://github.com/asottile/pyupgrade - rev: v3.3.2 - hooks: - - id: pyupgrade - args: [--py38-plus] - repo: https://github.com/psf/black rev: 23.3.0 hooks: - id: black -- repo: https://github.com/PyCQA/flake8 - rev: 6.0.0 +- repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.0.282 hooks: - - id: flake8 + - id: ruff + args: [--fix, --exit-non-zero-on-fix] diff --git a/.ruff.toml b/.ruff.toml new file mode 100644 index 000000000..aa08a7bc0 --- /dev/null +++ b/.ruff.toml @@ -0,0 +1,20 @@ +select = [ + "E", # pycodestyle + "W", # pycodestyle + "F", # pyflake +] + +ignore = [ + "E501", # line-too-long +] + +exclude = [ + "**/docs", +] + +target-version = "py38" + +[per-file-ignores] +# Ignore unused imports (F401) in these files +"__init__.py" = ["F401"] +"graphene_django/compat.py" = ["F401"] diff --git a/examples/cookbook/cookbook/recipes/models.py b/examples/cookbook/cookbook/recipes/models.py index 0bfb43433..03da594c0 100644 --- a/examples/cookbook/cookbook/recipes/models.py +++ b/examples/cookbook/cookbook/recipes/models.py @@ -6,7 +6,9 @@ class Recipe(models.Model): title = models.CharField(max_length=100) instructions = models.TextField() - __unicode__ = lambda self: self.title + + def __unicode__(self): + return self.title class RecipeIngredient(models.Model): diff --git a/graphene_django/debug/middleware.py b/graphene_django/debug/middleware.py index d3052a14a..8c7df6c02 100644 --- a/graphene_django/debug/middleware.py +++ b/graphene_django/debug/middleware.py @@ -1,6 +1,5 @@ from django.db import connections -from promise import Promise from .sql.tracking import unwrap_cursor, wrap_cursor from .exception.formating import wrap_exception diff --git a/graphene_django/filter/tests/conftest.py b/graphene_django/filter/tests/conftest.py index f8a65d7b2..2669c3d84 100644 --- a/graphene_django/filter/tests/conftest.py +++ b/graphene_django/filter/tests/conftest.py @@ -3,13 +3,12 @@ from django.db import models from django.db.models.query import QuerySet -from django_filters import filters from django_filters import FilterSet import graphene from graphene.relay import Node from graphene_django import DjangoObjectType from graphene_django.utils import DJANGO_FILTER_INSTALLED -from graphene_django.filter import ArrayFilter, ListFilter +from graphene_django.filter import ArrayFilter from ...compat import ArrayField diff --git a/graphene_django/filter/tests/test_fields.py b/graphene_django/filter/tests/test_fields.py index bee3c6cf4..7c0fd3be6 100644 --- a/graphene_django/filter/tests/test_fields.py +++ b/graphene_django/filter/tests/test_fields.py @@ -222,7 +222,7 @@ class Query(ObjectType): reporter = Field(ReporterFilterNode) article = Field(ArticleFilterNode) - schema = Schema(query=Query) + Schema(query=Query) articles_field = ReporterFilterNode._meta.fields["articles"].get_type() assert_arguments(articles_field, "headline", "reporter") assert_not_orderable(articles_field) @@ -294,7 +294,7 @@ class Query(ObjectType): reporter = Field(ReporterFilterNode) article = Field(ArticleFilterNode) - schema = Schema(query=Query) + Schema(query=Query) articles_field = ReporterFilterNode._meta.fields["articles"].get_type() assert_arguments(articles_field, "headline", "reporter") assert_not_orderable(articles_field) @@ -1186,7 +1186,7 @@ class Query(ObjectType): first_name="Adam", last_name="Doe", email="adam@doe.com" ) - article_2 = Article.objects.create( + Article.objects.create( headline="Good Bye", reporter=reporter_2, editor=reporter_2, diff --git a/graphene_django/filter/tests/test_range_filter.py b/graphene_django/filter/tests/test_range_filter.py index 6227a7071..6c770f1a2 100644 --- a/graphene_django/filter/tests/test_range_filter.py +++ b/graphene_django/filter/tests/test_range_filter.py @@ -1,8 +1,6 @@ import json import pytest -from django_filters import FilterSet -from django_filters import rest_framework as filters from graphene import ObjectType, Schema from graphene.relay import Node from graphene_django import DjangoObjectType diff --git a/graphene_django/filter/utils.py b/graphene_django/filter/utils.py index ebd2a0041..b48d317a7 100644 --- a/graphene_django/filter/utils.py +++ b/graphene_django/filter/utils.py @@ -1,8 +1,7 @@ import graphene from django import forms -from django_filters.utils import get_model_field, get_field_parts -from django_filters.filters import Filter, BaseCSVFilter -from .filters import ArrayFilter, ListFilter, RangeFilter, TypedFilter +from django_filters.utils import get_model_field +from .filters import ListFilter, RangeFilter, TypedFilter from .filterset import custom_filterset_factory, setup_filterset from ..forms import GlobalIDFormField, GlobalIDMultipleChoiceField @@ -50,7 +49,7 @@ def get_filtering_args_from_filterset(filterset_class, type): ): # Get the filter field for filters that are no explicitly declared. if filter_type == "isnull": - field = graphene.Boolean(required=required) + graphene.Boolean(required=required) else: model_field = get_model_field(model, filter_field.field_name) diff --git a/graphene_django/forms/tests/test_converter.py b/graphene_django/forms/tests/test_converter.py index b61227b77..f094f8533 100644 --- a/graphene_django/forms/tests/test_converter.py +++ b/graphene_django/forms/tests/test_converter.py @@ -1,7 +1,6 @@ from django import forms from pytest import raises -import graphene from graphene import ( String, Int, diff --git a/graphene_django/forms/tests/test_mutation.py b/graphene_django/forms/tests/test_mutation.py index 14c407c24..d71328dd2 100644 --- a/graphene_django/forms/tests/test_mutation.py +++ b/graphene_django/forms/tests/test_mutation.py @@ -1,4 +1,3 @@ -import pytest from django import forms from django.core.exceptions import ValidationError from pytest import raises diff --git a/graphene_django/rest_framework/tests/test_field_converter.py b/graphene_django/rest_framework/tests/test_field_converter.py index 8da8377c0..92ddb9e53 100644 --- a/graphene_django/rest_framework/tests/test_field_converter.py +++ b/graphene_django/rest_framework/tests/test_field_converter.py @@ -2,7 +2,6 @@ import graphene from django.db import models -from graphene import InputObjectType from pytest import raises from rest_framework import serializers diff --git a/graphene_django/rest_framework/tests/test_mutation.py b/graphene_django/rest_framework/tests/test_mutation.py index 98cd11d0a..fc44e19fb 100644 --- a/graphene_django/rest_framework/tests/test_mutation.py +++ b/graphene_django/rest_framework/tests/test_mutation.py @@ -250,7 +250,7 @@ class Meta: model_operations = ["update"] with raises(Exception) as exc: - result = InvalidModelMutation.mutate_and_get_payload( + InvalidModelMutation.mutate_and_get_payload( None, mock_info(), **{"cool_name": "Narf"} ) diff --git a/graphene_django/tests/issues/test_520.py b/graphene_django/tests/issues/test_520.py index 4e55f9655..2aed351ac 100644 --- a/graphene_django/tests/issues/test_520.py +++ b/graphene_django/tests/issues/test_520.py @@ -1,18 +1,12 @@ # https://github.com/graphql-python/graphene-django/issues/520 -import datetime from django import forms import graphene -from graphene import Field, ResolveInfo -from graphene.types.inputobjecttype import InputObjectType -from pytest import raises -from pytest import mark from rest_framework import serializers -from ...types import DjangoObjectType from ...rest_framework.models import MyFakeModel from ...rest_framework.mutation import SerializerMutation from ...forms.mutation import DjangoFormMutation diff --git a/graphene_django/tests/test_fields.py b/graphene_django/tests/test_fields.py index 8c7b78d36..33b565a97 100644 --- a/graphene_django/tests/test_fields.py +++ b/graphene_django/tests/test_fields.py @@ -22,7 +22,7 @@ class TestType(ObjectType): foo = String() with pytest.raises(AssertionError): - list_field = DjangoListField(TestType) + DjangoListField(TestType) def test_only_import_paths(self): list_field = DjangoListField("graphene_django.tests.schema.Human") diff --git a/graphene_django/tests/test_get_queryset.py b/graphene_django/tests/test_get_queryset.py index 99f50c7ad..cd1121fcb 100644 --- a/graphene_django/tests/test_get_queryset.py +++ b/graphene_django/tests/test_get_queryset.py @@ -5,7 +5,6 @@ from graphql_relay import to_global_id -from ..fields import DjangoConnectionField from ..types import DjangoObjectType from .models import Article, Reporter, FilmDetails, Film diff --git a/graphene_django/tests/test_query.py b/graphene_django/tests/test_query.py index 91bacbdf3..4a75a882d 100644 --- a/graphene_django/tests/test_query.py +++ b/graphene_django/tests/test_query.py @@ -517,7 +517,7 @@ def resolve_films(self, info, **args): ).distinct() f = Film.objects.create() - fd = FilmDetails.objects.create(location="Berlin", film=f) + FilmDetails.objects.create(location="Berlin", film=f) schema = graphene.Schema(query=Query) query = """ @@ -640,7 +640,7 @@ class Meta: class Query(graphene.ObjectType): all_reporters = DjangoConnectionField(ReporterType) - r = Reporter.objects.create( + Reporter.objects.create( first_name="John", last_name="Doe", email="johndoe@example.com", a_choice=1 ) @@ -682,7 +682,7 @@ class Query(graphene.ObjectType): assert Query.all_reporters.max_limit == 100 - r = Reporter.objects.create( + Reporter.objects.create( first_name="John", last_name="Doe", email="johndoe@example.com", a_choice=1 ) @@ -724,7 +724,7 @@ class Query(graphene.ObjectType): assert Query.all_reporters.max_limit == 100 - r = Reporter.objects.create( + Reporter.objects.create( first_name="John", last_name="Doe", email="johndoe@example.com", a_choice=1 ) @@ -788,7 +788,7 @@ def resolve_all_reporters(self, info, **args): def test_should_query_connectionfields_with_last(): - r = Reporter.objects.create( + Reporter.objects.create( first_name="John", last_name="Doe", email="johndoe@example.com", a_choice=1 ) @@ -825,11 +825,11 @@ def resolve_all_reporters(self, info, **args): def test_should_query_connectionfields_with_manager(): - r = Reporter.objects.create( + Reporter.objects.create( first_name="John", last_name="Doe", email="johndoe@example.com", a_choice=1 ) - r = Reporter.objects.create( + Reporter.objects.create( first_name="John", last_name="NotDoe", email="johndoe@example.com", a_choice=1 ) @@ -1369,10 +1369,10 @@ class Query(graphene.ObjectType): def test_should_resolve_get_queryset_connectionfields(): - reporter_1 = Reporter.objects.create( + Reporter.objects.create( first_name="John", last_name="Doe", email="johndoe@example.com", a_choice=1 ) - reporter_2 = CNNReporter.objects.create( + CNNReporter.objects.create( first_name="Some", last_name="Guy", email="someguy@cnn.com", @@ -1414,10 +1414,10 @@ class Query(graphene.ObjectType): def test_connection_should_limit_after_to_list_length(): - reporter_1 = Reporter.objects.create( + Reporter.objects.create( first_name="John", last_name="Doe", email="johndoe@example.com", a_choice=1 ) - reporter_2 = Reporter.objects.create( + Reporter.objects.create( first_name="Some", last_name="Guy", email="someguy@cnn.com", a_choice=1 ) @@ -1710,7 +1710,7 @@ def resolve_films(root, info, **kwargs): """ schema = graphene.Schema(query=Query) - with django_assert_num_queries(3) as captured: + with django_assert_num_queries(3): result = schema.execute(query) assert not result.errors @@ -2022,7 +2022,7 @@ def resolve_person(self, info, name): schema = graphene.Schema(query=Query) person = Person.objects.create(name="Jane") - pets = [ + [ Pet.objects.create(name="Stray dog", age=1), Pet.objects.create(name="Jane's dog", owner=person, age=1), ] diff --git a/graphene_django/tests/test_views.py b/graphene_django/tests/test_views.py index 5cadefe7e..dcbd73934 100644 --- a/graphene_django/tests/test_views.py +++ b/graphene_django/tests/test_views.py @@ -6,7 +6,6 @@ from django.db import connection -from graphene_django.settings import graphene_settings from .models import Pet @@ -31,8 +30,12 @@ def response_json(response): return json.loads(response.content.decode()) -j = lambda **kwargs: json.dumps(kwargs) -jl = lambda **kwargs: json.dumps([kwargs]) +def j(**kwargs): + return json.dumps(kwargs) + + +def jl(**kwargs): + return json.dumps([kwargs]) def test_graphiql_is_enabled(client): diff --git a/graphene_django/types.py b/graphene_django/types.py index dec872373..5597e27b6 100644 --- a/graphene_django/types.py +++ b/graphene_django/types.py @@ -1,9 +1,10 @@ import warnings from collections import OrderedDict -from typing import Type +from typing import Type # noqa: F401 + +from django.db.models import Model # noqa: F401 import graphene -from django.db.models import Model from graphene.relay import Connection, Node from graphene.types.objecttype import ObjectType, ObjectTypeOptions from graphene.types.utils import yank_fields_from_attrs From 4da0841ec25ad6bbed07011e42f9053bdc41cb98 Mon Sep 17 00:00:00 2001 From: Kien Dang Date: Sat, 5 Aug 2023 13:44:50 +0800 Subject: [PATCH 02/15] Add pyupgrade --- .ruff.toml | 1 + graphene_django/converter.py | 4 +--- graphene_django/filter/tests/test_in_filter.py | 9 +++------ graphene_django/forms/converter.py | 4 ++-- graphene_django/registry.py | 4 +--- graphene_django/rest_framework/serializer_converter.py | 4 ++-- graphene_django/types.py | 10 +++++----- 7 files changed, 15 insertions(+), 21 deletions(-) diff --git a/.ruff.toml b/.ruff.toml index aa08a7bc0..b58fa1ec9 100644 --- a/.ruff.toml +++ b/.ruff.toml @@ -2,6 +2,7 @@ select = [ "E", # pycodestyle "W", # pycodestyle "F", # pyflake + "UP", # pyupgrade ] ignore = [ diff --git a/graphene_django/converter.py b/graphene_django/converter.py index f27119a64..eda3a02f9 100644 --- a/graphene_django/converter.py +++ b/graphene_django/converter.py @@ -161,9 +161,7 @@ def get_django_field_description(field): @singledispatch def convert_django_field(field, registry=None): raise Exception( - "Don't know how to convert the Django field {} ({})".format( - field, field.__class__ - ) + f"Don't know how to convert the Django field {field} ({field.__class__})" ) diff --git a/graphene_django/filter/tests/test_in_filter.py b/graphene_django/filter/tests/test_in_filter.py index a69d6f5e4..a64f7367e 100644 --- a/graphene_django/filter/tests/test_in_filter.py +++ b/graphene_django/filter/tests/test_in_filter.py @@ -348,9 +348,9 @@ def test_fk_id_in_filter(query): schema = Schema(query=query) - query = """ + query = f""" query {{ - articles (reporter_In: [{}, {}]) {{ + articles (reporter_In: [{john_doe.id}, {jean_bon.id}]) {{ edges {{ node {{ headline @@ -361,10 +361,7 @@ def test_fk_id_in_filter(query): }} }} }} - """.format( - john_doe.id, - jean_bon.id, - ) + """ result = schema.execute(query) assert not result.errors assert result.data["articles"]["edges"] == [ diff --git a/graphene_django/forms/converter.py b/graphene_django/forms/converter.py index 47eb51d5f..449ab2e2f 100644 --- a/graphene_django/forms/converter.py +++ b/graphene_django/forms/converter.py @@ -27,8 +27,8 @@ def get_form_field_description(field): @singledispatch def convert_form_field(field): raise ImproperlyConfigured( - "Don't know how to convert the Django form field %s (%s) " - "to Graphene type" % (field, field.__class__) + "Don't know how to convert the Django form field {} ({}) " + "to Graphene type".format(field, field.__class__) ) diff --git a/graphene_django/registry.py b/graphene_django/registry.py index 470863779..900feeb3c 100644 --- a/graphene_django/registry.py +++ b/graphene_django/registry.py @@ -8,9 +8,7 @@ def register(self, cls): assert issubclass( cls, DjangoObjectType - ), 'Only DjangoObjectTypes can be registered, received "{}"'.format( - cls.__name__ - ) + ), f'Only DjangoObjectTypes can be registered, received "{cls.__name__}"' assert cls._meta.registry == self, "Registry for a Model have to match." # assert self.get_type_for_model(cls._meta.model) == cls, ( # 'Multiple DjangoObjectTypes registered for "{}"'.format(cls._meta.model) diff --git a/graphene_django/rest_framework/serializer_converter.py b/graphene_django/rest_framework/serializer_converter.py index 1d850f031..a680de4a3 100644 --- a/graphene_django/rest_framework/serializer_converter.py +++ b/graphene_django/rest_framework/serializer_converter.py @@ -13,8 +13,8 @@ @singledispatch def get_graphene_type_from_serializer_field(field): raise ImproperlyConfigured( - "Don't know how to convert the serializer field %s (%s) " - "to Graphene type" % (field, field.__class__) + "Don't know how to convert the serializer field {} ({}) " + "to Graphene type".format(field, field.__class__) ) diff --git a/graphene_django/types.py b/graphene_django/types.py index 5597e27b6..ba8e36d4a 100644 --- a/graphene_django/types.py +++ b/graphene_django/types.py @@ -150,7 +150,7 @@ def __init_subclass_with_meta__( interfaces=(), convert_choices_to_enum=True, _meta=None, - **options + **options, ): assert is_valid_django_model(model), ( 'You need to pass a valid Django Model in {}.Meta, received "{}".' @@ -240,9 +240,9 @@ def __init_subclass_with_meta__( ) if connection is not None: - assert issubclass(connection, Connection), ( - "The connection must be a Connection. Received {}" - ).format(connection.__name__) + assert issubclass( + connection, Connection + ), f"The connection must be a Connection. Received {connection.__name__}" if not _meta: _meta = DjangoObjectTypeOptions(cls) @@ -273,7 +273,7 @@ def is_type_of(cls, root, info): if isinstance(root, cls): return True if not is_valid_django_model(root.__class__): - raise Exception(('Received incompatible instance "{}".').format(root)) + raise Exception(f'Received incompatible instance "{root}".') if cls._meta.model._meta.proxy: model = root._meta.model From 8a216b3461b202c8030c8fea050f3903636ee8ea Mon Sep 17 00:00:00 2001 From: Kien Dang Date: Sat, 5 Aug 2023 13:50:14 +0800 Subject: [PATCH 03/15] Add isort --- .ruff.toml | 7 +++++++ examples/cookbook-plain/cookbook/schema.py | 6 +++--- examples/cookbook-plain/cookbook/urls.py | 3 +-- examples/cookbook/cookbook/ingredients/schema.py | 3 ++- examples/cookbook/cookbook/recipes/schema.py | 3 ++- examples/cookbook/cookbook/schema.py | 6 +++--- examples/cookbook/cookbook/urls.py | 1 - examples/django_test_settings.py | 2 +- examples/starwars/schema.py | 8 +++++--- graphene_django/compat.py | 2 +- graphene_django/converter.py | 10 ++++++---- graphene_django/debug/middleware.py | 3 +-- graphene_django/debug/tests/test_query.py | 3 ++- graphene_django/debug/types.py | 2 +- graphene_django/fields.py | 2 -- graphene_django/filter/__init__.py | 1 + graphene_django/filter/fields.py | 2 +- graphene_django/filter/filters/__init__.py | 1 + graphene_django/filter/filters/global_id_filter.py | 1 - graphene_django/filter/filterset.py | 8 +++++--- graphene_django/filter/tests/conftest.py | 5 +++-- graphene_django/filter/tests/test_enum_filtering.py | 3 +-- graphene_django/filter/tests/test_fields.py | 2 +- graphene_django/filter/tests/test_in_filter.py | 8 +++++--- graphene_django/filter/tests/test_range_filter.py | 1 + graphene_django/filter/tests/test_typed_filter.py | 4 +--- graphene_django/filter/utils.py | 6 ++++-- graphene_django/forms/converter.py | 6 +++--- graphene_django/forms/forms.py | 1 - graphene_django/forms/tests/test_converter.py | 12 ++++++------ .../forms/tests/test_djangoinputobject.py | 6 +++--- graphene_django/forms/types.py | 5 ++--- .../management/commands/graphql_schema.py | 6 +++--- graphene_django/rest_framework/mutation.py | 3 +-- .../rest_framework/serializer_converter.py | 2 +- .../rest_framework/tests/test_field_converter.py | 3 ++- .../rest_framework/tests/test_mutation.py | 2 +- graphene_django/settings.py | 5 ++--- graphene_django/tests/issues/test_520.py | 5 ++--- graphene_django/tests/mutations.py | 1 - graphene_django/tests/test_command.py | 4 ++-- graphene_django/tests/test_fields.py | 2 +- graphene_django/tests/test_forms.py | 1 - graphene_django/tests/test_get_queryset.py | 6 ++---- graphene_django/tests/test_query.py | 8 ++++---- graphene_django/tests/test_types.py | 8 +++++--- graphene_django/tests/test_utils.py | 6 +++--- graphene_django/tests/test_views.py | 5 +---- graphene_django/utils/__init__.py | 2 +- graphene_django/utils/str_converters.py | 1 + graphene_django/utils/tests/test_testing.py | 6 +++--- graphene_django/views.py | 3 +-- 52 files changed, 109 insertions(+), 103 deletions(-) diff --git a/.ruff.toml b/.ruff.toml index b58fa1ec9..1e6ba8838 100644 --- a/.ruff.toml +++ b/.ruff.toml @@ -2,6 +2,7 @@ select = [ "E", # pycodestyle "W", # pycodestyle "F", # pyflake + "I", # isort "UP", # pyupgrade ] @@ -19,3 +20,9 @@ target-version = "py38" # Ignore unused imports (F401) in these files "__init__.py" = ["F401"] "graphene_django/compat.py" = ["F401"] + +[isort] +known-first-party = ["graphene", "graphene-django"] +known-local-folder = ["cookbook"] +force-wrap-aliases = true +combine-as-imports = true diff --git a/examples/cookbook-plain/cookbook/schema.py b/examples/cookbook-plain/cookbook/schema.py index bde937261..8c4e5e4ba 100644 --- a/examples/cookbook-plain/cookbook/schema.py +++ b/examples/cookbook-plain/cookbook/schema.py @@ -1,9 +1,9 @@ -import cookbook.ingredients.schema -import cookbook.recipes.schema import graphene - from graphene_django.debug import DjangoDebug +import cookbook.ingredients.schema +import cookbook.recipes.schema + class Query( cookbook.ingredients.schema.Query, diff --git a/examples/cookbook-plain/cookbook/urls.py b/examples/cookbook-plain/cookbook/urls.py index a64a87520..a5ec5de21 100644 --- a/examples/cookbook-plain/cookbook/urls.py +++ b/examples/cookbook-plain/cookbook/urls.py @@ -1,9 +1,8 @@ -from django.urls import path from django.contrib import admin +from django.urls import path from graphene_django.views import GraphQLView - urlpatterns = [ path("admin/", admin.site.urls), path("graphql/", GraphQLView.as_view(graphiql=True)), diff --git a/examples/cookbook/cookbook/ingredients/schema.py b/examples/cookbook/cookbook/ingredients/schema.py index 4ed9eff13..941f3797a 100644 --- a/examples/cookbook/cookbook/ingredients/schema.py +++ b/examples/cookbook/cookbook/ingredients/schema.py @@ -1,8 +1,9 @@ -from cookbook.ingredients.models import Category, Ingredient from graphene import Node from graphene_django.filter import DjangoFilterConnectionField from graphene_django.types import DjangoObjectType +from cookbook.ingredients.models import Category, Ingredient + # Graphene will automatically map the Category model's fields onto the CategoryNode. # This is configured in the CategoryNode's Meta class (as you can see below) diff --git a/examples/cookbook/cookbook/recipes/schema.py b/examples/cookbook/cookbook/recipes/schema.py index ea5ed38f1..c0cb13ae7 100644 --- a/examples/cookbook/cookbook/recipes/schema.py +++ b/examples/cookbook/cookbook/recipes/schema.py @@ -1,8 +1,9 @@ -from cookbook.recipes.models import Recipe, RecipeIngredient from graphene import Node from graphene_django.filter import DjangoFilterConnectionField from graphene_django.types import DjangoObjectType +from cookbook.recipes.models import Recipe, RecipeIngredient + class RecipeNode(DjangoObjectType): class Meta: diff --git a/examples/cookbook/cookbook/schema.py b/examples/cookbook/cookbook/schema.py index bde937261..8c4e5e4ba 100644 --- a/examples/cookbook/cookbook/schema.py +++ b/examples/cookbook/cookbook/schema.py @@ -1,9 +1,9 @@ -import cookbook.ingredients.schema -import cookbook.recipes.schema import graphene - from graphene_django.debug import DjangoDebug +import cookbook.ingredients.schema +import cookbook.recipes.schema + class Query( cookbook.ingredients.schema.Query, diff --git a/examples/cookbook/cookbook/urls.py b/examples/cookbook/cookbook/urls.py index 6f8a3021c..e72b383d7 100644 --- a/examples/cookbook/cookbook/urls.py +++ b/examples/cookbook/cookbook/urls.py @@ -3,7 +3,6 @@ from graphene_django.views import GraphQLView - urlpatterns = [ url(r"^admin/", admin.site.urls), url(r"^graphql$", GraphQLView.as_view(graphiql=True)), diff --git a/examples/django_test_settings.py b/examples/django_test_settings.py index 7b9886104..dcb1f6c80 100644 --- a/examples/django_test_settings.py +++ b/examples/django_test_settings.py @@ -1,5 +1,5 @@ -import sys import os +import sys ROOT_PATH = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, ROOT_PATH + "/examples/") diff --git a/examples/starwars/schema.py b/examples/starwars/schema.py index 4bc26e937..07bf9d286 100644 --- a/examples/starwars/schema.py +++ b/examples/starwars/schema.py @@ -3,9 +3,11 @@ from graphene_django import DjangoConnectionField, DjangoObjectType from .data import create_ship, get_empire, get_faction, get_rebels, get_ship, get_ships -from .models import Character as CharacterModel -from .models import Faction as FactionModel -from .models import Ship as ShipModel +from .models import ( + Character as CharacterModel, + Faction as FactionModel, + Ship as ShipModel, +) class Ship(DjangoObjectType): diff --git a/graphene_django/compat.py b/graphene_django/compat.py index 4b48f0367..fde632aa4 100644 --- a/graphene_django/compat.py +++ b/graphene_django/compat.py @@ -13,9 +13,9 @@ def __init__(self, *args, **kwargs): # Postgres fields are only available in Django with psycopg2 installed # and we cannot have psycopg2 on PyPy from django.contrib.postgres.fields import ( - IntegerRangeField, ArrayField, HStoreField, + IntegerRangeField, RangeField, ) except ImportError: diff --git a/graphene_django/converter.py b/graphene_django/converter.py index eda3a02f9..2a46dff63 100644 --- a/graphene_django/converter.py +++ b/graphene_django/converter.py @@ -6,6 +6,7 @@ from django.utils.encoding import force_str from django.utils.functional import Promise from django.utils.module_loading import import_string +from graphql import GraphQLError from graphene import ( ID, @@ -13,6 +14,7 @@ Boolean, Date, DateTime, + Decimal, Dynamic, Enum, Field, @@ -22,13 +24,11 @@ NonNull, String, Time, - Decimal, ) from graphene.types.json import JSONString -from graphene.types.scalars import BigInt from graphene.types.resolver import get_default_resolver +from graphene.types.scalars import BigInt from graphene.utils.str_converters import to_camel_case -from graphql import GraphQLError try: from graphql import assert_name @@ -38,7 +38,7 @@ from graphql.pyutils import register_description from .compat import ArrayField, HStoreField, RangeField -from .fields import DjangoListField, DjangoConnectionField +from .fields import DjangoConnectionField, DjangoListField from .settings import graphene_settings from .utils.str_converters import to_const @@ -259,6 +259,7 @@ def convert_time_to_string(field, registry=None): @convert_django_field.register(models.OneToOneRel) def convert_onetoone_field_to_djangomodel(field, registry=None): from graphene.utils.str_converters import to_snake_case + from .types import DjangoObjectType model = field.related_model @@ -362,6 +363,7 @@ def dynamic_type(): @convert_django_field.register(models.ForeignKey) def convert_field_to_djangomodel(field, registry=None): from graphene.utils.str_converters import to_snake_case + from .types import DjangoObjectType model = field.related_model diff --git a/graphene_django/debug/middleware.py b/graphene_django/debug/middleware.py index 8c7df6c02..de0d72d18 100644 --- a/graphene_django/debug/middleware.py +++ b/graphene_django/debug/middleware.py @@ -1,8 +1,7 @@ from django.db import connections - -from .sql.tracking import unwrap_cursor, wrap_cursor from .exception.formating import wrap_exception +from .sql.tracking import unwrap_cursor, wrap_cursor from .types import DjangoDebug diff --git a/graphene_django/debug/tests/test_query.py b/graphene_django/debug/tests/test_query.py index 1ea86b123..1f5e58420 100644 --- a/graphene_django/debug/tests/test_query.py +++ b/graphene_django/debug/tests/test_query.py @@ -1,5 +1,6 @@ -import graphene import pytest + +import graphene from graphene.relay import Node from graphene_django import DjangoConnectionField, DjangoObjectType diff --git a/graphene_django/debug/types.py b/graphene_django/debug/types.py index a523b4fe1..4b0f9d1a2 100644 --- a/graphene_django/debug/types.py +++ b/graphene_django/debug/types.py @@ -1,7 +1,7 @@ from graphene import List, ObjectType -from .sql.types import DjangoDebugSQL from .exception.types import DjangoDebugException +from .sql.types import DjangoDebugSQL class DjangoDebug(ObjectType): diff --git a/graphene_django/fields.py b/graphene_django/fields.py index 0fe123deb..3537da394 100644 --- a/graphene_django/fields.py +++ b/graphene_django/fields.py @@ -1,14 +1,12 @@ from functools import partial from django.db.models.query import QuerySet - from graphql_relay import ( connection_from_array_slice, cursor_to_offset, get_offset_with_default, offset_to_cursor, ) - from promise import Promise from graphene import Int, NonNull diff --git a/graphene_django/filter/__init__.py b/graphene_django/filter/__init__.py index f02fc6bcb..e4dbc0651 100644 --- a/graphene_django/filter/__init__.py +++ b/graphene_django/filter/__init__.py @@ -1,4 +1,5 @@ import warnings + from ..utils import DJANGO_FILTER_INSTALLED if not DJANGO_FILTER_INSTALLED: diff --git a/graphene_django/filter/fields.py b/graphene_django/filter/fields.py index cdb8f850f..ccf45dd40 100644 --- a/graphene_django/filter/fields.py +++ b/graphene_django/filter/fields.py @@ -3,8 +3,8 @@ from django.core.exceptions import ValidationError -from graphene.types.enum import EnumType from graphene.types.argument import to_arguments +from graphene.types.enum import EnumType from graphene.utils.str_converters import to_snake_case from ..fields import DjangoConnectionField diff --git a/graphene_django/filter/filters/__init__.py b/graphene_django/filter/filters/__init__.py index fcf75afd8..a81a96c7d 100644 --- a/graphene_django/filter/filters/__init__.py +++ b/graphene_django/filter/filters/__init__.py @@ -1,4 +1,5 @@ import warnings + from ...utils import DJANGO_FILTER_INSTALLED if not DJANGO_FILTER_INSTALLED: diff --git a/graphene_django/filter/filters/global_id_filter.py b/graphene_django/filter/filters/global_id_filter.py index 37877d58b..e0de1e3ed 100644 --- a/graphene_django/filter/filters/global_id_filter.py +++ b/graphene_django/filter/filters/global_id_filter.py @@ -1,5 +1,4 @@ from django_filters import Filter, MultipleChoiceFilter - from graphql_relay.node.node import from_global_id from ...forms import GlobalIDFormField, GlobalIDMultipleChoiceField diff --git a/graphene_django/filter/filterset.py b/graphene_django/filter/filterset.py index fa91477f1..7e0d0c520 100644 --- a/graphene_django/filter/filterset.py +++ b/graphene_django/filter/filterset.py @@ -1,12 +1,14 @@ import itertools from django.db import models -from django_filters.filterset import BaseFilterSet, FilterSet -from django_filters.filterset import FILTER_FOR_DBFIELD_DEFAULTS +from django_filters.filterset import ( + FILTER_FOR_DBFIELD_DEFAULTS, + BaseFilterSet, + FilterSet, +) from .filters import GlobalIDFilter, GlobalIDMultipleChoiceFilter - GRAPHENE_FILTER_SET_OVERRIDES = { models.AutoField: {"filter_class": GlobalIDFilter}, models.OneToOneField: {"filter_class": GlobalIDFilter}, diff --git a/graphene_django/filter/tests/conftest.py b/graphene_django/filter/tests/conftest.py index 2669c3d84..1556f5457 100644 --- a/graphene_django/filter/tests/conftest.py +++ b/graphene_django/filter/tests/conftest.py @@ -1,14 +1,15 @@ from unittest.mock import MagicMock -import pytest +import pytest from django.db import models from django.db.models.query import QuerySet from django_filters import FilterSet + import graphene from graphene.relay import Node from graphene_django import DjangoObjectType -from graphene_django.utils import DJANGO_FILTER_INSTALLED from graphene_django.filter import ArrayFilter +from graphene_django.utils import DJANGO_FILTER_INSTALLED from ...compat import ArrayField diff --git a/graphene_django/filter/tests/test_enum_filtering.py b/graphene_django/filter/tests/test_enum_filtering.py index a284d0834..32238e52b 100644 --- a/graphene_django/filter/tests/test_enum_filtering.py +++ b/graphene_django/filter/tests/test_enum_filtering.py @@ -2,8 +2,7 @@ import graphene from graphene.relay import Node - -from graphene_django import DjangoObjectType, DjangoConnectionField +from graphene_django import DjangoConnectionField, DjangoObjectType from graphene_django.tests.models import Article, Reporter from graphene_django.utils import DJANGO_FILTER_INSTALLED diff --git a/graphene_django/filter/tests/test_fields.py b/graphene_django/filter/tests/test_fields.py index 7c0fd3be6..df3b97acb 100644 --- a/graphene_django/filter/tests/test_fields.py +++ b/graphene_django/filter/tests/test_fields.py @@ -19,8 +19,8 @@ from django_filters import FilterSet, NumberFilter, OrderingFilter from graphene_django.filter import ( - GlobalIDFilter, DjangoFilterConnectionField, + GlobalIDFilter, GlobalIDMultipleChoiceFilter, ) from graphene_django.filter.tests.filters import ( diff --git a/graphene_django/filter/tests/test_in_filter.py b/graphene_django/filter/tests/test_in_filter.py index a64f7367e..b91475d7d 100644 --- a/graphene_django/filter/tests/test_in_filter.py +++ b/graphene_django/filter/tests/test_in_filter.py @@ -1,14 +1,16 @@ from datetime import datetime import pytest +from django_filters import ( + FilterSet, + rest_framework as filters, +) -from django_filters import FilterSet -from django_filters import rest_framework as filters from graphene import ObjectType, Schema from graphene.relay import Node from graphene_django import DjangoObjectType -from graphene_django.tests.models import Pet, Person, Reporter, Article, Film from graphene_django.filter.tests.filters import ArticleFilter +from graphene_django.tests.models import Article, Film, Person, Pet, Reporter from graphene_django.utils import DJANGO_FILTER_INSTALLED pytestmark = [] diff --git a/graphene_django/filter/tests/test_range_filter.py b/graphene_django/filter/tests/test_range_filter.py index 6c770f1a2..e08660ccc 100644 --- a/graphene_django/filter/tests/test_range_filter.py +++ b/graphene_django/filter/tests/test_range_filter.py @@ -1,4 +1,5 @@ import json + import pytest from graphene import ObjectType, Schema diff --git a/graphene_django/filter/tests/test_typed_filter.py b/graphene_django/filter/tests/test_typed_filter.py index f22138ff2..084affada 100644 --- a/graphene_django/filter/tests/test_typed_filter.py +++ b/graphene_django/filter/tests/test_typed_filter.py @@ -1,10 +1,8 @@ import pytest - from django_filters import FilterSet import graphene from graphene.relay import Node - from graphene_django import DjangoObjectType from graphene_django.tests.models import Article, Reporter from graphene_django.utils import DJANGO_FILTER_INSTALLED @@ -14,8 +12,8 @@ if DJANGO_FILTER_INSTALLED: from graphene_django.filter import ( DjangoFilterConnectionField, - TypedFilter, ListFilter, + TypedFilter, ) else: pytestmark.append( diff --git a/graphene_django/filter/utils.py b/graphene_django/filter/utils.py index b48d317a7..079e822d0 100644 --- a/graphene_django/filter/utils.py +++ b/graphene_django/filter/utils.py @@ -1,9 +1,11 @@ -import graphene from django import forms from django_filters.utils import get_model_field + +import graphene + +from ..forms import GlobalIDFormField, GlobalIDMultipleChoiceField from .filters import ListFilter, RangeFilter, TypedFilter from .filterset import custom_filterset_factory, setup_filterset -from ..forms import GlobalIDFormField, GlobalIDMultipleChoiceField def get_field_type(registry, model, field_name): diff --git a/graphene_django/forms/converter.py b/graphene_django/forms/converter.py index 449ab2e2f..3691e9ad6 100644 --- a/graphene_django/forms/converter.py +++ b/graphene_django/forms/converter.py @@ -5,15 +5,15 @@ from graphene import ( ID, + UUID, Boolean, + Date, + DateTime, Decimal, Float, Int, List, String, - UUID, - Date, - DateTime, Time, ) diff --git a/graphene_django/forms/forms.py b/graphene_django/forms/forms.py index 4b8185938..f6ed031e8 100644 --- a/graphene_django/forms/forms.py +++ b/graphene_django/forms/forms.py @@ -3,7 +3,6 @@ from django.core.exceptions import ValidationError from django.forms import CharField, Field, MultipleChoiceField from django.utils.translation import gettext_lazy as _ - from graphql_relay import from_global_id diff --git a/graphene_django/forms/tests/test_converter.py b/graphene_django/forms/tests/test_converter.py index f094f8533..7e2a6d342 100644 --- a/graphene_django/forms/tests/test_converter.py +++ b/graphene_django/forms/tests/test_converter.py @@ -2,17 +2,17 @@ from pytest import raises from graphene import ( - String, - Int, + ID, + UUID, Boolean, + Date, + DateTime, Decimal, Float, - ID, - UUID, + Int, List, NonNull, - DateTime, - Date, + String, Time, ) diff --git a/graphene_django/forms/tests/test_djangoinputobject.py b/graphene_django/forms/tests/test_djangoinputobject.py index c54bbf69f..20b816e28 100644 --- a/graphene_django/forms/tests/test_djangoinputobject.py +++ b/graphene_django/forms/tests/test_djangoinputobject.py @@ -1,11 +1,11 @@ -import graphene - from django import forms from pytest import raises +import graphene from graphene_django import DjangoObjectType + +from ...tests.models import CHOICES, Film, Reporter from ..types import DjangoFormInputObjectType -from ...tests.models import Reporter, Film, CHOICES # Reporter a_choice CHOICES = ((1, "this"), (2, _("that"))) THIS = CHOICES[0][0] diff --git a/graphene_django/forms/types.py b/graphene_django/forms/types.py index 132095b22..b370afd84 100644 --- a/graphene_django/forms/types.py +++ b/graphene_django/forms/types.py @@ -1,12 +1,11 @@ import graphene - from graphene import ID from graphene.types.inputobjecttype import InputObjectType from graphene.utils.str_converters import to_camel_case -from .mutation import fields_for_form -from ..types import ErrorType # noqa Import ErrorType for backwards compatability from ..converter import BlankValueField +from ..types import ErrorType # noqa Import ErrorType for backwards compatability +from .mutation import fields_for_form class DjangoFormInputObjectType(InputObjectType): diff --git a/graphene_django/management/commands/graphql_schema.py b/graphene_django/management/commands/graphql_schema.py index 42c41c173..16b49d200 100644 --- a/graphene_django/management/commands/graphql_schema.py +++ b/graphene_django/management/commands/graphql_schema.py @@ -1,12 +1,12 @@ -import os +import functools import importlib import json -import functools +import os from django.core.management.base import BaseCommand, CommandError from django.utils import autoreload - from graphql import print_schema + from graphene_django.settings import graphene_settings diff --git a/graphene_django/rest_framework/mutation.py b/graphene_django/rest_framework/mutation.py index 837db1e62..9423d4f60 100644 --- a/graphene_django/rest_framework/mutation.py +++ b/graphene_django/rest_framework/mutation.py @@ -1,6 +1,5 @@ -from enum import Enum - from collections import OrderedDict +from enum import Enum from django.shortcuts import get_object_or_404 from rest_framework import serializers diff --git a/graphene_django/rest_framework/serializer_converter.py b/graphene_django/rest_framework/serializer_converter.py index a680de4a3..f99dc4409 100644 --- a/graphene_django/rest_framework/serializer_converter.py +++ b/graphene_django/rest_framework/serializer_converter.py @@ -5,8 +5,8 @@ import graphene -from ..registry import get_global_registry from ..converter import convert_choices_to_named_enum_with_descriptions +from ..registry import get_global_registry from .types import DictType diff --git a/graphene_django/rest_framework/tests/test_field_converter.py b/graphene_django/rest_framework/tests/test_field_converter.py index 92ddb9e53..b0d7a6d6c 100644 --- a/graphene_django/rest_framework/tests/test_field_converter.py +++ b/graphene_django/rest_framework/tests/test_field_converter.py @@ -1,10 +1,11 @@ import copy -import graphene from django.db import models from pytest import raises from rest_framework import serializers +import graphene + from ..serializer_converter import convert_serializer_field from ..types import DictType diff --git a/graphene_django/rest_framework/tests/test_mutation.py b/graphene_django/rest_framework/tests/test_mutation.py index fc44e19fb..bfe53cc9a 100644 --- a/graphene_django/rest_framework/tests/test_mutation.py +++ b/graphene_django/rest_framework/tests/test_mutation.py @@ -9,9 +9,9 @@ from ...types import DjangoObjectType from ..models import ( MyFakeModel, + MyFakeModelWithChoiceField, MyFakeModelWithDate, MyFakeModelWithPassword, - MyFakeModelWithChoiceField, ) from ..mutation import SerializerMutation diff --git a/graphene_django/settings.py b/graphene_django/settings.py index 9c7dc3861..d0ef16cf8 100644 --- a/graphene_django/settings.py +++ b/graphene_django/settings.py @@ -12,11 +12,10 @@ back to the defaults. """ -from django.conf import settings -from django.test.signals import setting_changed - import importlib # Available in Python 3.1+ +from django.conf import settings +from django.test.signals import setting_changed # Copied shamelessly from Django REST Framework diff --git a/graphene_django/tests/issues/test_520.py b/graphene_django/tests/issues/test_520.py index 2aed351ac..700ae6fd3 100644 --- a/graphene_django/tests/issues/test_520.py +++ b/graphene_django/tests/issues/test_520.py @@ -2,14 +2,13 @@ from django import forms +from rest_framework import serializers import graphene -from rest_framework import serializers - +from ...forms.mutation import DjangoFormMutation from ...rest_framework.models import MyFakeModel from ...rest_framework.mutation import SerializerMutation -from ...forms.mutation import DjangoFormMutation class MyModelSerializer(serializers.ModelSerializer): diff --git a/graphene_django/tests/mutations.py b/graphene_django/tests/mutations.py index 3aa8bfcfd..68247a200 100644 --- a/graphene_django/tests/mutations.py +++ b/graphene_django/tests/mutations.py @@ -1,5 +1,4 @@ from graphene import Field - from graphene_django.forms.mutation import DjangoFormMutation, DjangoModelFormMutation from .forms import PetForm diff --git a/graphene_django/tests/test_command.py b/graphene_django/tests/test_command.py index f7325d569..d209e0373 100644 --- a/graphene_django/tests/test_command.py +++ b/graphene_django/tests/test_command.py @@ -1,8 +1,8 @@ +from io import StringIO from textwrap import dedent +from unittest.mock import mock_open, patch from django.core import management -from io import StringIO -from unittest.mock import mock_open, patch from graphene import ObjectType, Schema, String diff --git a/graphene_django/tests/test_fields.py b/graphene_django/tests/test_fields.py index 33b565a97..d1c119cc4 100644 --- a/graphene_django/tests/test_fields.py +++ b/graphene_django/tests/test_fields.py @@ -1,8 +1,8 @@ import datetime import re -from django.db.models import Count, Prefetch import pytest +from django.db.models import Count, Prefetch from graphene import List, NonNull, ObjectType, Schema, String diff --git a/graphene_django/tests/test_forms.py b/graphene_django/tests/test_forms.py index a42fcee9e..3957f01da 100644 --- a/graphene_django/tests/test_forms.py +++ b/graphene_django/tests/test_forms.py @@ -3,7 +3,6 @@ from ..forms import GlobalIDFormField, GlobalIDMultipleChoiceField - # 'TXlUeXBlOmFiYw==' -> 'MyType', 'abc' diff --git a/graphene_django/tests/test_get_queryset.py b/graphene_django/tests/test_get_queryset.py index cd1121fcb..d5b1d938a 100644 --- a/graphene_django/tests/test_get_queryset.py +++ b/graphene_django/tests/test_get_queryset.py @@ -1,13 +1,11 @@ import pytest +from graphql_relay import to_global_id import graphene from graphene.relay import Node -from graphql_relay import to_global_id - from ..types import DjangoObjectType - -from .models import Article, Reporter, FilmDetails, Film +from .models import Article, Film, FilmDetails, Reporter class TestShouldCallGetQuerySetOnForeignKey: diff --git a/graphene_django/tests/test_query.py b/graphene_django/tests/test_query.py index 4a75a882d..00a8858a2 100644 --- a/graphene_django/tests/test_query.py +++ b/graphene_django/tests/test_query.py @@ -1,5 +1,5 @@ -import datetime import base64 +import datetime import pytest from django.db import models @@ -16,6 +16,7 @@ from ..types import DjangoObjectType from ..utils import DJANGO_FILTER_INSTALLED from .models import ( + APNewsReporter, Article, CNNReporter, Film, @@ -23,7 +24,6 @@ Person, Pet, Reporter, - APNewsReporter, ) @@ -126,9 +126,9 @@ def resolve_reporter(self, info): @pytest.mark.skipif(IntegerRangeField is MissingType, reason="RangeField should exist") def test_should_query_postgres_fields(): from django.contrib.postgres.fields import ( - IntegerRangeField, ArrayField, HStoreField, + IntegerRangeField, ) class Event(models.Model): @@ -355,7 +355,7 @@ def resolve_all_reporters(self, info, **args): def test_should_keep_annotations(): - from django.db.models import Count, Avg + from django.db.models import Avg, Count class ReporterType(DjangoObjectType): class Meta: diff --git a/graphene_django/tests/test_types.py b/graphene_django/tests/test_types.py index fd85ef140..34828dbb4 100644 --- a/graphene_django/tests/test_types.py +++ b/graphene_django/tests/test_types.py @@ -1,9 +1,9 @@ from collections import OrderedDict, defaultdict from textwrap import dedent +from unittest.mock import patch import pytest from django.db import models -from unittest.mock import patch from graphene import Connection, Field, Interface, ObjectType, Schema, String from graphene.relay import Node @@ -11,8 +11,10 @@ from .. import registry from ..filter import DjangoFilterConnectionField from ..types import DjangoObjectType, DjangoObjectTypeOptions -from .models import Article as ArticleModel -from .models import Reporter as ReporterModel +from .models import ( + Article as ArticleModel, + Reporter as ReporterModel, +) class Reporter(DjangoObjectType): diff --git a/graphene_django/tests/test_utils.py b/graphene_django/tests/test_utils.py index 4e6861eda..3fa8ba457 100644 --- a/graphene_django/tests/test_utils.py +++ b/graphene_django/tests/test_utils.py @@ -1,12 +1,12 @@ import json +from unittest.mock import patch import pytest from django.utils.translation import gettext_lazy -from unittest.mock import patch -from ..utils import camelize, get_model_fields, get_reverse_fields, GraphQLTestCase -from .models import Film, Reporter, CNNReporter, APNewsReporter +from ..utils import GraphQLTestCase, camelize, get_model_fields, get_reverse_fields from ..utils.testing import graphql_query +from .models import APNewsReporter, CNNReporter, Film, Reporter def test_get_model_fields_no_duplication(): diff --git a/graphene_django/tests/test_views.py b/graphene_django/tests/test_views.py index dcbd73934..e72f293e7 100644 --- a/graphene_django/tests/test_views.py +++ b/graphene_django/tests/test_views.py @@ -1,12 +1,9 @@ import json - -import pytest - from unittest.mock import patch +import pytest from django.db import connection - from .models import Pet try: diff --git a/graphene_django/utils/__init__.py b/graphene_django/utils/__init__.py index e4780e694..a64ee36a7 100644 --- a/graphene_django/utils/__init__.py +++ b/graphene_django/utils/__init__.py @@ -1,12 +1,12 @@ from .testing import GraphQLTestCase from .utils import ( DJANGO_FILTER_INSTALLED, + bypass_get_queryset, camelize, get_model_fields, get_reverse_fields, is_valid_django_model, maybe_queryset, - bypass_get_queryset, ) __all__ = [ diff --git a/graphene_django/utils/str_converters.py b/graphene_django/utils/str_converters.py index 77a0f37e7..03ad64d7b 100644 --- a/graphene_django/utils/str_converters.py +++ b/graphene_django/utils/str_converters.py @@ -1,4 +1,5 @@ import re + from text_unidecode import unidecode diff --git a/graphene_django/utils/tests/test_testing.py b/graphene_django/utils/tests/test_testing.py index de5615859..fe38530f5 100644 --- a/graphene_django/utils/tests/test_testing.py +++ b/graphene_django/utils/tests/test_testing.py @@ -1,9 +1,9 @@ import pytest +from django.test import Client -from .. import GraphQLTestCase -from ...tests.test_types import with_local_registry from ...settings import graphene_settings -from django.test import Client +from ...tests.test_types import with_local_registry +from .. import GraphQLTestCase @with_local_registry diff --git a/graphene_django/views.py b/graphene_django/views.py index 3fb87d410..96c0b0da6 100644 --- a/graphene_django/views.py +++ b/graphene_django/views.py @@ -12,10 +12,9 @@ from graphql import OperationType, get_operation_ast, parse from graphql.error import GraphQLError from graphql.execution import ExecutionResult - -from graphene import Schema from graphql.execution.middleware import MiddlewareManager +from graphene import Schema from graphene_django.constants import MUTATION_ERRORS_FLAG from graphene_django.utils.utils import set_rollback From 47004eedec4528a0b8350e1f5e41c5ad713b8d2e Mon Sep 17 00:00:00 2001 From: Kien Dang Date: Sat, 5 Aug 2023 14:01:49 +0800 Subject: [PATCH 04/15] Add bugbear --- .ruff.toml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.ruff.toml b/.ruff.toml index 1e6ba8838..59d386563 100644 --- a/.ruff.toml +++ b/.ruff.toml @@ -3,11 +3,15 @@ select = [ "W", # pycodestyle "F", # pyflake "I", # isort + "B", # flake8-bugbear "UP", # pyupgrade ] ignore = [ "E501", # line-too-long + "B017", # pytest.raises(Exception) should be considered evil + "B028", # warnings.warn called without an explicit stacklevel keyword argument + "B904", # check for raise statements in exception handlers that lack a from clause ] exclude = [ From f0aca15c7b794edcd17ffdb2db1b1b3ec4f61e64 Mon Sep 17 00:00:00 2001 From: Kien Dang Date: Sat, 5 Aug 2023 14:02:34 +0800 Subject: [PATCH 05/15] Fix B015 Pointless comparison --- graphene_django/forms/tests/test_mutation.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/graphene_django/forms/tests/test_mutation.py b/graphene_django/forms/tests/test_mutation.py index d71328dd2..230b2fd2c 100644 --- a/graphene_django/forms/tests/test_mutation.py +++ b/graphene_django/forms/tests/test_mutation.py @@ -279,7 +279,7 @@ def test_model_form_mutation_mutate_invalid_form(): result = PetMutation.mutate_and_get_payload(None, None) # A pet was not created - Pet.objects.count() == 0 + assert Pet.objects.count() == 0 fields_w_error = [e.field for e in result.errors] assert len(result.errors) == 2 From 28f5478b4eac38343566ea1d2cac67b19ddad27f Mon Sep 17 00:00:00 2001 From: Kien Dang Date: Sat, 5 Aug 2023 14:03:44 +0800 Subject: [PATCH 06/15] Fix B026 --- graphene_django/tests/test_converter.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/graphene_django/tests/test_converter.py b/graphene_django/tests/test_converter.py index 7f4e350ca..e8c09208c 100644 --- a/graphene_django/tests/test_converter.py +++ b/graphene_django/tests/test_converter.py @@ -31,10 +31,10 @@ def assert_conversion(django_field, graphene_field, *args, **kwargs): - _kwargs = kwargs.copy() + _kwargs = {**kwargs, "help_text": "Custom Help Text"} if "null" not in kwargs: _kwargs["null"] = True - field = django_field(help_text="Custom Help Text", *args, **_kwargs) + field = django_field(*args, **_kwargs) graphene_type = convert_django_field(field) assert isinstance(graphene_type, graphene_field) field = graphene_type.Field() From fc333f3ec9355d72221ca5b2f065ad56c8d04ec7 Mon Sep 17 00:00:00 2001 From: Kien Dang Date: Sat, 5 Aug 2023 14:05:52 +0800 Subject: [PATCH 07/15] B018 false positive --- graphene_django/utils/tests/test_testing.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/graphene_django/utils/tests/test_testing.py b/graphene_django/utils/tests/test_testing.py index fe38530f5..801708ec8 100644 --- a/graphene_django/utils/tests/test_testing.py +++ b/graphene_django/utils/tests/test_testing.py @@ -23,7 +23,7 @@ def runTest(self): tc.setUpClass() with pytest.warns(PendingDeprecationWarning): - tc._client + tc._client # noqa: B018 @with_local_registry From dcf875ed18c9272d797ebcb4b1ccdfe2def1a900 Mon Sep 17 00:00:00 2001 From: Kien Dang Date: Sat, 5 Aug 2023 14:06:53 +0800 Subject: [PATCH 08/15] Remove flake8 and isort config from setup.cfg --- setup.cfg | 37 ------------------------------------- 1 file changed, 37 deletions(-) diff --git a/setup.cfg b/setup.cfg index c725df1bf..bd6d271f0 100644 --- a/setup.cfg +++ b/setup.cfg @@ -4,46 +4,9 @@ test=pytest [bdist_wheel] universal=1 -[flake8] -exclude = docs,graphene_django/debug/sql/* -max-line-length = 120 -select = - # Dictionary key repeated - F601, - # Ensure use of ==/!= to compare with str, bytes and int literals - F632, - # Redefinition of unused name - F811, - # Using an undefined variable - F821, - # Defining an undefined variable in __all__ - F822, - # Using a variable before it is assigned - F823, - # Duplicate argument in function declaration - F831, - # Black would format this line - BLK, - # Do not use bare except - B001, - # Don't allow ++n. You probably meant n += 1 - B002, - # Do not use mutable structures for argument defaults - B006, - # Do not perform calls in argument defaults - B008 - [coverage:run] omit = */tests/* -[isort] -known_first_party=graphene,graphene_django -multi_line_output=3 -include_trailing_comma=True -force_grid_wrap=0 -use_parentheses=True -line_length=88 - [tool:pytest] DJANGO_SETTINGS_MODULE = examples.django_test_settings addopts = --random-order From 9b6dcdcdaae6d084f86047a3584b450bfe69c6f2 Mon Sep 17 00:00:00 2001 From: Kien Dang Date: Sat, 5 Aug 2023 18:43:14 +0800 Subject: [PATCH 09/15] Remove black and flake8 from dev dependencies --- setup.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/setup.py b/setup.py index 2cba05332..65a489753 100644 --- a/setup.py +++ b/setup.py @@ -26,10 +26,6 @@ dev_requires = [ - "black==23.3.0", - "flake8==6.0.0", - "flake8-black==0.3.6", - "flake8-bugbear==23.3.23", "pre-commit", ] + tests_require From de039783fe26a42a620c0ca1a27b01b812af549b Mon Sep 17 00:00:00 2001 From: Kien Dang Date: Sat, 5 Aug 2023 19:24:58 +0800 Subject: [PATCH 10/15] Update black --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 52e9b5420..5ae528718 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -16,7 +16,7 @@ repos: - id: trailing-whitespace exclude: README.md - repo: https://github.com/psf/black - rev: 23.3.0 + rev: 23.7.0 hooks: - id: black - repo: https://github.com/astral-sh/ruff-pre-commit From 1bdc52402962d6e838d2e6ace0c13a361e686694 Mon Sep 17 00:00:00 2001 From: Kien Dang Date: Sat, 5 Aug 2023 20:28:09 +0800 Subject: [PATCH 11/15] Show list of fixes applied with autofix on --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 5ae528718..f894223d5 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -23,4 +23,4 @@ repos: rev: v0.0.282 hooks: - id: ruff - args: [--fix, --exit-non-zero-on-fix] + args: [--fix, --exit-non-zero-on-fix, --show-fixes] From c4d9bd374edd13642503d3a069f6e6322a811e1e Mon Sep 17 00:00:00 2001 From: Kien Dang Date: Sun, 6 Aug 2023 01:41:46 +0800 Subject: [PATCH 12/15] Fix typo --- graphene_django/filter/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/graphene_django/filter/utils.py b/graphene_django/filter/utils.py index 079e822d0..483e02506 100644 --- a/graphene_django/filter/utils.py +++ b/graphene_django/filter/utils.py @@ -51,7 +51,7 @@ def get_filtering_args_from_filterset(filterset_class, type): ): # Get the filter field for filters that are no explicitly declared. if filter_type == "isnull": - graphene.Boolean(required=required) + field_type = graphene.Boolean(required=required) else: model_field = get_model_field(model, filter_field.field_name) From b7e95b218a18ebee365df8d27e0521f0d9026851 Mon Sep 17 00:00:00 2001 From: Kien Dang Date: Sun, 6 Aug 2023 01:45:54 +0800 Subject: [PATCH 13/15] Add C4 flake8-comprehensions --- .ruff.toml | 1 + graphene_django/filter/fields.py | 2 +- graphene_django/tests/test_query.py | 32 ++++++++++++++--------------- graphene_django/tests/test_views.py | 14 ++++++------- graphene_django/views.py | 4 ++-- 5 files changed, 27 insertions(+), 26 deletions(-) diff --git a/.ruff.toml b/.ruff.toml index 59d386563..b24997ce2 100644 --- a/.ruff.toml +++ b/.ruff.toml @@ -4,6 +4,7 @@ select = [ "F", # pyflake "I", # isort "B", # flake8-bugbear + "C4", # flake8-comprehensions "UP", # pyupgrade ] diff --git a/graphene_django/filter/fields.py b/graphene_django/filter/fields.py index ccf45dd40..f6ad911d2 100644 --- a/graphene_django/filter/fields.py +++ b/graphene_django/filter/fields.py @@ -58,7 +58,7 @@ def args(self, args): def filterset_class(self): if not self._filterset_class: fields = self._fields or self.node_type._meta.filter_fields - meta = dict(model=self.model, fields=fields) + meta = {"model": self.model, "fields": fields} if self._extra_filter_meta: meta.update(self._extra_filter_meta) diff --git a/graphene_django/tests/test_query.py b/graphene_django/tests/test_query.py index 00a8858a2..cdfbc69fd 100644 --- a/graphene_django/tests/test_query.py +++ b/graphene_django/tests/test_query.py @@ -1444,19 +1444,19 @@ class Query(graphene.ObjectType): """ after = base64.b64encode(b"arrayconnection:10").decode() - result = schema.execute(query, variable_values=dict(after=after)) + result = schema.execute(query, variable_values={"after": after}) expected = {"allReporters": {"edges": []}} assert not result.errors assert result.data == expected REPORTERS = [ - dict( - first_name=f"First {i}", - last_name=f"Last {i}", - email=f"johndoe+{i}@example.com", - a_choice=1, - ) + { + "first_name": f"First {i}", + "last_name": f"Last {i}", + "email": f"johndoe+{i}@example.com", + "a_choice": 1, + } for i in range(6) ] @@ -1531,7 +1531,7 @@ class Query(graphene.ObjectType): assert result.data["allReporters"]["pageInfo"]["hasNextPage"] last_result = result.data["allReporters"]["pageInfo"]["endCursor"] - result2 = schema.execute(query, variable_values=dict(first=4, after=last_result)) + result2 = schema.execute(query, variable_values={"first": 4, "after": last_result}) assert not result2.errors assert len(result2.data["allReporters"]["edges"]) == 2 assert not result2.data["allReporters"]["pageInfo"]["hasNextPage"] @@ -1622,7 +1622,7 @@ def test_query_first_last_and_after(self, graphene_settings, max_limit): after = base64.b64encode(b"arrayconnection:0").decode() result = schema.execute( query_first_last_and_after, - variable_values=dict(after=after), + variable_values={"after": after}, ) assert not result.errors assert len(result.data["allReporters"]["edges"]) == 3 @@ -1654,7 +1654,7 @@ def test_query_last_and_before(self, graphene_settings, max_limit): before = base64.b64encode(b"arrayconnection:5").decode() result = schema.execute( query_first_last_and_after, - variable_values=dict(before=before), + variable_values={"before": before}, ) assert not result.errors assert len(result.data["allReporters"]["edges"]) == 1 @@ -1877,7 +1877,7 @@ class Query(graphene.ObjectType): } """ before = base64.b64encode(b"arrayconnection:2").decode() - result = schema.execute(query, variable_values=dict(before=before)) + result = schema.execute(query, variable_values={"before": before}) expected_error = "You can't provide a `before` value at the same time as an `offset` value to properly paginate the `allReporters` connection." assert len(result.errors) == 1 assert result.errors[0].message == expected_error @@ -1913,7 +1913,7 @@ class Query(graphene.ObjectType): """ after = base64.b64encode(b"arrayconnection:0").decode() - result = schema.execute(query, variable_values=dict(after=after)) + result = schema.execute(query, variable_values={"after": after}) assert not result.errors expected = { "allReporters": { @@ -1949,7 +1949,7 @@ class Query(graphene.ObjectType): } """ - result = schema.execute(query, variable_values=dict(last=2)) + result = schema.execute(query, variable_values={"last": 2}) assert not result.errors expected = {"allReporters": {"edges": []}} assert result.data == expected @@ -1959,7 +1959,7 @@ class Query(graphene.ObjectType): Reporter.objects.create(first_name="Jane", last_name="Roe") Reporter.objects.create(first_name="Some", last_name="Lady") - result = schema.execute(query, variable_values=dict(last=2)) + result = schema.execute(query, variable_values={"last": 2}) assert not result.errors expected = { "allReporters": { @@ -1971,7 +1971,7 @@ class Query(graphene.ObjectType): } assert result.data == expected - result = schema.execute(query, variable_values=dict(last=4)) + result = schema.execute(query, variable_values={"last": 4}) assert not result.errors expected = { "allReporters": { @@ -1985,7 +1985,7 @@ class Query(graphene.ObjectType): } assert result.data == expected - result = schema.execute(query, variable_values=dict(last=20)) + result = schema.execute(query, variable_values={"last": 20}) assert not result.errors expected = { "allReporters": { diff --git a/graphene_django/tests/test_views.py b/graphene_django/tests/test_views.py index e72f293e7..d64a4f02b 100644 --- a/graphene_django/tests/test_views.py +++ b/graphene_django/tests/test_views.py @@ -229,7 +229,7 @@ def test_allows_sending_a_mutation_via_post(client): def test_allows_post_with_url_encoding(client): response = client.post( url_string(), - urlencode(dict(query="{test}")), + urlencode({"query": "{test}"}), "application/x-www-form-urlencoded", ) @@ -303,10 +303,10 @@ def test_supports_post_url_encoded_query_with_string_variables(client): response = client.post( url_string(), urlencode( - dict( - query="query helloWho($who: String){ test(who: $who) }", - variables=json.dumps({"who": "Dolly"}), - ) + { + "query": "query helloWho($who: String){ test(who: $who) }", + "variables": json.dumps({"who": "Dolly"}), + } ), "application/x-www-form-urlencoded", ) @@ -329,7 +329,7 @@ def test_supports_post_json_quey_with_get_variable_values(client): def test_post_url_encoded_query_with_get_variable_values(client): response = client.post( url_string(variables=json.dumps({"who": "Dolly"})), - urlencode(dict(query="query helloWho($who: String){ test(who: $who) }")), + urlencode({"query": "query helloWho($who: String){ test(who: $who) }"}), "application/x-www-form-urlencoded", ) @@ -511,7 +511,7 @@ def mocked_read(*args): monkeypatch.setattr("django.http.request.HttpRequest.read", mocked_read) - valid_json = json.dumps(dict(foo="bar")) + valid_json = json.dumps({"foo": "bar"}) response = client.post(url_string(), valid_json, "application/json") assert response.status_code == 400 diff --git a/graphene_django/views.py b/graphene_django/views.py index 96c0b0da6..ce08d26a9 100644 --- a/graphene_django/views.py +++ b/graphene_django/views.py @@ -39,9 +39,9 @@ def qualify(x): raw_content_types = request.META.get("HTTP_ACCEPT", "*/*").split(",") qualified_content_types = map(qualify, raw_content_types) - return list( + return [ x[0] for x in sorted(qualified_content_types, key=lambda x: x[1], reverse=True) - ) + ] def instantiate_middleware(middlewares): From 91cd27781f5db2b74f19800c884de5b133644b17 Mon Sep 17 00:00:00 2001 From: Kien Dang Date: Sun, 6 Aug 2023 01:53:40 +0800 Subject: [PATCH 14/15] Add ruff to dev dependencies --- setup.py | 1 + 1 file changed, 1 insertion(+) diff --git a/setup.py b/setup.py index 65a489753..bccf8c814 100644 --- a/setup.py +++ b/setup.py @@ -26,6 +26,7 @@ dev_requires = [ + "ruff", "pre-commit", ] + tests_require From 17199fb470ca3f72d15bb4206d1d8f98891ad76d Mon Sep 17 00:00:00 2001 From: Kien Dang Date: Sun, 6 Aug 2023 02:09:49 +0800 Subject: [PATCH 15/15] Fix up --- graphene_django/filter/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/graphene_django/filter/utils.py b/graphene_django/filter/utils.py index 483e02506..3dd835fc3 100644 --- a/graphene_django/filter/utils.py +++ b/graphene_django/filter/utils.py @@ -51,7 +51,7 @@ def get_filtering_args_from_filterset(filterset_class, type): ): # Get the filter field for filters that are no explicitly declared. if filter_type == "isnull": - field_type = graphene.Boolean(required=required) + field_type = graphene.Boolean else: model_field = get_model_field(model, filter_field.field_name)