Python graphene.ObjectType() Examples

The following are 30 code examples of graphene.ObjectType(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module graphene , or try the search function .
Example #1
Source File: test_types.py    From graphene-gae with BSD 3-Clause "New" or "Revised" License 8 votes vote down vote up
def testQuery_excludedField(self):
        Article(headline="h1", summary="s1").put()

        class ArticleType(NdbObjectType):
            class Meta:
                model = Article
                exclude_fields = ['summary']

        class QueryType(graphene.ObjectType):
            articles = graphene.List(ArticleType)

            def resolve_articles(self, info):
                return Article.query()

        schema = graphene.Schema(query=QueryType)
        query = '''
            query ArticlesQuery {
              articles { headline, summary }
            }
        '''

        result = schema.execute(query)

        self.assertIsNotNone(result.errors)
        self.assertTrue('Cannot query field "summary"' in result.errors[0].message) 
Example #2
Source File: test_schema.py    From graphql-over-kafka with MIT License 6 votes vote down vote up
def test_does_not_auto_camel_case(self):

        # a query to test with a snake case field
        class TestQuery(ObjectType):
            test_field = String()

            def resolve_test_field(self, args, info):
                return 'hello'

        # assign the query to the schema
        self.schema.query = TestQuery

        # the query to test
        test_query = "query {test_field}"

        # execute the query
        resolved_query = self.schema.execute(test_query)

        assert 'test_field' in resolved_query.data, (
            "Schema did not have snake_case field."
        )

        assert resolved_query.data['test_field'] == 'hello', (
            "Snake_case field did not have the right value"
        ) 
Example #3
Source File: test_relay_query.py    From graphene-mongo with MIT License 6 votes vote down vote up
def test_should_filter_by_id(fixtures):
    # Notes: https://goo.gl/hMNRgs
    class Query(graphene.ObjectType):
        reporter = Node.Field(nodes.ReporterNode)

    query = """
        query ReporterQuery {
            reporter (id: "UmVwb3J0ZXJOb2RlOjE=") {
                id,
                firstName,
                awards
            }
        }
    """
    expected = {
        "reporter": {
            "id": "UmVwb3J0ZXJOb2RlOjE=",
            "firstName": "Allen",
            "awards": ["2010-mvp"],
        }
    }
    schema = graphene.Schema(query=Query)
    result = schema.execute(query)
    assert not result.errors
    assert result.data == expected 
Example #4
Source File: test_utils.py    From graphene-sqlalchemy with MIT License 6 votes vote down vote up
def test_get_session():
    session = "My SQLAlchemy session"

    class Query(ObjectType):
        x = String()

        def resolve_x(self, info):
            return get_session(info.context)

    query = """
        query ReporterQuery {
            x
        }
    """

    schema = Schema(query=Query)
    result = schema.execute(query, context_value={"session": session})
    assert not result.errors
    assert result.data["x"] == session 
Example #5
Source File: service.py    From graphene-federation with MIT License 6 votes vote down vote up
def get_service_query(schema):
    sdl_str = get_sdl(schema, custom_entities)

    class _Service(ObjectType):
        sdl = String()

        def resolve_sdl(parent, _):
            return sdl_str

    class ServiceQuery(ObjectType):
        _service = Field(_Service, name="_service")

        def resolve__service(parent, info):
            return _Service()

    return ServiceQuery 
Example #6
Source File: test_types.py    From graphene-mongo with MIT License 6 votes vote down vote up
def test_objecttype_registered():
    assert issubclass(Character, ObjectType)
    assert Character._meta.model == Reporter
    assert set(Character._meta.fields.keys()) == set(
        [
            "id",
            "first_name",
            "last_name",
            "email",
            "embedded_articles",
            "embedded_list_articles",
            "articles",
            "awards",
            "generic_reference",
            "generic_embedded_document",
            "generic_references",
        ]
    ) 
Example #7
Source File: test_types.py    From graphene-gae with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def testQuery_onlyFields(self):
        Article(headline="h1", summary="s1").put()

        class ArticleType(NdbObjectType):
            class Meta:
                model = Article
                only_fields = ['headline']

        class QueryType(graphene.ObjectType):
            articles = graphene.List(ArticleType)

            def resolve_articles(self, info):
                return Article.query()

        schema = graphene.Schema(query=QueryType)
        query = '''
                    query ArticlesQuery {
                      articles { headline }
                    }
                '''

        result = schema.execute(query)

        self.assertIsNotNone(result.data)
        self.assertEqual(result.data['articles'][0]['headline'], 'h1')

        query = '''
                    query ArticlesQuery {
                      articles { headline, summary }
                    }
                '''
        result = schema.execute(query)

        self.assertIsNotNone(result.errors)
        self.assertTrue('Cannot query field "summary"' in result.errors[0].message) 
Example #8
Source File: test_mutation.py    From graphene-django with MIT License 5 votes vote down vote up
def test_model_form_mutation_invalid_input(pet_type):
    class PetMutation(DjangoModelFormMutation):
        pet = Field(pet_type)

        class Meta:
            form_class = PetForm

    class Mutation(ObjectType):
        pet_mutation = PetMutation.Field()

    schema = Schema(query=MockQuery, mutation=Mutation)

    result = schema.execute(
        """ mutation PetMutation {
            petMutation(input: { name: "Mia", age: 99 }) {
                pet {
                    name
                    age
                }
                errors {
                    field
                    messages
                }
            }
        }
        """
    )
    assert result.errors is None
    assert result.data["petMutation"]["pet"] is None
    assert result.data["petMutation"]["errors"] == [
        {"field": "age", "messages": ["Too old"]}
    ]

    assert Pet.objects.count() == 0 
Example #9
Source File: generate_api_schema.py    From graphql-over-kafka with MIT License 5 votes vote down vote up
def generate_api_schema(models, connections=[], mutations=[], **schema_args):

    # collect the schema types
    schema_types = []

    # for each model
    for model in models:
        # find any matching connections
        model_connections = [connection for connection in connections \
                    if connection['connection']['from']['service'] == model['name']]
        # build a graphql type for the model
        graphql_type = graphql_type_from_summary(model, model_connections)

        # add the graphql type to the list
        schema_types.append(graphql_type)

    # if there are types for the schema
    if schema_types:
        # create a query with a connection to each model
        query = type('Query', (ObjectType,), {
            field.__name__: List(field) for field in schema_types
        })

        # create mutations for each provided mutation
        mutations = [graphql_mutation_from_summary(mut) for mut in mutations]

        # if there are mutations to add
        if mutations:
            # create an object type to contain the mutations
            mutations = type('Mutations', (ObjectType,), {
                mut._meta.object_name: graphene.Field(mut) for mut in mutations
            })

        # build the schema with the query object
        schema = graphene.Schema(
            query=query,
            mutation=mutations,
            **schema_args
        )

        return schema 
Example #10
Source File: test_fields.py    From graphene-django with MIT License 5 votes vote down vote up
def test_only_django_object_types(self):
        class TestType(ObjectType):
            foo = String()

        with pytest.raises(AssertionError):
            list_field = DjangoListField(TestType) 
Example #11
Source File: test_fields.py    From graphene-django with MIT License 5 votes vote down vote up
def test_list_field_default_queryset(self):
        class Reporter(DjangoObjectType):
            class Meta:
                model = ReporterModel
                fields = ("first_name",)

        class Query(ObjectType):
            reporters = DjangoListField(Reporter)

        schema = Schema(query=Query)

        query = """
            query {
                reporters {
                    firstName
                }
            }
        """

        ReporterModel.objects.create(first_name="Tara", last_name="West")
        ReporterModel.objects.create(first_name="Debra", last_name="Payne")

        result = schema.execute(query)

        assert not result.errors
        assert result.data == {
            "reporters": [{"firstName": "Tara"}, {"firstName": "Debra"}]
        } 
Example #12
Source File: test_query.py    From graphene-mongo with MIT License 5 votes vote down vote up
def test_should_query_with_embedded_document(fixtures):
    class Query(graphene.ObjectType):
        professor_vector = graphene.Field(
            types.ProfessorVectorType, id=graphene.String()
        )

        def resolve_professor_vector(self, info, id):
            return models.ProfessorVector.objects(metadata__id=id).first()

    query = """
        query {
          professorVector(id: "5e06aa20-6805-4eef-a144-5615dedbe32b") {
            vec
            metadata {
                firstName
            }
          }
        }
    """

    expected = {
        "professorVector": {"vec": [1.0, 2.3], "metadata": {"firstName": "Steven"}}
    }
    schema = graphene.Schema(query=Query, types=[types.ProfessorVectorType])
    result = schema.execute(query)
    assert not result.errors
    assert result.data == expected 
Example #13
Source File: test_types.py    From graphene-django with MIT License 5 votes vote down vote up
def test_django_objecttype_convert_choices_enum_false(self, PetModel):
        class Pet(DjangoObjectType):
            class Meta:
                model = PetModel
                convert_choices_to_enum = False

        class Query(ObjectType):
            pet = Field(Pet)

        schema = Schema(query=Query)

        assert str(schema) == dedent(
            """\
        schema {
          query: Query
        }

        type Pet {
          id: ID!
          kind: String!
          cuteness: Int!
        }

        type Query {
          pet: Pet
        }
        """
        ) 
Example #14
Source File: test_types.py    From graphene-django with MIT License 5 votes vote down vote up
def test_django_objecttype_convert_choices_enum_list(self, PetModel):
        class Pet(DjangoObjectType):
            class Meta:
                model = PetModel
                convert_choices_to_enum = ["kind"]

        class Query(ObjectType):
            pet = Field(Pet)

        schema = Schema(query=Query)

        assert str(schema) == dedent(
            """\
        schema {
          query: Query
        }

        type Pet {
          id: ID!
          kind: PetModelKind!
          cuteness: Int!
        }

        enum PetModelKind {
          CAT
          DOG
        }

        type Query {
          pet: Pet
        }
        """
        ) 
Example #15
Source File: test_types.py    From graphene-django with MIT License 5 votes vote down vote up
def test_django_objecttype_convert_choices_enum_empty_list(self, PetModel):
        class Pet(DjangoObjectType):
            class Meta:
                model = PetModel
                convert_choices_to_enum = []

        class Query(ObjectType):
            pet = Field(Pet)

        schema = Schema(query=Query)

        assert str(schema) == dedent(
            """\
        schema {
          query: Query
        }

        type Pet {
          id: ID!
          kind: String!
          cuteness: Int!
        }

        type Query {
          pet: Pet
        }
        """
        ) 
Example #16
Source File: test_types.py    From graphene-django with MIT License 5 votes vote down vote up
def test_django_objecttype_convert_choices_enum_naming_collisions(
        self, PetModel, graphene_settings
    ):
        graphene_settings.DJANGO_CHOICE_FIELD_ENUM_V3_NAMING = True

        class PetModelKind(DjangoObjectType):
            class Meta:
                model = PetModel
                fields = ["id", "kind"]

        class Query(ObjectType):
            pet = Field(PetModelKind)

        schema = Schema(query=Query)

        assert str(schema) == dedent(
            """\
        schema {
          query: Query
        }

        type PetModelKind {
          id: ID!
          kind: TestsPetModelKindChoices!
        }

        type Query {
          pet: PetModelKind
        }

        enum TestsPetModelKindChoices {
          CAT
          DOG
        }
        """
        ) 
Example #17
Source File: test_mutation.py    From graphene-django with MIT License 5 votes vote down vote up
def test_model_form_mutation_creates_new(pet_type):
    class PetMutation(DjangoModelFormMutation):
        pet = Field(pet_type)

        class Meta:
            form_class = PetForm

    class Mutation(ObjectType):
        pet_mutation = PetMutation.Field()

    schema = Schema(query=MockQuery, mutation=Mutation)

    result = schema.execute(
        """ mutation PetMutation {
            petMutation(input: { name: "Mia", age: 10 }) {
                pet {
                    name
                    age
                }
                errors {
                    field
                    messages
                }
            }
        }
        """
    )
    assert result.errors is None
    assert result.data["petMutation"]["pet"] == {"name": "Mia", "age": 10}

    assert Pet.objects.count() == 1
    pet = Pet.objects.get()
    assert pet.name == "Mia"
    assert pet.age == 10 
Example #18
Source File: test_relay_query.py    From graphene-mongo with MIT License 5 votes vote down vote up
def test_should_filter_mongoengine_queryset_with_list(fixtures):
    class Query(graphene.ObjectType):
        players = MongoengineConnectionField(nodes.PlayerNode)

    query = """
        query players {
            players(firstName_In: ["Michael", "Magic"]) {
                edges {
                    node {
                        firstName
                    }
                }
            }
        }
    """
    expected = {
        "players": {
            "edges": [
                {"node": {"firstName": "Michael"}},
                {"node": {"firstName": "Magic"}},
            ]
        }
    }
    schema = graphene.Schema(query=Query)
    result = schema.execute(query)

    assert not result.errors
    assert json.dumps(result.data, sort_keys=True) == json.dumps(
        expected, sort_keys=True
    ) 
Example #19
Source File: graphql_type_from_summary.py    From graphql-over-kafka with MIT License 5 votes vote down vote up
def graphql_type_from_summary(summary, connections=[]):
    # the name of the type
    name = summary['name']
    # the fields of the type
    fields = {
        field['name']: getattr(graphene, field['type'])() \
                                    for field in summary['fields']
    }
    # add the connections to the model
    # for connection in connec
    connections = {
        field['name']: graphene.List(field['connection']['to']['service']) \
                                    for field in connections
    }
    # print(connections)
    # merge the two field dictionaries
    class_fields = {
        **fields,
        **connections
    }

    graphql_type = type(name, (graphene.ObjectType,), class_fields)
    graphql_type._service_name = name

    # create the class record for the model
    return graphql_type 
Example #20
Source File: test_relay_query.py    From graphene-mongo with MIT License 5 votes vote down vote up
def test_should_query_document_with_embedded(fixtures):
    class Query(graphene.ObjectType):
        foos = MongoengineConnectionField(nodes.FooNode)

        def resolve_multiple_foos(self, *args, **kwargs):
            return list(models.Foo.objects.all())

    query = """
        query {
            foos {
                edges {
                    node {
                        bars {
                            edges {
                                node {
                                    someListField
                                }
                            }
                        }
                    }
                }
            }
        }
    """

    schema = graphene.Schema(query=Query)
    result = schema.execute(query)
    assert not result.errors 
Example #21
Source File: test_relay_query.py    From graphene-mongo with MIT License 5 votes vote down vote up
def test_should_filter_mongoengine_queryset(fixtures):
    class Query(graphene.ObjectType):
        players = MongoengineConnectionField(nodes.PlayerNode)

    query = """
        query players {
            players(firstName_Istartswith: "M") {
                edges {
                    node {
                        firstName
                    }
                }
            }
        }
    """
    expected = {
        "players": {
            "edges": [
                {"node": {"firstName": "Michael"}},
                {"node": {"firstName": "Magic"}},
            ]
        }
    }
    schema = graphene.Schema(query=Query)
    result = schema.execute(query)

    assert not result.errors
    assert json.dumps(result.data, sort_keys=True) == json.dumps(
        expected, sort_keys=True
    ) 
Example #22
Source File: test_relay_query.py    From graphene-mongo with MIT License 5 votes vote down vote up
def test_should_get_queryset_returns_dict_filters(fixtures):
    class Query(graphene.ObjectType):
        node = Node.Field()
        articles = MongoengineConnectionField(
            nodes.ArticleNode, get_queryset=lambda *_, **__: {"headline": "World"}
        )

    query = """
           query ArticlesQuery {
               articles {
                   edges {
                       node {
                           headline,
                           pubDate,
                           editor {
                               firstName
                           }
                       }
                   }
               }
           }
       """
    expected = {
        "articles": {
            "edges": [
                {
                    "node": {
                        "headline": "World",
                        "editor": {"firstName": "Grant"},
                        "pubDate": "2020-01-01T00:00:00",
                    }
                }
            ]
        }
    }
    schema = graphene.Schema(query=Query)
    result = schema.execute(query)
    assert not result.errors
    assert result.data == expected 
Example #23
Source File: test_relay_query.py    From graphene-mongo with MIT License 5 votes vote down vote up
def test_should_query_with_embedded_document(fixtures):
    class Query(graphene.ObjectType):

        professors = MongoengineConnectionField(nodes.ProfessorVectorNode)

    query = """
    query {
        professors {
            edges {
                node {
                    vec,
                    metadata {
                        firstName
                    }
                }
            }
        }
    }
    """
    expected = {
        "professors": {
            "edges": [
                {"node": {"vec": [1.0, 2.3], "metadata": {"firstName": "Steven"}}}
            ]
        }
    }
    schema = graphene.Schema(query=Query)
    result = schema.execute(query)
    assert not result.errors
    assert result.data == expected 
Example #24
Source File: test_relay_query.py    From graphene-mongo with MIT License 5 votes vote down vote up
def test_should_last_n(fixtures):
    class Query(graphene.ObjectType):
        players = MongoengineConnectionField(nodes.PlayerNode)

    query = """
        query PlayerQuery {
            players(last: 2) {
                edges {
                    cursor,
                    node {
                        firstName
                    }
                }
            }
        }
    """
    expected = {
        "players": {
            "edges": [
                {"cursor": "YXJyYXljb25uZWN0aW9uOjI=", "node": {"firstName": "Larry"}},
                {"cursor": "YXJyYXljb25uZWN0aW9uOjM=", "node": {"firstName": "Chris"}},
            ]
        }
    }
    schema = graphene.Schema(query=Query)
    result = schema.execute(query)

    assert not result.errors
    assert result.data == expected 
Example #25
Source File: test_relay_query.py    From graphene-mongo with MIT License 5 votes vote down vote up
def test_should_before(fixtures):
    class Query(graphene.ObjectType):

        players = MongoengineConnectionField(nodes.PlayerNode)

    query = """
        query EditorQuery {
            players(before: "YXJyYXljb25uZWN0aW9uOjI=") {
                edges {
                    cursor,
                    node {
                        firstName
                    }
                }
            }
        }
    """
    expected = {
        "players": {
            "edges": [
                {
                    "cursor": "YXJyYXljb25uZWN0aW9uOjA=",
                    "node": {"firstName": "Michael"},
                },
                {"cursor": "YXJyYXljb25uZWN0aW9uOjE=", "node": {"firstName": "Magic"}},
            ]
        }
    }
    schema = graphene.Schema(query=Query)
    result = schema.execute(query)

    assert not result.errors
    assert result.data == expected 
Example #26
Source File: test_relay_query.py    From graphene-mongo with MIT License 5 votes vote down vote up
def test_should_filter_through_inheritance(fixtures):
    class Query(graphene.ObjectType):
        node = Node.Field()
        children = MongoengineConnectionField(nodes.ChildNode)

    query = """
        query ChildrenQuery {
            children(bar: "bar") {
                edges {
                    node {
                        bar,
                        baz,
                        loc {
                             type,
                             coordinates
                        }
                    }
                }
            }
        }
    """
    expected = {
        "children": {
            "edges": [
                {
                    "node": {
                        "bar": "bar",
                        "baz": "baz",
                        "loc": {"type": "Point", "coordinates": [10.0, 20.0]},
                    }
                }
            ]
        }
    }
    schema = graphene.Schema(query=Query)
    result = schema.execute(query)
    assert not result.errors
    assert result.data == expected 
Example #27
Source File: test_relay_query.py    From graphene-mongo with MIT License 5 votes vote down vote up
def test_should_filter_by_reference_field(fixtures):
    class Query(graphene.ObjectType):
        articles = MongoengineConnectionField(nodes.ArticleNode)

    query = """
        query ArticlesQuery {
            articles(editor: "RWRpdG9yTm9kZTox") {
                edges {
                    node {
                        headline,
                        editor {
                            firstName
                        }
                    }
                }
            }
        }
    """
    expected = {
        "articles": {
            "edges": [{"node": {"headline": "Hello", "editor": {"firstName": "Penny"}}}]
        }
    }
    schema = graphene.Schema(query=Query)
    result = schema.execute(query)
    assert not result.errors
    assert result.data == expected 
Example #28
Source File: test_relay_query.py    From graphene-mongo with MIT License 5 votes vote down vote up
def test_should_filter_editors_by_id(fixtures):
    class Query(graphene.ObjectType):
        editors = MongoengineConnectionField(nodes.EditorNode)

    query = """
        query EditorQuery {
          editors(id: "RWRpdG9yTm9kZToy") {
            edges {
                node {
                    id,
                    firstName,
                    lastName
                }
            }
          }
        }
    """
    expected = {
        "editors": {
            "edges": [
                {
                    "node": {
                        "id": "RWRpdG9yTm9kZToy",
                        "firstName": "Grant",
                        "lastName": "Hill",
                    }
                }
            ]
        }
    }
    schema = graphene.Schema(query=Query)
    result = schema.execute(query)
    assert not result.errors
    assert result.data == expected 
Example #29
Source File: test_query.py    From graphene-mongo with MIT License 5 votes vote down vote up
def test_should_query_child(fixtures):
    class Query(graphene.ObjectType):

        children = graphene.List(types.ChildType)

        def resolve_children(self, *args, **kwargs):
            return list(models.Child.objects.all())

    query = """
        query Query {
            children {
                bar,
                baz,
                loc {
                     type,
                     coordinates
                }
            }
        }
    """
    expected = {
        "children": [
            {"bar": "BAR", "baz": "BAZ", "loc": None},
            {
                "bar": "bar",
                "baz": "baz",
                "loc": {"type": "Point", "coordinates": [10.0, 20.0]},
            },
        ]
    }

    schema = graphene.Schema(query=Query)
    result = schema.execute(query)
    assert not result.errors
    assert result.data == expected 
Example #30
Source File: test_types.py    From graphene-django with MIT License 5 votes vote down vote up
def test_django_objecttype_choices_custom_enum_name(
        self, PetModel, graphene_settings
    ):
        graphene_settings.DJANGO_CHOICE_FIELD_ENUM_CUSTOM_NAME = (
            "graphene_django.tests.test_types.custom_enum_name"
        )

        class PetModelKind(DjangoObjectType):
            class Meta:
                model = PetModel
                fields = ["id", "kind"]

        class Query(ObjectType):
            pet = Field(PetModelKind)

        schema = Schema(query=Query)

        assert str(schema) == dedent(
            """\
        schema {
          query: Query
        }

        enum CustomEnumKind {
          CAT
          DOG
        }

        type PetModelKind {
          id: ID!
          kind: CustomEnumKind!
        }

        type Query {
          pet: PetModelKind
        }
        """
        )