From 936a1d1602933f65e93382f06ddb00e47fa2e7de Mon Sep 17 00:00:00 2001 From: "sourcery-ai[bot]" Date: Wed, 20 Nov 2024 12:10:13 +0000 Subject: [PATCH 01/10] Support nullable Connection types in relay field decorator Enable nullable Connection types in the connection field decorator by updating type checking logic and adding validation for inner types. Update documentation and add tests to ensure compatibility with permission extensions and different nullable syntax. New Features: - Support nullable Connection types in the connection field decorator in strawberry.relay.fields. Enhancements: - Update type checking logic to handle Optional[Connection[T]] and Connection[T] | None annotations. Documentation: - Update documentation to reflect that connection fields can now be nullable. Tests: - Add tests to verify nullable connection fields work correctly with permission extensions and both Optional[Connection[T]] and Connection[T] | None syntax. Resolves #3703 --- strawberry/relay/fields.py | 12 ++++ tests/relay/test_connection.py | 124 +++++++++++++++++++++++++++++++++ 2 files changed, 136 insertions(+) create mode 100644 tests/relay/test_connection.py diff --git a/strawberry/relay/fields.py b/strawberry/relay/fields.py index 5af00700f8..0b7414bb48 100644 --- a/strawberry/relay/fields.py +++ b/strawberry/relay/fields.py @@ -6,6 +6,8 @@ from collections import defaultdict from collections.abc import AsyncIterable from typing import ( + TypeVar, + UnionType, TYPE_CHECKING, Any, AsyncIterator, @@ -233,7 +235,17 @@ def apply(self, field: StrawberryField) -> None: f_type = f_type.resolve_type() field.type = f_type + # Handle Optional[Connection[T]] and Union[Connection[T], None] cases type_origin = get_origin(f_type) if is_generic_alias(f_type) else f_type + + # If it's Optional or Union, extract the inner type + if type_origin in (Union, UnionType): + types = getattr(f_type, "__args__", ()) + # Find the non-None type in the Union + inner_type = next((t for t in types if t is not type(None)), None) # noqa: E721 + if inner_type is not None: + type_origin = get_origin(inner_type) if is_generic_alias(inner_type) else inner_type + if not isinstance(type_origin, type) or not issubclass(type_origin, Connection): raise RelayWrongAnnotationError(field.name, cast(type, field.origin)) diff --git a/tests/relay/test_connection.py b/tests/relay/test_connection.py new file mode 100644 index 0000000000..b12a48750f --- /dev/null +++ b/tests/relay/test_connection.py @@ -0,0 +1,124 @@ +from typing import List, Optional, Union + +import pytest + +import strawberry +from strawberry.permission import BasePermission +from strawberry.relay import Connection, Node, connection + + +@strawberry.type +class User(Node): + name: str = "John" + + @classmethod + def resolve_nodes(cls, *, info, node_ids, required): + return [cls() for _ in node_ids] + + +class TestPermission(BasePermission): + message = "Not allowed" + + def has_permission(self, source, info, **kwargs): + return False + + +def test_nullable_connection_with_optional(): + @strawberry.type + class Query: + @connection + def users(self) -> Optional[Connection[User]]: + return None + + schema = strawberry.Schema(query=Query) + query = """ + query { + users { + edges { + node { + name + } + } + } + } + """ + + result = schema.execute_sync(query) + assert result.data == {"users": None} + assert not result.errors + + +def test_nullable_connection_with_union(): + @strawberry.type + class Query: + @connection + def users(self) -> Union[Connection[User], None]: + return None + + schema = strawberry.Schema(query=Query) + query = """ + query { + users { + edges { + node { + name + } + } + } + } + """ + + result = schema.execute_sync(query) + assert result.data == {"users": None} + assert not result.errors + + +def test_nullable_connection_with_permission(): + @strawberry.type + class Query: + @strawberry.permission_classes([TestPermission]) + @connection + def users(self) -> Optional[Connection[User]]: + return Connection[User](edges=[], page_info=None) + + schema = strawberry.Schema(query=Query) + query = """ + query { + users { + edges { + node { + name + } + } + } + } + """ + + result = schema.execute_sync(query) + assert result.data == {"users": None} + assert not result.errors + + +def test_non_nullable_connection(): + @strawberry.type + class Query: + @connection + def users(self) -> Connection[User]: + return Connection[User](edges=[], page_info=None) + + schema = strawberry.Schema(query=Query) + query = """ + query { + users { + edges { + node { + name + } + } + } + } + """ + + result = schema.execute_sync(query) + assert result.data == {"users": {"edges": []}} + assert not result.errors From c61f422668423101239fa4327738c000fe41ea6b Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 20 Nov 2024 12:10:53 +0000 Subject: [PATCH 02/10] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- strawberry/relay/fields.py | 15 +++++++++------ tests/relay/test_connection.py | 4 +--- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/strawberry/relay/fields.py b/strawberry/relay/fields.py index 0b7414bb48..a65a2ed279 100644 --- a/strawberry/relay/fields.py +++ b/strawberry/relay/fields.py @@ -6,8 +6,6 @@ from collections import defaultdict from collections.abc import AsyncIterable from typing import ( - TypeVar, - UnionType, TYPE_CHECKING, Any, AsyncIterator, @@ -25,6 +23,7 @@ Tuple, Type, Union, + UnionType, cast, overload, ) @@ -237,15 +236,19 @@ def apply(self, field: StrawberryField) -> None: # Handle Optional[Connection[T]] and Union[Connection[T], None] cases type_origin = get_origin(f_type) if is_generic_alias(f_type) else f_type - + # If it's Optional or Union, extract the inner type if type_origin in (Union, UnionType): types = getattr(f_type, "__args__", ()) # Find the non-None type in the Union - inner_type = next((t for t in types if t is not type(None)), None) # noqa: E721 + inner_type = next((t for t in types if t is not type(None)), None) if inner_type is not None: - type_origin = get_origin(inner_type) if is_generic_alias(inner_type) else inner_type - + type_origin = ( + get_origin(inner_type) + if is_generic_alias(inner_type) + else inner_type + ) + if not isinstance(type_origin, type) or not issubclass(type_origin, Connection): raise RelayWrongAnnotationError(field.name, cast(type, field.origin)) diff --git a/tests/relay/test_connection.py b/tests/relay/test_connection.py index b12a48750f..40a8203eda 100644 --- a/tests/relay/test_connection.py +++ b/tests/relay/test_connection.py @@ -1,6 +1,4 @@ -from typing import List, Optional, Union - -import pytest +from typing import Optional, Union import strawberry from strawberry.permission import BasePermission From 1b82b34bb7718a9e36dc8c4ae80ca0a02b6a2298 Mon Sep 17 00:00:00 2001 From: Patrick Arminio Date: Wed, 20 Nov 2024 20:34:03 +0000 Subject: [PATCH 03/10] Initial working version --- strawberry/annotation.py | 2 +- strawberry/relay/fields.py | 45 ++++++++++---------- tests/relay/test_connection.py | 77 ++++++++++++++++++---------------- 3 files changed, 65 insertions(+), 59 deletions(-) diff --git a/strawberry/annotation.py b/strawberry/annotation.py index dff708a1a1..8934f5bad8 100644 --- a/strawberry/annotation.py +++ b/strawberry/annotation.py @@ -208,7 +208,7 @@ def create_optional(self, evaled_type: Any) -> StrawberryOptional: ) # Note that passing a single type to `Union` is equivalent to not using `Union` - # at all. This allows us to not di any checks for how many types have been + # at all. This allows us to not do any checks for how many types have been # passed as we can safely use `Union` for both optional types # (e.g. `Optional[str]`) and optional unions (e.g. # `Optional[Union[TypeA, TypeB]]`) diff --git a/strawberry/relay/fields.py b/strawberry/relay/fields.py index a65a2ed279..ac002fa978 100644 --- a/strawberry/relay/fields.py +++ b/strawberry/relay/fields.py @@ -23,11 +23,10 @@ Tuple, Type, Union, - UnionType, cast, overload, ) -from typing_extensions import Annotated, get_origin +from typing_extensions import Annotated, get_args, get_origin from strawberry.annotation import StrawberryAnnotation from strawberry.extensions.field_extension import ( @@ -45,9 +44,9 @@ from strawberry.types.fields.resolver import StrawberryResolver from strawberry.types.lazy_type import LazyType from strawberry.utils.aio import asyncgen_to_list -from strawberry.utils.typing import eval_type, is_generic_alias +from strawberry.utils.typing import eval_type, is_generic_alias, is_union -from .types import Connection, GlobalID, Node, NodeIterableType, NodeType +from .types import Connection, GlobalID, Node, NodeIterableType if TYPE_CHECKING: from typing_extensions import Literal @@ -234,20 +233,10 @@ def apply(self, field: StrawberryField) -> None: f_type = f_type.resolve_type() field.type = f_type - # Handle Optional[Connection[T]] and Union[Connection[T], None] cases - type_origin = get_origin(f_type) if is_generic_alias(f_type) else f_type + if isinstance(f_type, StrawberryOptional): + f_type = f_type.of_type - # If it's Optional or Union, extract the inner type - if type_origin in (Union, UnionType): - types = getattr(f_type, "__args__", ()) - # Find the non-None type in the Union - inner_type = next((t for t in types if t is not type(None)), None) - if inner_type is not None: - type_origin = ( - get_origin(inner_type) - if is_generic_alias(inner_type) - else inner_type - ) + type_origin = get_origin(f_type) if is_generic_alias(f_type) else f_type if not isinstance(type_origin, type) or not issubclass(type_origin, Connection): raise RelayWrongAnnotationError(field.name, cast(type, field.origin)) @@ -268,13 +257,18 @@ def apply(self, field: StrawberryField) -> None: None, ) + if is_union(resolver_type): + # TODO: actually check if is optional and get correct type + resolver_type = get_args(resolver_type)[0] + origin = get_origin(resolver_type) + if origin is None or not issubclass( origin, (Iterator, Iterable, AsyncIterator, AsyncIterable) ): raise RelayWrongResolverAnnotationError(field.name, field.base_resolver) - self.connection_type = cast(Type[Connection[Node]], field.type) + self.connection_type = cast(Type[Connection[Node]], f_type) def resolve( self, @@ -342,9 +336,18 @@ def node(*args: Any, **kwargs: Any) -> StrawberryField: return field(*args, **kwargs) +# we used to have `Type[Connection[NodeType]]` here, but that when we added +# support for making the Connection type optional, we had to change it to +# `Any` because otherwise it wouldn't be type check since `Optional[Connection[Something]]` +# is not a `Type`, but a special form, see https://discuss.python.org/t/is-annotated-compatible-with-type-t/43898/46 +# for more information, and also https://peps.python.org/pep-0747/, which is currently +# in draft status (and no type checker supports it yet) +ConnectionGraphQLType = Any + + @overload def connection( - graphql_type: Optional[Type[Connection[NodeType]]] = None, + graphql_type: Optional[ConnectionGraphQLType] = None, *, resolver: Optional[_RESOLVER_TYPE[NodeIterableType[Any]]] = None, name: Optional[str] = None, @@ -363,7 +366,7 @@ def connection( @overload def connection( - graphql_type: Optional[Type[Connection[NodeType]]] = None, + graphql_type: Optional[ConnectionGraphQLType] = None, *, name: Optional[str] = None, is_subscription: bool = False, @@ -379,7 +382,7 @@ def connection( def connection( - graphql_type: Optional[Type[Connection[NodeType]]] = None, + graphql_type: Optional[ConnectionGraphQLType] = None, *, resolver: Optional[_RESOLVER_TYPE[Any]] = None, name: Optional[str] = None, diff --git a/tests/relay/test_connection.py b/tests/relay/test_connection.py index 40a8203eda..3595a8c7a2 100644 --- a/tests/relay/test_connection.py +++ b/tests/relay/test_connection.py @@ -1,12 +1,17 @@ -from typing import Optional, Union +import sys +from typing import Any, Iterable, List, Optional +from typing_extensions import Self + +import pytest import strawberry from strawberry.permission import BasePermission -from strawberry.relay import Connection, Node, connection +from strawberry.relay import Connection, Node @strawberry.type class User(Node): + id: strawberry.relay.NodeID name: str = "John" @classmethod @@ -14,6 +19,22 @@ def resolve_nodes(cls, *, info, node_ids, required): return [cls() for _ in node_ids] +@strawberry.type +class UserConnection(Connection[User]): + @classmethod + def resolve_connection( + cls, + nodes: Iterable[User], + *, + info: Any, + after: Optional[str] = None, + before: Optional[str] = None, + first: Optional[int] = None, + last: Optional[int] = None, + ) -> Optional[Self]: + return None + + class TestPermission(BasePermission): message = "Not allowed" @@ -24,8 +45,8 @@ def has_permission(self, source, info, **kwargs): def test_nullable_connection_with_optional(): @strawberry.type class Query: - @connection - def users(self) -> Optional[Connection[User]]: + @strawberry.relay.connection(Optional[UserConnection]) + def users(self) -> Optional[List[User]]: return None schema = strawberry.Schema(query=Query) @@ -46,11 +67,17 @@ def users(self) -> Optional[Connection[User]]: assert not result.errors -def test_nullable_connection_with_union(): +pytest.mark.skipif( + sys.version_info < (3, 10), + reason="pipe syntax for union is only available on python 3.10+", +) + + +def test_nullable_connection_with_pipe(): @strawberry.type class Query: - @connection - def users(self) -> Union[Connection[User], None]: + @strawberry.relay.connection(UserConnection | None) + def users(self) -> List[User] | None: return None schema = strawberry.Schema(query=Query) @@ -74,10 +101,11 @@ def users(self) -> Union[Connection[User], None]: def test_nullable_connection_with_permission(): @strawberry.type class Query: - @strawberry.permission_classes([TestPermission]) - @connection - def users(self) -> Optional[Connection[User]]: - return Connection[User](edges=[], page_info=None) + @strawberry.relay.connection( + Optional[UserConnection], permission_classes=[TestPermission] + ) + def users(self) -> Optional[List[User]]: + return None schema = strawberry.Schema(query=Query) query = """ @@ -94,29 +122,4 @@ def users(self) -> Optional[Connection[User]]: result = schema.execute_sync(query) assert result.data == {"users": None} - assert not result.errors - - -def test_non_nullable_connection(): - @strawberry.type - class Query: - @connection - def users(self) -> Connection[User]: - return Connection[User](edges=[], page_info=None) - - schema = strawberry.Schema(query=Query) - query = """ - query { - users { - edges { - node { - name - } - } - } - } - """ - - result = schema.execute_sync(query) - assert result.data == {"users": {"edges": []}} - assert not result.errors + assert result.errors[0].message == "Not allowed" From d72b5606c67c93540dc375cdfd151f24d9588353 Mon Sep 17 00:00:00 2001 From: Patrick Arminio Date: Mon, 9 Dec 2024 00:02:40 +0000 Subject: [PATCH 04/10] Fix typos and types --- strawberry/relay/fields.py | 41 ++-------------------------------- strawberry/schema/subscribe.py | 2 +- 2 files changed, 3 insertions(+), 40 deletions(-) diff --git a/strawberry/relay/fields.py b/strawberry/relay/fields.py index ac002fa978..3c605c1129 100644 --- a/strawberry/relay/fields.py +++ b/strawberry/relay/fields.py @@ -24,7 +24,6 @@ Type, Union, cast, - overload, ) from typing_extensions import Annotated, get_args, get_origin @@ -46,7 +45,7 @@ from strawberry.utils.aio import asyncgen_to_list from strawberry.utils.typing import eval_type, is_generic_alias, is_union -from .types import Connection, GlobalID, Node, NodeIterableType +from .types import Connection, GlobalID, Node if TYPE_CHECKING: from typing_extensions import Literal @@ -345,42 +344,6 @@ def node(*args: Any, **kwargs: Any) -> StrawberryField: ConnectionGraphQLType = Any -@overload -def connection( - graphql_type: Optional[ConnectionGraphQLType] = None, - *, - resolver: Optional[_RESOLVER_TYPE[NodeIterableType[Any]]] = None, - name: Optional[str] = None, - is_subscription: bool = False, - description: Optional[str] = None, - init: Literal[True] = True, - permission_classes: Optional[List[Type[BasePermission]]] = None, - deprecation_reason: Optional[str] = None, - default: Any = dataclasses.MISSING, - default_factory: Union[Callable[..., object], object] = dataclasses.MISSING, - metadata: Optional[Mapping[Any, Any]] = None, - directives: Optional[Sequence[object]] = (), - extensions: List[FieldExtension] = (), # type: ignore -) -> Any: ... - - -@overload -def connection( - graphql_type: Optional[ConnectionGraphQLType] = None, - *, - name: Optional[str] = None, - is_subscription: bool = False, - description: Optional[str] = None, - permission_classes: Optional[List[Type[BasePermission]]] = None, - deprecation_reason: Optional[str] = None, - default: Any = dataclasses.MISSING, - default_factory: Union[Callable[..., object], object] = dataclasses.MISSING, - metadata: Optional[Mapping[Any, Any]] = None, - directives: Optional[Sequence[object]] = (), - extensions: List[FieldExtension] = (), # type: ignore -) -> StrawberryField: ... - - def connection( graphql_type: Optional[ConnectionGraphQLType] = None, *, @@ -397,7 +360,7 @@ def connection( extensions: List[FieldExtension] = (), # type: ignore # This init parameter is used by pyright to determine whether this field # is added in the constructor or not. It is not used to change - # any behavior at the moment. + # any behaviour at the moment. init: Literal[True, False, None] = None, ) -> Any: """Annotate a property or a method to create a relay connection field. diff --git a/strawberry/schema/subscribe.py b/strawberry/schema/subscribe.py index be8b783cb2..22052e36cf 100644 --- a/strawberry/schema/subscribe.py +++ b/strawberry/schema/subscribe.py @@ -138,7 +138,7 @@ async def subscribe( middleware_manager, execution_context_class, ) - # GrapQL-core might return an initial error result instead of an async iterator. + # GraphQL-core might return an initial error result instead of an async iterator. # This happens when "there was an immediate error" i.e resolver is not an async iterator. # To overcome this while maintaining the extension contexts we do this trick. first = await asyncgen.__anext__() From ee98aee72d4a34cb494a42638e5543ace77bb2e4 Mon Sep 17 00:00:00 2001 From: Patrick Arminio Date: Mon, 9 Dec 2024 00:06:51 +0000 Subject: [PATCH 05/10] Pre-commit --- strawberry/experimental/pydantic/_compat.py | 1 - strawberry/experimental/pydantic/error_type.py | 1 - strawberry/experimental/pydantic/fields.py | 1 - strawberry/experimental/pydantic/utils.py | 1 - tests/experimental/pydantic/schema/test_basic.py | 2 +- tests/experimental/pydantic/schema/test_defaults.py | 1 - tests/experimental/pydantic/schema/test_federation.py | 3 +-- .../experimental/pydantic/schema/test_forward_reference.py | 1 - tests/experimental/pydantic/schema/test_mutation.py | 1 - tests/experimental/pydantic/test_basic.py | 2 +- tests/experimental/pydantic/test_conversion.py | 2 +- tests/experimental/pydantic/test_error_type.py | 2 +- tests/experimental/pydantic/test_fields.py | 4 ++-- tests/relay/test_connection.py | 6 ++++-- 14 files changed, 11 insertions(+), 17 deletions(-) diff --git a/strawberry/experimental/pydantic/_compat.py b/strawberry/experimental/pydantic/_compat.py index 9971c962b5..dc3c2fe08f 100644 --- a/strawberry/experimental/pydantic/_compat.py +++ b/strawberry/experimental/pydantic/_compat.py @@ -8,7 +8,6 @@ import pydantic from pydantic import BaseModel from pydantic.version import VERSION as PYDANTIC_VERSION - from strawberry.experimental.pydantic.exceptions import UnsupportedTypeError if TYPE_CHECKING: diff --git a/strawberry/experimental/pydantic/error_type.py b/strawberry/experimental/pydantic/error_type.py index bbedfe610b..d07284e145 100644 --- a/strawberry/experimental/pydantic/error_type.py +++ b/strawberry/experimental/pydantic/error_type.py @@ -15,7 +15,6 @@ ) from pydantic import BaseModel - from strawberry.experimental.pydantic._compat import ( CompatModelField, PydanticCompat, diff --git a/strawberry/experimental/pydantic/fields.py b/strawberry/experimental/pydantic/fields.py index 9cac486290..3ded38fc29 100644 --- a/strawberry/experimental/pydantic/fields.py +++ b/strawberry/experimental/pydantic/fields.py @@ -3,7 +3,6 @@ from typing_extensions import Annotated from pydantic import BaseModel - from strawberry.experimental.pydantic._compat import ( PydanticCompat, get_args, diff --git a/strawberry/experimental/pydantic/utils.py b/strawberry/experimental/pydantic/utils.py index 912553fb98..9987c2ee59 100644 --- a/strawberry/experimental/pydantic/utils.py +++ b/strawberry/experimental/pydantic/utils.py @@ -14,7 +14,6 @@ ) from pydantic import BaseModel - from strawberry.experimental.pydantic._compat import ( CompatModelField, PydanticCompat, diff --git a/tests/experimental/pydantic/schema/test_basic.py b/tests/experimental/pydantic/schema/test_basic.py index f816208978..75b6411bd2 100644 --- a/tests/experimental/pydantic/schema/test_basic.py +++ b/tests/experimental/pydantic/schema/test_basic.py @@ -3,9 +3,9 @@ from enum import Enum from typing import List, Optional, Union -import pydantic import pytest +import pydantic import strawberry from tests.experimental.pydantic.utils import needs_pydantic_v1 diff --git a/tests/experimental/pydantic/schema/test_defaults.py b/tests/experimental/pydantic/schema/test_defaults.py index 6d87c690a7..6708ee036e 100644 --- a/tests/experimental/pydantic/schema/test_defaults.py +++ b/tests/experimental/pydantic/schema/test_defaults.py @@ -2,7 +2,6 @@ from typing import Optional import pydantic - import strawberry from strawberry.printer import print_schema from tests.conftest import skip_if_gql_32 diff --git a/tests/experimental/pydantic/schema/test_federation.py b/tests/experimental/pydantic/schema/test_federation.py index 47bd56c2f9..90a506d62e 100644 --- a/tests/experimental/pydantic/schema/test_federation.py +++ b/tests/experimental/pydantic/schema/test_federation.py @@ -1,8 +1,7 @@ import typing -from pydantic import BaseModel - import strawberry +from pydantic import BaseModel from strawberry.federation.schema_directives import Key diff --git a/tests/experimental/pydantic/schema/test_forward_reference.py b/tests/experimental/pydantic/schema/test_forward_reference.py index ebc94d4b37..23ad750b51 100644 --- a/tests/experimental/pydantic/schema/test_forward_reference.py +++ b/tests/experimental/pydantic/schema/test_forward_reference.py @@ -4,7 +4,6 @@ from typing import Optional import pydantic - import strawberry diff --git a/tests/experimental/pydantic/schema/test_mutation.py b/tests/experimental/pydantic/schema/test_mutation.py index 03e545eece..a1efa945cd 100644 --- a/tests/experimental/pydantic/schema/test_mutation.py +++ b/tests/experimental/pydantic/schema/test_mutation.py @@ -1,7 +1,6 @@ from typing import Dict, List, Union import pydantic - import strawberry from strawberry.experimental.pydantic._compat import IS_PYDANTIC_V2 diff --git a/tests/experimental/pydantic/test_basic.py b/tests/experimental/pydantic/test_basic.py index 9556d3f617..2540ff99f1 100644 --- a/tests/experimental/pydantic/test_basic.py +++ b/tests/experimental/pydantic/test_basic.py @@ -3,9 +3,9 @@ from typing import Any, List, Optional, Union from typing_extensions import Annotated -import pydantic import pytest +import pydantic import strawberry from strawberry.experimental.pydantic.exceptions import MissingFieldsListError from strawberry.schema_directive import Location diff --git a/tests/experimental/pydantic/test_conversion.py b/tests/experimental/pydantic/test_conversion.py index 745e5e90c4..8963c3e6ae 100644 --- a/tests/experimental/pydantic/test_conversion.py +++ b/tests/experimental/pydantic/test_conversion.py @@ -6,9 +6,9 @@ from typing import Any, Dict, List, NewType, Optional, TypeVar, Union import pytest -from pydantic import BaseModel, Field, ValidationError import strawberry +from pydantic import BaseModel, Field, ValidationError from strawberry.experimental.pydantic._compat import ( IS_PYDANTIC_V2, CompatModelField, diff --git a/tests/experimental/pydantic/test_error_type.py b/tests/experimental/pydantic/test_error_type.py index 8e37c6402c..37af6e51e3 100644 --- a/tests/experimental/pydantic/test_error_type.py +++ b/tests/experimental/pydantic/test_error_type.py @@ -1,8 +1,8 @@ from typing import List, Optional -import pydantic import pytest +import pydantic import strawberry from strawberry.experimental.pydantic.exceptions import MissingFieldsListError from strawberry.types.base import ( diff --git a/tests/experimental/pydantic/test_fields.py b/tests/experimental/pydantic/test_fields.py index 878969b9af..884236f704 100644 --- a/tests/experimental/pydantic/test_fields.py +++ b/tests/experimental/pydantic/test_fields.py @@ -2,11 +2,11 @@ from typing import List from typing_extensions import Literal -import pydantic import pytest -from pydantic import BaseModel, ValidationError, conlist +import pydantic import strawberry +from pydantic import BaseModel, ValidationError, conlist from strawberry.experimental.pydantic._compat import IS_PYDANTIC_V1 from strawberry.types.base import StrawberryObjectDefinition, StrawberryOptional from tests.experimental.pydantic.utils import needs_pydantic_v1, needs_pydantic_v2 diff --git a/tests/relay/test_connection.py b/tests/relay/test_connection.py index 3595a8c7a2..5d8ec52eda 100644 --- a/tests/relay/test_connection.py +++ b/tests/relay/test_connection.py @@ -15,7 +15,9 @@ class User(Node): name: str = "John" @classmethod - def resolve_nodes(cls, *, info, node_ids, required): + def resolve_nodes( + cls, *, info: strawberry.Info, node_ids: List[Any], required: bool + ) -> List[Self]: return [cls() for _ in node_ids] @@ -38,7 +40,7 @@ def resolve_connection( class TestPermission(BasePermission): message = "Not allowed" - def has_permission(self, source, info, **kwargs): + def has_permission(self, source, info, **kwargs: Any): return False From 748f6d9d97d4e78d6fa5cbe50c1e7b1ec6b7c7de Mon Sep 17 00:00:00 2001 From: Patrick Arminio Date: Mon, 9 Dec 2024 00:07:13 +0000 Subject: [PATCH 06/10] Fix missing `@` --- tests/relay/test_connection.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/tests/relay/test_connection.py b/tests/relay/test_connection.py index 5d8ec52eda..08cb789243 100644 --- a/tests/relay/test_connection.py +++ b/tests/relay/test_connection.py @@ -69,12 +69,10 @@ def users(self) -> Optional[List[User]]: assert not result.errors -pytest.mark.skipif( +@pytest.mark.skipif( sys.version_info < (3, 10), reason="pipe syntax for union is only available on python 3.10+", ) - - def test_nullable_connection_with_pipe(): @strawberry.type class Query: From 2cdbcfa07e2ad1dd5876082c462f98eacc55db5c Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 9 Dec 2024 00:07:52 +0000 Subject: [PATCH 07/10] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- strawberry/experimental/pydantic/_compat.py | 1 + strawberry/experimental/pydantic/error_type.py | 1 + strawberry/experimental/pydantic/fields.py | 1 + strawberry/experimental/pydantic/utils.py | 1 + tests/experimental/pydantic/schema/test_basic.py | 2 +- tests/experimental/pydantic/schema/test_defaults.py | 1 + tests/experimental/pydantic/schema/test_federation.py | 3 ++- tests/experimental/pydantic/schema/test_forward_reference.py | 1 + tests/experimental/pydantic/schema/test_mutation.py | 1 + tests/experimental/pydantic/test_basic.py | 2 +- tests/experimental/pydantic/test_conversion.py | 2 +- tests/experimental/pydantic/test_error_type.py | 2 +- tests/experimental/pydantic/test_fields.py | 4 ++-- 13 files changed, 15 insertions(+), 7 deletions(-) diff --git a/strawberry/experimental/pydantic/_compat.py b/strawberry/experimental/pydantic/_compat.py index dc3c2fe08f..9971c962b5 100644 --- a/strawberry/experimental/pydantic/_compat.py +++ b/strawberry/experimental/pydantic/_compat.py @@ -8,6 +8,7 @@ import pydantic from pydantic import BaseModel from pydantic.version import VERSION as PYDANTIC_VERSION + from strawberry.experimental.pydantic.exceptions import UnsupportedTypeError if TYPE_CHECKING: diff --git a/strawberry/experimental/pydantic/error_type.py b/strawberry/experimental/pydantic/error_type.py index d07284e145..bbedfe610b 100644 --- a/strawberry/experimental/pydantic/error_type.py +++ b/strawberry/experimental/pydantic/error_type.py @@ -15,6 +15,7 @@ ) from pydantic import BaseModel + from strawberry.experimental.pydantic._compat import ( CompatModelField, PydanticCompat, diff --git a/strawberry/experimental/pydantic/fields.py b/strawberry/experimental/pydantic/fields.py index 3ded38fc29..9cac486290 100644 --- a/strawberry/experimental/pydantic/fields.py +++ b/strawberry/experimental/pydantic/fields.py @@ -3,6 +3,7 @@ from typing_extensions import Annotated from pydantic import BaseModel + from strawberry.experimental.pydantic._compat import ( PydanticCompat, get_args, diff --git a/strawberry/experimental/pydantic/utils.py b/strawberry/experimental/pydantic/utils.py index 9987c2ee59..912553fb98 100644 --- a/strawberry/experimental/pydantic/utils.py +++ b/strawberry/experimental/pydantic/utils.py @@ -14,6 +14,7 @@ ) from pydantic import BaseModel + from strawberry.experimental.pydantic._compat import ( CompatModelField, PydanticCompat, diff --git a/tests/experimental/pydantic/schema/test_basic.py b/tests/experimental/pydantic/schema/test_basic.py index 75b6411bd2..f816208978 100644 --- a/tests/experimental/pydantic/schema/test_basic.py +++ b/tests/experimental/pydantic/schema/test_basic.py @@ -3,9 +3,9 @@ from enum import Enum from typing import List, Optional, Union +import pydantic import pytest -import pydantic import strawberry from tests.experimental.pydantic.utils import needs_pydantic_v1 diff --git a/tests/experimental/pydantic/schema/test_defaults.py b/tests/experimental/pydantic/schema/test_defaults.py index 6708ee036e..6d87c690a7 100644 --- a/tests/experimental/pydantic/schema/test_defaults.py +++ b/tests/experimental/pydantic/schema/test_defaults.py @@ -2,6 +2,7 @@ from typing import Optional import pydantic + import strawberry from strawberry.printer import print_schema from tests.conftest import skip_if_gql_32 diff --git a/tests/experimental/pydantic/schema/test_federation.py b/tests/experimental/pydantic/schema/test_federation.py index 90a506d62e..47bd56c2f9 100644 --- a/tests/experimental/pydantic/schema/test_federation.py +++ b/tests/experimental/pydantic/schema/test_federation.py @@ -1,7 +1,8 @@ import typing -import strawberry from pydantic import BaseModel + +import strawberry from strawberry.federation.schema_directives import Key diff --git a/tests/experimental/pydantic/schema/test_forward_reference.py b/tests/experimental/pydantic/schema/test_forward_reference.py index 23ad750b51..ebc94d4b37 100644 --- a/tests/experimental/pydantic/schema/test_forward_reference.py +++ b/tests/experimental/pydantic/schema/test_forward_reference.py @@ -4,6 +4,7 @@ from typing import Optional import pydantic + import strawberry diff --git a/tests/experimental/pydantic/schema/test_mutation.py b/tests/experimental/pydantic/schema/test_mutation.py index a1efa945cd..03e545eece 100644 --- a/tests/experimental/pydantic/schema/test_mutation.py +++ b/tests/experimental/pydantic/schema/test_mutation.py @@ -1,6 +1,7 @@ from typing import Dict, List, Union import pydantic + import strawberry from strawberry.experimental.pydantic._compat import IS_PYDANTIC_V2 diff --git a/tests/experimental/pydantic/test_basic.py b/tests/experimental/pydantic/test_basic.py index 2540ff99f1..9556d3f617 100644 --- a/tests/experimental/pydantic/test_basic.py +++ b/tests/experimental/pydantic/test_basic.py @@ -3,9 +3,9 @@ from typing import Any, List, Optional, Union from typing_extensions import Annotated +import pydantic import pytest -import pydantic import strawberry from strawberry.experimental.pydantic.exceptions import MissingFieldsListError from strawberry.schema_directive import Location diff --git a/tests/experimental/pydantic/test_conversion.py b/tests/experimental/pydantic/test_conversion.py index 8963c3e6ae..745e5e90c4 100644 --- a/tests/experimental/pydantic/test_conversion.py +++ b/tests/experimental/pydantic/test_conversion.py @@ -6,9 +6,9 @@ from typing import Any, Dict, List, NewType, Optional, TypeVar, Union import pytest +from pydantic import BaseModel, Field, ValidationError import strawberry -from pydantic import BaseModel, Field, ValidationError from strawberry.experimental.pydantic._compat import ( IS_PYDANTIC_V2, CompatModelField, diff --git a/tests/experimental/pydantic/test_error_type.py b/tests/experimental/pydantic/test_error_type.py index 37af6e51e3..8e37c6402c 100644 --- a/tests/experimental/pydantic/test_error_type.py +++ b/tests/experimental/pydantic/test_error_type.py @@ -1,8 +1,8 @@ from typing import List, Optional +import pydantic import pytest -import pydantic import strawberry from strawberry.experimental.pydantic.exceptions import MissingFieldsListError from strawberry.types.base import ( diff --git a/tests/experimental/pydantic/test_fields.py b/tests/experimental/pydantic/test_fields.py index 884236f704..878969b9af 100644 --- a/tests/experimental/pydantic/test_fields.py +++ b/tests/experimental/pydantic/test_fields.py @@ -2,11 +2,11 @@ from typing import List from typing_extensions import Literal +import pydantic import pytest +from pydantic import BaseModel, ValidationError, conlist -import pydantic import strawberry -from pydantic import BaseModel, ValidationError, conlist from strawberry.experimental.pydantic._compat import IS_PYDANTIC_V1 from strawberry.types.base import StrawberryObjectDefinition, StrawberryOptional from tests.experimental.pydantic.utils import needs_pydantic_v1, needs_pydantic_v2 From e314998b15228da3ac9efdf9e053cfd2983bf338 Mon Sep 17 00:00:00 2001 From: Patrick Arminio Date: Mon, 9 Dec 2024 00:15:05 +0000 Subject: [PATCH 08/10] Add release file --- RELEASE.md | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 RELEASE.md diff --git a/RELEASE.md b/RELEASE.md new file mode 100644 index 0000000000..b099974c24 --- /dev/null +++ b/RELEASE.md @@ -0,0 +1,51 @@ +Release type: minor + +This release adds support for making Relay connection optional, this is useful +when you want to add permission classes to the connection and not fail the whole +query if the user doesn't have permission to access the connection. + +Example: + +```python +import strawberry +from strawberry import relay +from strawberry.permission import BasePermission + + +class IsAuthenticated(BasePermission): + message = "User is not authenticated" + + # This method can also be async! + def has_permission( + self, source: typing.Any, info: strawberry.Info, **kwargs + ) -> bool: + return False + + +@strawberry.type +class Fruit(relay.Node): + code: relay.NodeID[int] + name: str + weight: float + + @classmethod + def resolve_nodes( + cls, + *, + info: strawberry.Info, + node_ids: Iterable[str], + ): + return [] + + +@strawberry.type +class Query: + node: relay.Node = relay.node() + + @relay.connection( + relay.ListConnection[Fruit] | None, permission_classes=[IsAuthenticated()] + ) + def fruits(self) -> Iterable[Fruit]: + # This can be a database query, a generator, an async generator, etc + return all_fruits.values() +``` From 3c066e82018e6e0014322b7adccf82e6ba9408c7 Mon Sep 17 00:00:00 2001 From: Patrick Arminio Date: Thu, 19 Dec 2024 18:34:09 +0100 Subject: [PATCH 09/10] Update tests/relay/test_connection.py Co-authored-by: Thiago Bellini Ribeiro --- tests/relay/test_connection.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/relay/test_connection.py b/tests/relay/test_connection.py index 08cb789243..f84d398895 100644 --- a/tests/relay/test_connection.py +++ b/tests/relay/test_connection.py @@ -104,8 +104,8 @@ class Query: @strawberry.relay.connection( Optional[UserConnection], permission_classes=[TestPermission] ) - def users(self) -> Optional[List[User]]: - return None + def users(self) -> Optional[List[User]]: # pragma: no cover + pytest.fail("Should not have been called...") schema = strawberry.Schema(query=Query) query = """ From 304c648b4ff107aff079da8728c114b69261426d Mon Sep 17 00:00:00 2001 From: Patrick Arminio Date: Fri, 20 Dec 2024 14:08:33 +0100 Subject: [PATCH 10/10] Add check --- strawberry/relay/fields.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/strawberry/relay/fields.py b/strawberry/relay/fields.py index 3c605c1129..32673cfc10 100644 --- a/strawberry/relay/fields.py +++ b/strawberry/relay/fields.py @@ -43,7 +43,7 @@ from strawberry.types.fields.resolver import StrawberryResolver from strawberry.types.lazy_type import LazyType from strawberry.utils.aio import asyncgen_to_list -from strawberry.utils.typing import eval_type, is_generic_alias, is_union +from strawberry.utils.typing import eval_type, is_generic_alias, is_optional, is_union from .types import Connection, GlobalID, Node @@ -257,7 +257,8 @@ def apply(self, field: StrawberryField) -> None: ) if is_union(resolver_type): - # TODO: actually check if is optional and get correct type + assert is_optional(resolver_type) + resolver_type = get_args(resolver_type)[0] origin = get_origin(resolver_type)