def test_order_by_is_perserved():
    class ReporterType(DjangoObjectType):
        class Meta:
            model = Reporter
            interfaces = (Node,)
            fields = "__all__"
            filter_fields = ()

    class Query(ObjectType):
        all_reporters = DjangoFilterConnectionField(
            ReporterType, reverse_order=Boolean()
        )

        def resolve_all_reporters(self, info, reverse_order=False, **args):
            reporters = Reporter.objects.order_by("first_name")

            if reverse_order:
                return reporters.reverse()

            return reporters

    Reporter.objects.create(first_name="b")
    Reporter.objects.create(first_name="a")

    schema = Schema(query=Query)
    query = """
        query NodeFilteringQuery {
            allReporters(first: 1) {
                edges {
                    node {
                        firstName
                    }
                }
            }
        }
    """
    expected = {"allReporters": {"edges": [{"node": {"firstName": "a"}}]}}

    result = schema.execute(query)
    assert not result.errors
    assert result.data == expected

    reverse_query = """
        query NodeFilteringQuery {
            allReporters(first: 1, reverseOrder: true) {
                edges {
                    node {
                        firstName
                    }
                }
            }
        }
    """

    reverse_expected = {"allReporters": {"edges": [{"node": {"firstName": "b"}}]}}

    reverse_result = schema.execute(reverse_query)

    assert not reverse_result.errors
    assert reverse_result.data == reverse_expected
    def test_field_types__specified__overrides_field_type(self):
        # This registers the UserNode type
        # noinspection PyUnresolvedReferences
        from .schema import UserNode

        class UpdateDogMutation(DjangoUpdateMutation):
            class Meta:
                model = Dog
                field_types = {"tag": graphene.Int()}

            @classmethod
            def handle_tag(self, value, *args, **kwargs):
                return f"Dog-{value}"

        class Mutations(graphene.ObjectType):
            update_dog = UpdateDogMutation.Field()

        dog = DogFactory.create()
        user = UserFactory.create()
        schema = Schema(mutation=Mutations)
        mutation = """
            mutation UpdateDog(
                $id: ID!,
                $input: UpdateDogInput! 
            ){
                updateDog(id: $id, input: $input){
                    dog{
                        id
                    }
                }
            }
        """
        # Result with a string in the tag field should fail now
        result = schema.execute(mutation,
                                variables={
                                    "id": to_global_id("DogNode", dog.id),
                                    "input": {
                                        "name": "Sparky",
                                        "tag": "not-an-int",
                                        "breed": "HUSKY",
                                        "owner":
                                        to_global_id("UserNode", user.id)
                                    }
                                },
                                context=Dict(user=user))
        self.assertEqual(len(result.errors), 1)

        result = schema.execute(mutation,
                                variables={
                                    "id": to_global_id("DogNode", dog.id),
                                    "input": {
                                        "name": "Sparky",
                                        "breed": "HUSKY",
                                        "tag": 25,
                                        "owner":
                                        to_global_id("UserNode", user.id)
                                    }
                                },
                                context=Dict(user=user))
        self.assertIsNone(result.errors)
    def test_get_permissions__list_with_permissions__requires_returned_permissions(
        self, ):
        # This registers the UserNode type
        # noinspection PyUnresolvedReferences
        from .schema import UserNode

        class UpdateCatMutation(DjangoUpdateMutation):
            class Meta:
                model = Cat

            @classmethod
            def get_permissions(cls, root, info, *args, **kwargs):
                return ["tests.change_cat"]

        class Mutations(graphene.ObjectType):
            update_cat = UpdateCatMutation.Field()

        user = UserFactory.create()
        user_with_permissions = UserWithPermissionsFactory.create(
            permissions=["tests.change_cat"])
        cat = CatFactory.create()
        schema = Schema(mutation=Mutations)
        mutation = """
            mutation UpdateCat(
                $id: ID!,
                $input: UpdateCatInput! 
            ){
                updateCat(id: $id, input: $input){
                    cat{
                        id
                    }
                }
            }
        """
        result = schema.execute(
            mutation,
            variables={
                "id": to_global_id("CatNode", cat.id),
                "input": {
                    "name": "Name",
                    "owner": to_global_id("UserNode", user.id)
                },
            },
            context=Dict(user=user),
        )
        self.assertEqual(len(result.errors), 1)

        result = schema.execute(
            mutation,
            variables={
                "id": to_global_id("CatNode", cat.id),
                "input": {
                    "name": "Name",
                    "owner": to_global_id("UserNode", user.id)
                },
            },
            context=Dict(user=user_with_permissions),
        )
        self.assertIsNone(result.errors)
    def test_check_permissions__override__uses_new_check_permissions_to_grant_access(
            self):
        # This registers the UserNode type
        # noinspection PyUnresolvedReferences
        from .schema import UserNode

        class UpdateCatMutation(DjangoUpdateMutation):
            class Meta:
                model = Cat
                # This will be overridden
                permissions = ("tests.change_cat", )

            @classmethod
            def check_permissions(cls, root, info, id, input) -> None:
                if input["name"] == "Name 2":
                    raise ValueError("Cannot be Name 2")

                return None

        class Mutations(graphene.ObjectType):
            update_cat = UpdateCatMutation.Field()

        user = UserFactory.create()
        cat = CatFactory.create()
        schema = Schema(mutation=Mutations)
        mutation = """
            mutation UpdateCat(
                $id: ID!,
                $input: UpdateCatInput! 
            ){
                updateCat(id: $id, input: $input){
                    cat{
                        id
                    }
                }
            }
        """
        result = schema.execute(mutation,
                                variables={
                                    "id": to_global_id("UserNode", user.id),
                                    "input": {
                                        "name": "Name 2",
                                        "owner":
                                        to_global_id("UserNode", user.id)
                                    }
                                },
                                context=Dict(user=user))
        self.assertEqual(len(result.errors), 1)
        result = schema.execute(mutation,
                                variables={
                                    "id": to_global_id("UserNode", user.id),
                                    "input": {
                                        "name": "Name 3",
                                        "owner":
                                        to_global_id("UserNode", user.id)
                                    }
                                },
                                context=Dict(user=user))
        self.assertIsNone(result.errors)
    def test_validate__validate_field_raises__returns_error(self):
        # This registers the UserNode type
        # noinspection PyUnresolvedReferences
        from .schema import UserNode

        class UpdateCatMutation(DjangoUpdateMutation):
            class Meta:
                model = Cat

            @classmethod
            def validate_name(cls, root, info, value, input, id, obj):
                owner = User.objects.get(pk=disambiguate_id(input["owner"]))
                if value == owner.get_full_name():
                    raise ValueError("Cat must have different name than owner")

        class Mutations(graphene.ObjectType):
            update_cat = UpdateCatMutation.Field()

        user = UserFactory.create(first_name="John", last_name="Doe")
        cat = CatFactory.create()
        schema = Schema(mutation=Mutations)
        mutation = """
            mutation UpdateCat(
                $id: ID!,
                $input: UpdateCatInput! 
            ){
                updateCat(id: $id, input: $input){
                    cat{
                        id
                    }
                }
            }
        """
        result = schema.execute(
            mutation,
            variables={
                "id": to_global_id("UserNode", user.id),
                "input": {
                    "name": "John Doe",
                    "owner": to_global_id("UserNode", user.id),
                },
            },
            context=Dict(user=user),
        )
        self.assertEqual(len(result.errors), 1)

        result = schema.execute(
            mutation,
            variables={
                "id": to_global_id("UserNode", user.id),
                "input": {
                    "name": "Kitty",
                    "owner": to_global_id("UserNode", user.id)
                },
            },
            context=Dict(user=user),
        )
        self.assertIsNone(result.errors)
