引发异常,但未被assertRaise捕获 [英] Exception raised but not caught by assertRaises

查看:113
本文介绍了引发异常,但未被assertRaise捕获的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试我的身份验证是否失败。异常被引发,但未被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

推荐答案

您的测试没有捕获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

这篇关于引发异常,但未被assertRaise捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