From 936a1d1602933f65e93382f06ddb00e47fa2e7de Mon Sep 17 00:00:00 2001 From: "sourcery-ai[bot]" Date: Wed, 20 Nov 2024 12:10:13 +0000 Subject: [PATCH 1/2] 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 2/2] [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