Example #6
0
    def test_form_invalid_form(self):
        class MyMutation(DjangoFormMutation):
            class Meta:
                form_class = MyForm
                mirror_input = True

        class Mutation(ObjectType):
            my_mutation = MyMutation.Field()

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

        result = schema.execute(""" mutation MyMutation {
                myMutation(input: { text: "INVALID_INPUT" }) {
                    errors {
                        field
                        messages
                    }
                    text
                }
            }
            """)

        self.assertIs(result.errors, None)
        self.assertEqual(
            result.data["myMutation"]["errors"],
            [{
                "field": "text",
                "messages": ["Invalid input"]
            }],
        )
Example #7
0
def test_string_in_filter():
    """
    Test in filter on a string field.
    """
    Pet.objects.create(name="Brutus", age=12)
    Pet.objects.create(name="Mimi", age=3)
    Pet.objects.create(name="Jojo, the rabbit", age=3)

    schema = Schema(query=Query)

    query = """
    query {
        pets (name_In: ["Brutus", "Jojo, the rabbit"]) {
            edges {
                node {
                    name
                }
            }
        }
    }
    """
    result = schema.execute(query)
    assert not result.errors
    assert result.data["pets"]["edges"] == [
        {
            "node": {
                "name": "Brutus"
            }
        },
        {
            "node": {
                "name": "Jojo, the rabbit"
            }
        },
    ]
    def test_many_to_one_extras__add_by_input__adds_by_input(self):
        # This registers the UserNode type
        # noinspection PyUnresolvedReferences
        from .schema import UserNode

        class CreateCatMutation(DjangoCreateMutation):
            class Meta:
                model = Cat

        class UpdateUserMutation(DjangoUpdateMutation):
            class Meta:
                model = User
                exclude_fields = ("password", )
                many_to_one_extras = {"cats": {"add": {"type": "auto"}}}

        class Mutations(graphene.ObjectType):
            create_cat = CreateCatMutation.Field()
            update_user = UpdateUserMutation.Field()

        user = UserFactory.create()

        # Create some cats
        self.assertEqual(user.cats.all().count(), 0)

        schema = Schema(mutation=Mutations)
        mutation = """
            mutation UpdateUser(
                $id: ID!,
                $input: UpdateUserInput! 
            ){
                updateUser(id: $id, input: $input){
                    user{
                        id
                    }
                }
            }
        """

        result = schema.execute(mutation,
                                variables={
                                    "id": to_global_id("UserNode", user.id),
                                    "input": {
                                        "username":
                                        user.username,
                                        "firstName":
                                        user.first_name,
                                        "lastName":
                                        user.last_name,
                                        "email":
                                        user.email,
                                        "catsAdd": [{
                                            "name": "Cat damon"
                                        } for _ in range(5)]
                                    }
                                },
                                context=Dict(user=user))
        self.assertIsNone(result.errors)

        user.refresh_from_db()
        self.assertEqual(user.cats.all().count(), 5)
