[英]How to authenticate with django-grahql-jwt in a graphene-django GraphQLTestCase?
I'm trying to test my mutation according to graphene django documentation.我正在尝试根据石墨烯 django 文档测试我的突变。 the mutation works with @login_required
decorator and there's a problem because any method of login to test doesn't work.突变适用于@login_required
装饰器,并且存在问题,因为任何登录测试方法都不起作用。 I tried with self.client.login
, self.client.force_login
.我试过self.client.login
, self.client.force_login
。 I've even made a tokenAuth mutation, and hardcoded some credentials there and it also doesn't work;我什至做了一个 tokenAuth 突变,并在那里硬编码了一些凭据,但它也不起作用; the user is still Anonymous.用户仍然是匿名的。
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)
This is how I've solved it in my tests.这就是我在测试中解决它的方式。
You can pass a token that has been made for the test user in the headers
keyword argument of self.query()
:您可以在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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.