微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在Django / Graphene测试中模拟info.context schema.py tests.py

如何解决如何在Django / Graphene测试中模拟info.context schema.py tests.py

问题

我正在尝试测试graphql查询。该查询要求与请求关联的用户info.context.user)是超级用户.is_superuser)。否则,它将引发异常。我正在尝试测试查询是否正常运行,但是不确定如何确保info.context.user.is_superuser在测试中解析为true。请帮忙!

schema.py

class Query(graphene.ObjectType):
    gardens = graphene.List(GardenType)
    
    def resolve_gardens(self,info):
        user = info.context.user
        if not (user.is_superuser or user.is_staff):
            raise Exception("You must be staff or a superuser to view all gardens")
        return Garden.objects.all()

tests.py

from graphene_django.utils.testing import GraphQLTestCase,graphql_query
from users.models import CustomUser

class TestGraphQLQueries(GraphQLTestCase):
    """
    Test that GraphQL queries related to gardens work and throw errors appropriately
    """

    def test_gardens_query(self):
        response = self.query(
            """
            query {
                gardens {
                    id
                    name
                    owner {
                        id
                        email
                    }
                }
            }
            """
        )

        self.assertResponseNoErrors(response)

引发错误


gardens/tests.py:93: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
../env/lib/python3.6/site-packages/graphene_django/utils/testing.py:114: in assertResponseNoErrors
    self.assertnotin("errors",list(content.keys()))
E   AssertionError: 'errors' unexpectedly found in ['errors','data']
-------------------------- Captured log call ---------------------------
ERROR    graphql.execution.utils:utils.py:155 Traceback (most recent call last):
  File "/home/dthompson/Code/personal/gardenbuilder-backend/env/lib/python3.6/site-packages/promise/promise.py",line 489,in _resolve_from_executor
    executor(resolve,reject)
  File "/home/dthompson/Code/personal/gardenbuilder-backend/env/lib/python3.6/site-packages/promise/promise.py",line 756,in executor
    return resolve(f(*args,**kwargs))
  File "/home/dthompson/Code/personal/gardenbuilder-backend/env/lib/python3.6/site-packages/graphql/execution/middleware.py",line 75,in make_it_promise
    return next(*args,**kwargs)
  File "/home/dthompson/Code/personal/gardenbuilder-backend/src/gardens/schema.py",line 43,in resolve_gardens
    raise Exception("You must be a superuser to view all gardens")
graphql.error.located_error.GraphQLLocatedError: You must be a superuser to view all gardens
======================= short test summary info ========================
Failed gardens/tests.py::TestGraphQLQueries::test_gardens_query - Ass...

解决方法

您不能将上下文值直接传递到self.query方法中。

您需要做的是创建一个测试客户端,然后提供要用于测试的测试上下文值。


from graphene.test import Client
from snapshottest import TestCase

from users.models import CustomUser
from .schema import schema

class SuperUser:
    is_superuser = True

class TestContext:
    user = SuperUser()

class TestGraphQLQueries(TestCase):
    """
    Test that GraphQL queries related to gardens work and throw errors appropriately
    """

    context_value = TestContext()

    def test_gardens_query(self):
        client = Client(schema,context_value=self.context_value)
        query = (
            """
            query {
                gardens {
                    id
                    name
                    owner {
                        id
                        email
                    }
                }
            }
            """
        )
        
        self.assertMatchSnapshot(client.execute(query))
,

您可以使用RequestFactory来设置石墨烯请求的用户,方法与为Django设置石墨烯请求的用户相同。根据我在Testing Graphene-Django中的回答,模式是

from django.test import RequestFactory,TestCase
from graphene.test import Client


user = ... (fetch your test superuser)
api_query = """
        query {
            gardens {
                id
                name
                owner {
                    id
                    email
                }
            }
        }
        """
request_factory = RequestFactory()
context_value = request_factory.get('/api/')  # or use reverse() on your API endpoint
context_value.user = user
client = Client(schema)
executed = client.execute(api_query,context_value=context_value)
output_data = executed.get('data')

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。