Example #9
0
def test_array_field_overlap_one(Query):
    """
    Test overlap filter on a array field of string.
    """

    schema = Schema(query=Query)

    query = """
    query {
        events (tags_Overlap: ["music"]) {
            edges {
                node {
                    name
                }
            }
        }
    }
    """
    result = schema.execute(query)
    assert not result.errors
    assert result.data["events"]["edges"] == [
        {
            "node": {
                "name": "Live Show"
            }
        },
        {
            "node": {
                "name": "Musical"
            }
        },
    ]
def test_string_in_filter_with_filterset_class():
    """Test in filter on a string field with a custom filterset class."""
    Person.objects.create(name="John")
    Person.objects.create(name="Michael")
    Person.objects.create(name="Angela")

    schema = Schema(query=Query)

    query = """
    query {
        people (names: ["John", "Michael"]) {
            edges {
                node {
                    name
                }
            }
        }
    }
    """
    result = schema.execute(query)
    assert not result.errors
    assert result.data["people"]["edges"] == [
        {
            "node": {
                "name": "John"
            }
        },
        {
            "node": {
                "name": "Michael"
            }
        },
    ]
Example #11
0
def test_string_in_filter_with_otjer_filter(query):
    """
    Test in filter on a string field which has also a custom filter doing a similar operation.
    """
    Person.objects.create(name="John")
    Person.objects.create(name="Michael")
    Person.objects.create(name="Angela")

    schema = Schema(query=query)

    query = """
    query {
        people (name_In: ["John", "Michael"]) {
            edges {
                node {
                    name
                }
            }
        }
    }
    """
    result = schema.execute(query)
    assert not result.errors
    assert result.data["people"]["edges"] == [
        {
            "node": {
                "name": "John"
            }
        },
        {
            "node": {
                "name": "Michael"
            }
        },
    ]
