Graphene: Union types error in graphene version 1.0.2

Created on 4 Oct 2016  路  2Comments  路  Source: graphql-python/graphene

Hey guys,

I'm currently using graphene 1.0 and it all works great but when I tried to upgrade to version 1.0.2 I got this error where ever I use an Union type on my mutations:

GraphQLError('Abstract type CreatePostResult must resolve to an Object type at runtime for field CreatePost.result with value "<dependent_bug_example.schema.Success object at 0x10becb320>", received "None".',)

How to reproduce

Oh! yes I forgot. I'm using django==1.8.7 and graphene-django==1.0. But I just change graphene from 1.0 to 1.0.2 and this test breaks.

# models.py
class PostModel(models.Model):
    text = models.TextField()

# schema.py
# ...

class Post(DjangoObjectType):
    class Meta:
        interfaces = (relay.Node,)
        model = PostModel


class Success(graphene.ObjectType):
    post = graphene.Field(Post)


class Error(graphene.ObjectType):
    message = graphene.String()


class CreatePostResult(graphene.Union):
    class Meta:
        types = [Success, Error]


class CreatePost(Mutation):
    class Input:
        text = graphene.String(required=True)

    result = graphene.Field(CreatePostResult)

    @resolve_only_args
    def mutate(self, text):
        try:
            post = PostModel.objects.create(text=text)
            result = Success(post=post)
        except Exception as e:
            result = Error(message=str(e))

        return CreatePost(result=result)


class Mutations(graphene.ObjectType):
    create_post = CreatePost.Field()

# tests.py

def test_create_post():
    query_string = '''
    mutation {
      createPost(text: "Try this out") {
        result {
          __typename
        }
      }
    }
    '''

    schema = graphene.Schema(mutation=Mutations)
    result = schema.execute(query_string)

    assert not result.errors
    assert result.data['createPost']['result']['__typename'] == 'Success'

Most helpful comment

You should add resolve_type(...) to CreatePostResult

@staticmethod
def resolve_type(obj, context, info):
    if isinstance(obj, Success):
        return Success
    return Fail   

I think we need document for Union anyway.

All 2 comments

Just a shot in the dark, but you may need to add your own resolve_type method to CreatePostResult:

def resolve_type(self, _type):
    return type(_type)

You should add resolve_type(...) to CreatePostResult

@staticmethod
def resolve_type(obj, context, info):
    if isinstance(obj, Success):
        return Success
    return Fail   

I think we need document for Union anyway.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

romaia picture romaia  路  3Comments

mingzhou picture mingzhou  路  3Comments

tricoder42 picture tricoder42  路  4Comments

Globegitter picture Globegitter  路  4Comments

jloveric picture jloveric  路  4Comments