I use Django and Graphene in my project. I wrote tests with GraphQLTestCase
. When i try to authenticate users using JWT, i usually get errors.
Here is my code:
from django.test import TestCase
import json
from graphene_django.utils.testing import GraphQLTestCase
from resume.graph.schema import schema
from .models import Post
from django.contrib.auth import get_user_model
from graphql_jwt.shortcuts import get_token
User = get_user_model()
class PostTestCase(GraphQLTestCase):
GRAPHQL_SCHEMA = schema
def test_post_list(self):
token = get_token(User.objects.get(pk=1))
headers = {"HTTP_AUTHORIZATION": f"JWT {token}"}
response = self.query(
'''
query {
post{
user
text
}
}
''',
op_name = 'post',
headers=headers,
)
content = json.loads(response.content)
self.assertResponseNoErrors(response)
Here are the errors I get after running python manage.py test.
Traceback (most recent call last): File "C:\Users\Udemezue\Desktop\resume\post\tests.py", line 25, in test_post_list token = get_token(User.objects.get(pk=9)) File "C:\Users\Udemezue\Desktop\resume\env\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Udemezue\Desktop\resume\env\lib\site-packages\django\db\models\query.py", line 415, in get raise self.model.DoesNotExist( accounts.models.User.DoesNotExist: User matching query does not exist.
Here is the errors i get.
Traceback (most recent call last): File "C:\Users\Udemezue\Desktop\resume\post\tests.py", line 62, in test_post_list self.assertResponseNoErrors(response) File "C:\Users\Udemezue\Desktop\resume\env\lib\site-packages\graphene_django\utils\testing.py", line 75, in assertResponseNoErrors self.assertEqual(resp.status_code, 200) AssertionError: 400 != 200
Ran 1 test in 0.137s
FAILED (failures=1) Destroying test database for alias 'default'...
This works for me.
from django.contrib.auth import get_user_model
from graphql_jwt.shortcuts import get_token
User = get_user_model()
import json
class PostTestCase(GraphQLTestCase):
def test_post_list(self):
user = get_user_model().objects.create(username='myuser')
token = get_token(user)
headers = {"HTTP_AUTHORIZATION": f"JWT {token}"}
response = self.query(
'''
query GetUser($username: String!) {
user(username: $username) {
id
}
}
''',
headers=headers,
)
content = json.loads(response.content)
self.assertResponseNoErrors(response)