def main(req: func.HttpRequest, cmdl: bytes, cvec: bytes, clbl: str,
         nmdl: bytes, guid: str) -> func.HttpResponse:
    logging.info('Executing GraphQL function.')

    queue = QueueClient.from_connection_string(
        os.environ['AzureWebJobsStorage'], 'predictions')

    try:
        query = req.get_body().decode()
    except ValueError:
        pass

    if query:
        schema = Schema(Query)
        context = CACHE_MANAGER.get(guid, cmdl, cvec, clbl, nmdl)
        results = schema.execute(query, context=context)
        response = responses.graphql(results)

        # Write response to azure queue storage
        message = responses.storage(results)
        if message:
            queue.send_message(message, time_to_live=-1)

        return response
    else:
        return responses.bad_request(
            'Please pass a GraphQL query in the request body.')
def test_filter_filterset_related_results():
    class ReporterFilterNode(DjangoObjectType):

        class Meta:
            model = Reporter
            interfaces = (Node, )
            filter_fields = {
                'first_name': ['icontains']
            }

    class Query(ObjectType):
        all_reporters = DjangoFilterConnectionField(ReporterFilterNode)

    r1 = Reporter.objects.create(first_name='A test user', last_name='Last Name', email='*****@*****.**')
    r2 = Reporter.objects.create(first_name='Other test user', last_name='Other Last Name', email='*****@*****.**')
    r3 = Reporter.objects.create(first_name='Random', last_name='RandomLast', email='*****@*****.**')

    query = '''
    query {
        allReporters(firstName_Icontains: "test") {
            edges {
                node {
                    id
                }
            }
        }
    }
    '''
    schema = Schema(query=Query)
    result = schema.execute(query)
    assert not result.errors
    # We should only get two reporters
    assert len(result.data['allReporters']['edges']) == 2
Example #14
0
def test_node_get_queryset_is_called():
    class ReporterType(DjangoObjectType):
        class Meta:
            model = Reporter
            interfaces = (Node, )
            filter_fields = ()

        @classmethod
        def get_queryset(cls, queryset, info):
            return queryset.filter(first_name="b")

    class Query(ObjectType):
        all_reporters = DjangoFilterConnectionField(ReporterType,
                                                    reverse_order=Boolean())

    Reporter.objects.create(first_name="b")
    Reporter.objects.create(first_name="a")

    schema = Schema(query=Query)
    query = """
        query NodeFilteringQuery {
            allReporters(first: 10) {
                edges {
                    node {
                        firstName
                    }
                }
            }
        }
    """
    expected = {"allReporters": {"edges": [{"node": {"firstName": "b"}}]}}

    result = schema.execute(query)
    assert not result.errors
    assert result.data == expected
Example #15
0
def test_array_field_exact_empty_list(Query):
    """
    Test exact filter on a array field of string.
    """

    schema = Schema(query=Query)

    query = """
    query {
        events (tags: []) {
            edges {
                node {
                    name
                }
            }
        }
    }
    """
    result = schema.execute(query)
    assert not result.errors
    assert result.data["events"]["edges"] == [
        {
            "node": {
                "name": "Speech"
            }
        },
    ]
Example #16
0
def test_array_field_exact_match(Query):
    """
    Test exact filter on a array field of string.
    """

    schema = Schema(query=Query)

    query = """
    query {
        events (tags: ["movie", "music"]) {
            edges {
                node {
                    name
                }
            }
        }
    }
    """
    result = schema.execute(query)
    assert not result.errors
    assert result.data["events"]["edges"] == [
        {
            "node": {
                "name": "Musical"
            }
        },
    ]
