Как проверить исключение GraphQLError в graphene_django или graphql_jwt?

Я реализую типы пользователей и аутентификацию в django, используя graphene_django и graphql_jwt. Вот два моих файла: код и соответствующие тесты, расположенные в папке с именем 'users', которая является папкой уровня приложения (но не приложением django).

schema.py

import graphene
from graphene_django import DjangoObjectType
from django.contrib.auth import get_user_model

class UserType(DjangoObjectType):
    class Meta:
        model = get_user_model()

class Query(graphene.ObjectType):
    user = graphene.Field(UserType, id=graphene.Int(required=True))
    me = graphene.Field(UserType)

    def resolve_user(self, info, id):
        user = get_user_model().objects.get(id=id)
        return user

    def resolve_me(self, info):
        current_user = info.context.user
        if current_user.is_anonymous:
            raise GraphQLError("Not logged in !")
        return current_user

tests.py

from django.contrib.auth import get_user_model
from graphql import GraphQLError
from graphql.error.located_error import GraphQLLocatedError
from graphql_jwt.testcases import JSONWebTokenTestCase

class TestUserAuthentication(JSONWebTokenTestCase):

    def setUp(self):
        self.user = get_user_model().objects.create(
            username='Moctar', password='moctar')

    # @unittest.skip("Cannot handle raised GraphQLError")
    def test_not_autenticated_me(self):
        query = '''
        {
            me{
                id
                username
                password
            }
        }
        '''
        with self.assertRaises(GraphQLError, msg='Not logged in !'):
            self.client.execute(query)

    def test_autenticated_me(self):
        self.client.authenticate(self.user)
        query = '''
        {
            me{
                id 
                username
                password
            }
        }
        '''
        self.client.execute(query)

Затем, когда я запускаю свои тесты python manage.py test users он говорит это:

Creating test database for alias 'default'...
System check identified no issues (0 silenced).
..F.
======================================================================
FAIL: test_not_autenticated_me (tests.TestUserAuthentication)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/my_username/my_projects/server/arjangen/app/users/tests.py", line 97, in test_not_autenticated_me
    self.client.execute(query)
AssertionError: GraphQLError not raised : Not logged in !

----------------------------------------------------------------------
Ran 4 tests in 0.531s

FAILED (failures=1)
Destroying test database for alias 'default'...

Я искал такой поток stackru [Исключение возникло, но не было обнаружено assertRaises][1]

[1]: исключение возникло, но не было обнаружено assertRaises, но это все еще не может решить мою проблему. Итак, как действительно можно протестировать GraphQLError?

1 ответ

Попробуйте удалить эту строку на test_not_autenticated_me():

self.client.authenticate(self.user)

Потому что что authenticate()делает, это войти в систему и получить токен JWT. Если вы не войдете в систему, пользователь по умолчанию будет объектом AnonymousUser.

Другие вопросы по тегам