【问题标题】:How to authenticate with django-grahql-jwt in a graphene-django GraphQLTestCase?如何在 graphene-django GraphQLTestCase 中使用 django-grahql-jwt 进行身份验证?
【发布时间】:2023-03-20 01:23:01
【问题描述】:

我正在尝试根据石墨烯 django 文档测试我的突变。突变适用于@login_required 装饰器,并且存在问题,因为任何登录测试方法都不起作用。我试过self.client.loginself.client.force_login。我什至做了一个 tokenAuth 突变,并在那里硬编码了一些凭据,但它也不起作用;用户仍然是匿名的。

def test_create_member_mutation(self):
    response = self.query(
        '''
        mutation createMember($firstName: String) {
            createMember(firstName: $firstName) {
                member {
                    id
                }
            }
        }
        ''',
        op_name='createMember',
        variables={'firstName': 'Foo'}
    )

    self.assertResponseNoErrors(response)

【问题讨论】:

  • 你是用django的session认证还是graphql JWT?
  • @ruohola 抱歉,没有具体说明。 graphql jwt
  • 那么你很幸运,我也遇到了同样的问题。

标签: python django graphql graphene-django django-graphql-jwt


【解决方案1】:

这就是我在测试中解决它的方法。

您可以在self.query()headers 关键字参数中传递为测试用户制作的令牌:

from django.contrib.auth import get_user_model
from graphene_django.utils import GraphQLTestCase
from graphql_jwt.shortcuts import get_token


class ExampleTests(GraphQLTestCase):

    def test_create_member_mutation(self):
        user = get_user_model().objects.get(pk=1)
        token = get_token(user)
        headers = {"HTTP_AUTHORIZATION": f"JWT {token}"}

        graphql = '''
            mutation createMember($firstName: String) {
                createMember(firstName: $firstName) {
                    member {
                        id
                    }
                }
            }
        '''

        respsone = self.query(
            graphql,
            op_name='createMember',
            variables={'firstName': 'Foo'},
            headers=headers,
        )
        self.assertResponseNoErrors(response)

【讨论】:

  • 我得到:TypeError: query() got an unexpected keyword argument 'headers',您安装了哪些版本的graphql 和graphene?我阅读了所有的源代码,发现只有**extra,没有提到标题。
  • @EmacsTheViking 参数好像还在:github.com/graphql-python/graphene-django/blob/…
  • 谢谢!我不知道为什么我之前没有检查版本。我有 2.7.1,现在已经很旧了,我加入了这个项目,它是很久以前创建的......我会升级。谢谢。
猜你喜欢
  • 2021-01-21
  • 2016-12-17
  • 2020-04-14
  • 2016-12-16
  • 2017-02-04
  • 2019-05-02
  • 2018-07-13
  • 2021-09-14
  • 2018-12-15
相关资源
最近更新 更多