Example #17
0
def test_relationship_child_with_filter(schema: Schema):
    result = schema.execute(''' {
        countries {
            name
            states: filterStates(where: {name: {ne: "Victoria"}}) {
                internalId
                name
            }
        }
    }''')
    assert not result.errors
    assert result.data == {
        'countries': [
            {
                'name': 'Australia',
                'states': [
                    {
                        'internalId': 2,
                        'name': 'New South Wales'
                    },
                ]
            },
            {
                'name': 'United States',
                'states': [
                    {
                        'internalId': 3,
                        'name': 'New York'
                    },
                ]
            },
        ]
    }
    def test_model_form_mutation_creates_new(self):
        class PetMutation(DjangoModelFormMutation):
            pet = Field(PetType)

            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
                    }
                }
            }
            """)
        self.assertIs(result.errors, None)
        self.assertEqual(result.data["petMutation"]["pet"], {
            "name": "Mia",
            "age": 10
        })

        self.assertEqual(Pet.objects.count(), 1)
        pet = Pet.objects.get()
        self.assertEqual(pet.name, "Mia")
        self.assertEqual(pet.age, 10)
Example #19
0
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
    def test_nested_list_field(self):
        class Article(DjangoObjectType):
            class Meta:
                model = ArticleModel
                fields = ("headline",)

        class Reporter(DjangoObjectType):
            class Meta:
                model = ReporterModel
                fields = ("first_name", "articles")

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

        schema = Schema(query=Query)

        query = """
            query {
                reporters {
                    firstName
                    articles {
                        headline
                    }
                }
            }
        """

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

        ArticleModel.objects.create(
            headline="Amazing news",
            reporter=r1,
            pub_date=datetime.date.today(),
            pub_date_time=datetime.datetime.now(),
            editor=r1,
        )
        ArticleModel.objects.create(
            headline="Not so good news",
            reporter=r1,
            pub_date=datetime.date.today(),
            pub_date_time=datetime.datetime.now(),
            editor=r1,
        )

        result = schema.execute(query)

        assert not result.errors
        assert result.data == {
            "reporters": [
                {
                    "firstName": "Tara",
                    "articles": [
                        {"headline": "Amazing news"},
                        {"headline": "Not so good news"},
                    ],
                },
                {"firstName": "Debra", "articles": []},
            ]
        }
Example #21
0
def test_model_form_mutation_mutate_existing(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)

    pet = Pet.objects.create(name="Axel", age=10)

    result = schema.execute(
        """ mutation PetMutation($pk: ID!) {
            petMutation(input: { id: $pk, name: "Mia", age: 10 }) {
                pet {
                    name
                    age
                }
            }
        }
        """,
        variable_values={"pk": pet.pk},
    )

    assert result.errors is None
    assert result.data["petMutation"]["pet"] == {"name": "Mia", "age": 10}

    assert Pet.objects.count() == 1
    pet.refresh_from_db()
    assert pet.name == "Mia"
Example #22
0
    def test_override_resolver(self):
        class Reporter(DjangoObjectType):
            class Meta:
                model = ReporterModel
                fields = ("first_name", )

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

            def resolve_reporters(_, info):
                return ReporterModel.objects.filter(first_name="Tara")

        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"}]}
def test_array_field_contains_multiple(Query):
    """
    Test contains filter on a array field of string.
    """

    schema = Schema(query=Query)

    query = """
    query {
        events (tags_Contains: ["concert", "music"]) {
            edges {
                node {
                    name
                }
            }
        }
    }
    """
    result = schema.execute(query)
    assert not result.errors
    assert result.data["events"]["edges"] == [
        {
            "node": {
                "name": "Live Show"
            }
        },
    ]
Example #24
0
def test_relationship_paginate_states_last_2(schema: Schema):
    result = schema.execute(''' {
        states: paginateStates(last: 2, orderBy: [NAME_ASC]) {
            edges {
                node {
                    internalId
                    name
                }
            }
        }
    }''')
    assert not result.errors
    assert result.data == {
        'states': {
            'edges': [
                {
                    'node': {
                        'internalId': 3,
                        'name': 'New York'
                    }
                },
                {
                    'node': {
                        'internalId': 1,
                        'name': 'Victoria'
                    }
                },
            ]
        }
    }
Example #25
0
def test_form_invalid_form():
    class MyMutation(DjangoFormMutation):
        class Meta:
            form_class = MyForm

    class Mutation(ObjectType):
        my_mutation = MyMutation.Field()

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

    result = schema.execute(
        """ mutation MyMutation {
            myMutation(input: { text: "INVALID_INPUT" }) {
                errors {
                    field
                    messages
                }
                text
            }
        }
        """
    )

    assert result.errors is None
    assert result.data["myMutation"]["errors"] == [
        {"field": "text", "messages": ["Invalid input"]}
    ]
    def test__many_to_one_relation_exists__creates_specified_fields(self):
        # This registers the UserNode type
        # noinspection PyUnresolvedReferences
        from .schema import UserNode

        class CreateDogMutation(DjangoCreateMutation):
            class Meta:
                model = Dog

        class Mutations(graphene.ObjectType):
            create_dog = CreateDogMutation.Field()

        user = UserFactory.create()
        cat = CatFactory.create()

        schema = Schema(mutation=Mutations)
        mutation = """
            mutation CreateDog(
                $input: CreateDogInput!
            ){
                createDog(input: $input){
                    dog{
                        id
                        enemies{
                            edges{
                                node{
                                    id
                                }
                            }
                        }
                    }
                }
            }
        """

        result = schema.execute(
            mutation,
            variables={
                "input": {
                    "name": "Sparky",
                    "breed": "HUSKY",
                    "tag": "1234",
                    "owner": to_global_id("UserNode", user.id),
                    "enemies": [to_global_id("CatNode", cat.id)],
                },
            },
            context=Dict(user=user),
        )

        self.assertIsNone(result.errors)
        data = Dict(result.data)
        self.assertIsNone(result.errors)
        self.assertEqual(to_global_id("CatNode", cat.id),
                         data.createDog.dog.enemies.edges[0].node.id)

        new_dog = Dog.objects.get(pk=disambiguate_id(data.createDog.dog.id))

        # Load from database
        cat.refresh_from_db()
        self.assertEqual(cat, new_dog.enemies.first())
Example #27
0
    def test_handles_relay_node(self):
        class A(ObjectType, interfaces=[relay.Node]):
            field = String()

        class B(ObjectType):
            a = Field(A)
            node = relay.Node.Field()

        class Root(ObjectType):
            stitched = Field(stitch(B))

            def resolve_stitched(self, info):
                return stitch(B)({'node': {'field': 'value'}})

        schema = Schema(query=Root)
        id_ = to_global_id('A', 'foo')
        result = schema.execute('''query Test($id: ID!) {
            stitched {
                node(id: $id) {
                    __typename,
                    ... on A { field }
                }
            }
        }''', variables={'id': id_})

        assert_gql_data_equals(
            result, {'stitched': {'node': {
                '__typename': 'A',
                'field': 'value'
            }}}
        )
def test_int_range_filter():
    """
    Test range filter on an integer field.
    """
    Pet.objects.create(name="Brutus", age=12)
    Pet.objects.create(name="Mimi", age=8)
    Pet.objects.create(name="Jojo, the rabbit", age=3)
    Pet.objects.create(name="Picotin", age=5)

    schema = Schema(query=Query)

    query = """
    query {
        pets (age_Range: [4, 9]) {
            edges {
                node {
                    name
                }
            }
        }
    }
    """
    result = schema.execute(query)
    assert not result.errors
    assert result.data["pets"]["edges"] == [
        {"node": {"name": "Mimi"}},
        {"node": {"name": "Picotin"}},
    ]
Example #29
0
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 #30
0
    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"
            }]
        }
def test_should_query_filter_node_double_limit_raises():
    class ReporterFilter(FilterSet):
        limit = NumberFilter(method='filter_limit')

        def filter_limit(self, queryset, name, value):
            return queryset[:value]

        class Meta:
            model = Reporter
            fields = ['first_name', ]

    class ReporterType(DjangoObjectType):

        class Meta:
            model = Reporter
            interfaces = (Node, )

    class Query(ObjectType):
        all_reporters = DjangoFilterConnectionField(
            ReporterType,
            filterset_class=ReporterFilter
        )

        def resolve_all_reporters(self, args, context, info):
            return Reporter.objects.order_by('a_choice')[:2]

    Reporter.objects.create(
        first_name='Bob',
        last_name='Doe',
        email='*****@*****.**',
        a_choice=2
    )
    r = Reporter.objects.create(
        first_name='John',
        last_name='Doe',
        email='*****@*****.**',
        a_choice=1
    )

    schema = Schema(query=Query)
    query = '''
        query NodeFilteringQuery {
            allReporters(limit: 1) {
                edges {
                    node {
                        id
                        firstName
                    }
                }
            }
        }
    '''

    result = schema.execute(query)
    assert len(result.errors) == 1
    assert str(result.errors[0]) == (
        'Received two sliced querysets (high mark) in the connection, please slice only in one.'
    )
Example #32
0
def test_schema_register_interfaces():
    class Query(ObjectType):
        f = Field(Character)

        def resolve_f(self, args, info):
            return Human()

    schema = Schema(query=Query)

    schema.register(Human)

    result = schema.execute("{ f { name } }")
    assert not result.errors
Example #33
0
def test_filter_filterset_related_results():
    class ReporterFilterNode(DjangoObjectType):

        class Meta:
            model = Reporter
            interfaces = (Node, )
            filter_fields = ['first_name', 'articles']
            filter_order_by = True

    class ArticleFilterNode(DjangoObjectType):

        class Meta:
            interfaces = (Node, )
            model = Article
            filter_fields = ['headline', 'reporter']
            filter_order_by = True

    class Query(ObjectType):
        all_reporters = DjangoFilterConnectionField(ReporterFilterNode)
        all_articles = DjangoFilterConnectionField(ArticleFilterNode)
        reporter = Field(ReporterFilterNode)
        article = Field(ArticleFilterNode)

    r1 = Reporter.objects.create(first_name='r1', last_name='r1', email='*****@*****.**')
    r2 = Reporter.objects.create(first_name='r2', last_name='r2', email='*****@*****.**')
    Article.objects.create(headline='a1', pub_date=datetime.now(), reporter=r1)
    Article.objects.create(headline='a2', pub_date=datetime.now(), reporter=r2)

    query = '''
    query {
        allReporters {
            edges {
                node {
                    articles {
                        edges {
                            node {
                                headline
                            }
                        }
                    }
                }
            }
        }
    }
    '''
    schema = Schema(query=Query)
    result = schema.execute(query)
    assert not result.errors
    # We should only get back a single article for each reporter
    assert len(result.data['allReporters']['edges'][0]['node']['articles']['edges']) == 1
    assert len(result.data['allReporters']['edges'][1]['node']['articles']['edges']) == 1
Example #34
0
def test_get_session():
    session = 'My SQLAlchemy session'

    class Query(ObjectType):
        x = String()

        def resolve_x(self, args, context, info):
            return get_session(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 #35
0
def test_get_session():
    session = "My SQLAlchemy session"
    schema = Schema(session=session)

    class Query(ObjectType):
        x = String()

        def resolve_x(self, args, info):
            return get_session(info)

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

    schema = Schema(query=Query, session=session)
    result = schema.execute(query)
    assert not result.errors
    assert result.data["x"] == session
def test_should_query_filter_node_limit():
    class ReporterFilter(FilterSet):
        limit = NumberFilter(method='filter_limit')

        def filter_limit(self, queryset, name, value):
            return queryset[:value]

        class Meta:
            model = Reporter
            fields = ['first_name', ]

    class ReporterType(DjangoObjectType):

        class Meta:
            model = Reporter
            interfaces = (Node, )

    class ArticleType(DjangoObjectType):

        class Meta:
            model = Article
            interfaces = (Node, )
            filter_fields = ('lang', )

    class Query(ObjectType):
        all_reporters = DjangoFilterConnectionField(
            ReporterType,
            filterset_class=ReporterFilter
        )

        def resolve_all_reporters(self, args, context, info):
            return Reporter.objects.order_by('a_choice')

    Reporter.objects.create(
        first_name='Bob',
        last_name='Doe',
        email='*****@*****.**',
        a_choice=2
    )
    r = Reporter.objects.create(
        first_name='John',
        last_name='Doe',
        email='*****@*****.**',
        a_choice=1
    )

    Article.objects.create(
        headline='Article Node 1',
        pub_date=datetime.now(),
        reporter=r,
        editor=r,
        lang='es'
    )
    Article.objects.create(
        headline='Article Node 2',
        pub_date=datetime.now(),
        reporter=r,
        editor=r,
        lang='en'
    )

    schema = Schema(query=Query)
    query = '''
        query NodeFilteringQuery {
            allReporters(limit: 1) {
                edges {
                    node {
                        id
                        firstName
                        articles(lang: "es") {
                            edges {
                                node {
                                    id
                                    lang
                                }
                            }
                        }
                    }
                }
            }
        }
    '''

    expected = {
        'allReporters': {
            'edges': [{
                'node': {
                    'id': 'UmVwb3J0ZXJUeXBlOjI=',
                    'firstName': 'John',
                    'articles': {
                        'edges': [{
                            'node': {
                                'id': 'QXJ0aWNsZVR5cGU6MQ==',
                                'lang': 'ES'
                            }
                        }]
                    }
                }
            }]
        }
    }

    result = schema.execute(query)
    assert not result.errors
    assert result.data == expected