Add unions support
from dataclasses import dataclass
import pytest
-from graphql import GraphQLError
+from graphql import GraphQLError, graphql_sync
+from ..executable_schema import make_executable_schema
from ..object_type import ObjectType
from ..union_type import UnionType
@@ -88,6 +89,40 @@ class CommentType(ObjectType):
"""
+class ResultUnion(UnionType):
+ __schema__ = "union Result = Comment | User"
+ __requires__ = [CommentType, UserType]
+
+ @staticmethod
+ def resolve_type(instance, *_):
+ if isinstance(instance, Comment):
+ return "Comment"
+
+ if isinstance(instance, User):
+ return "User"
+
+ return None
+
+
+class QueryType(ObjectType):
+ __schema__ = """
+ type Query {
+ results: [Result!]!
+ }
+ """
+ __requires__ = [ResultUnion]
+
+ @staticmethod
+ def resolve_results(*_):
+ return [
+ User(id=1, name="Alice"),
+ Comment(id=1, message="Hello world!"),
+ ]
+
+
+schema = make_executable_schema(QueryType, UserType, CommentType)
+
+
def test_union_type_extracts_graphql_name():
class ExampleUnion(UnionType):
__schema__ = "union Example = User | Comment"
@@ -104,3 +139,38 @@ def test_union_type_raises_error_when_defined_without_member_type_dependency(sna
__requires__ = [UserType]
snapshot.assert_match(err)
+
+
+def test_interface_type_binds_type_resolver():
+ query = """
+ query {
+ results {
+ ... on User {
+ __typename
+ id
+ name
+ }
+ ... on Comment {
+ __typename
+ id
+ message
+ }
+ }
+ }
+ """
+
+ result = graphql_sync(schema, query)
+ assert result.data == {
+ "results": [
+ {
+ "__typename": "User",
+ "id": "1",
+ "name": "Alice",
+ },
+ {
+ "__typename": "Comment",
+ "id": "1",
+ "message": "Hello world!",
+ },
+ ],
+ }
