我已经在其中创建了我的自定义异常errors.py
mapper = {
'E101':
'There is no data at all for these constraints',
'E102':
'There is no data for these constraints in this market, try changing market',
'E103':
'There is no data for these constraints during these dates, try changing dates',
}
class DataException(Exception):
def __init__(self, code):
super().__init__()
self.msg = mapper[code]
def __str__(self):
return self.msg
代码中其他地方的另一个函数会引发不同的实例,说明数据帧DataException
中是否没有足够的pandas
数据。我想用unittest
它来确保它返回适当的异常及其相应的消息。
使用一个简单的例子,为什么这不起作用:
from .. import DataException
def foobar():
raise DataException('E101')
import unittest
with unittest.TestCase.assertRaises(DataException):
foobar()
如此处所建议:Python assertRaises on user-defined exceptions
我收到此错误:
TypeError: assertRaises() missing 1 required positional argument: 'expected_exception'
或者:
def foobar():
raise DataException('E101')
import unittest
unittest.TestCase.assertRaises(DataException, foobar)
结果是:
TypeError: assertRaises() arg 1 must be an exception type or tuple of exception types
为什么它不被识别DataException
为Exception
?为什么链接的stackoverflow问题答案在不提供第二个参数的情况下工作assertRaises
?