我正在尝试测试我的身份验证失败。引发了异常,但未被assertRaises
捕获。我在这里想念什么?
def test_auth(self):
from graphql_jwt.exceptions import PermissionDenied
with self.assertRaises(PermissionDenied):
response = self.client.execute(self.query)
跟踪:
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
Traceback (most recent call last):
File "/home/dan/game/venv/lib/python3.7/site-packages/promise/promise.py", line 487, in _resolve_from_executor
executor(resolve, reject)
File "/home/dan/game/venv/lib/python3.7/site-packages/promise/promise.py", line 754, in executor
return resolve(f(*args, **kwargs))
File "/home/dan/game/venv/lib/python3.7/site-packages/graphql/execution/middleware.py", line 75, in make_it_promise
return next(*args, **kwargs)
File "/home/dan/game/venv/lib/python3.7/site-packages/graphene_django/filter/fields.py", line 106, in connection_resolver
**args
File "/home/dan/game/venv/lib/python3.7/site-packages/graphene_django/fields.py", line 156, in connection_resolver
iterable = resolver(root, info, **args)
File "/home/dan/game/venv/lib/python3.7/site-packages/graphql_jwt/decorators.py", line 31, in wrapper
return func(info.context, *args, **kwargs)
File "/home/dan/game/venv/lib/python3.7/site-packages/graphql_jwt/decorators.py", line 43, in wrapper
raise exceptions.PermissionDenied()
graphql.error.located_error.GraphQLLocatedError: You do not have permission to perform this action
F.
======================================================================
FAIL: test_auth (api.tests.test_mutations.TestGame)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/dan/game/api/tests/test_mutations.py", line 57, in test_auth
response = self.client.execute(self.query)
AssertionError: PermissionDenied not raised
正在引发异常here。
答案 0 :(得分:2)
您的测试未捕获到PermissionDenied
异常,因为正在运行的代码中的某些内容将该异常包装在graphql.error.located_error.GraphQLLocatedError
的实例中。因为您要检查错误的异常类型,所以测试失败。
我对所使用的库不了解太多,并且异常类型的无形更改似乎具有可怕的错误功能(它至少应将用于更改异常类型的代码添加到异常回溯中)因此您可以对其进行调试)。但是,您可以通过捕获包装的异常并重新抛出原始异常来解决此问题:
def test_auth(self):
from graphql_jwt.exceptions import PermissionDenied
from graphql.error.located_error import GraphQLLocatedError
with self.assertRaises(PermissionDenied):
try:
response = self.client.execute(self.query)
except GraphQLLocatedError as e:
raise e.original_error
答案 1 :(得分:1)
GraphQL捕获所有异常并将错误放入响应的错误部分。 如果要测试查询(self.client.execute(... query ...))的执行情况,则应获取结果并验证其错误部分与您的期望相符。
一种更简单的方法是专门测试解析器-直接而不是通过GraphQL执行层调用resolve_entity,然后像测试其他Python函数一样对其进行测试。