Pytest和自定义异常:TypeError:异常必须派生自BaseException,而不是类“module”

2024-09-30 06:15:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我似乎无法让pytest处理我的自定义异常

以下是异常代码:

class FileIsEmptyError(Exception):
    """Raised when the input file is empty"""

    def __init__(self, *args):
        if args:
            self.message = args[0]
        else:
            self.message = None

    def __str__(self):
        if self.message:
            return f"FileIsEmptyError, {self.message}"
        else:
            return f"FileIsEmptyError has been raised."

doc之后,下面是(简化的)测试函数:

from pyupurs.exceptions import FileIsEmptyError

...

with pytest.raises(FileIsEmptyError):
    raise FileIsEmptyError

下面是单元测试的回报:

with pytest.raises(FileIsEmptyError): E TypeError: exceptions must be derived from BaseException, not class 'module'

以下是项目结构:

pyupurs
|---pyupurs
   |---exceptions
      |---__init__.py
      |---FileIsEmptyError.py
   |--- stateless_file_ops
|--- tests
   |--- pyupurs
      |--- stateless_file_ops
         |--- __init__.py
         |--- test_auditing_ops.py
      |--- __init__.py
   |--- samples
      |--- ... 
|--- ...


Tags: pyselfmessageifinitpytestdefargs
1条回答
网友
1楼 · 发布于 2024-09-30 06:15:36

改变这个

from pyupurs.exceptions import FileIsEmptyError

对此

from pyupurs.exceptions.FileIsEmptyError import FileIsEmptyError

相关问题 更多 >

    热门问题