【问题标题】:How to test if exception was caught while running a django test如何在运行 django 测试时测试是否捕获到异常
【发布时间】:2020-11-10 22:30:56
【问题描述】:
假设这是我的代码:
def fun():
try:
raise Exception("An exception")
except Exception as e:
logger.debug(f'{e}')
现在我如何编写一个测试用例来检查该特定异常是否被捕获?
我可以通过阅读sys.stderr 进行测试,但我使用的是logger.debug。
我正在使用 django TestCase
【问题讨论】:
标签:
django
exception
python-3.7
django-tests
【解决方案1】:
您可以使用assertLogs,但我建议在您的日志中添加一个“前缀”,这样您就可以测试是否记录了正确的消息。
例子:
logger = logging.getLogger('foo')
def fun():
try:
raise Exception("An exception")
except Exception as e:
logger.debug(f'[error-x]: {e}')
你的测试:
with self.assertLogs('foo', level=logging.DEBUG) as cm:
call_your_method()
self.assertEqual(cm.output, ["DEBUG:foo:[error-x]: An exception"])
如果您的异常消息中有更多日志消息,您可以这样做:
self.assertIn("DEBUG:foo:[error-x]: An exception", cm.output)
您可以查看full example here