【问题标题】:Pytest & custom exception : TypeError: exceptions must be derived from BaseException, not class 'module'Pytest 和自定义异常:TypeError:异常必须从 BaseException 派生,而不是类“模块”
【发布时间】:2020-05-10 19:56:09
【问题描述】:

我似乎无法让 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: 异常 必须从 BaseException 派生,而不是类“模块”

这是项目结构:

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

【问题讨论】:

  • 我认为您只打算从Exception 继承,而不是从另一个“特定”异常。你不是supering IOError 或使用它的任何方法——你想达到什么目的?
  • 我试过ExceptionBaseExceptionOSErrorIOError 只是我在写这篇文章时犯的一个错误。现在更正它。
  • 你能显示FileIsEmptyError 的导入语句吗?
  • 我已经在帖子中包含了导入和项目结构

标签: python python-3.x exception pytest


【解决方案1】:

改变这个

from pyupurs.exceptions import FileIsEmptyError

到这里

from pyupurs.exceptions.FileIsEmptyError import FileIsEmptyError

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 2021-10-31
    • 2016-05-03
    • 1970-01-01
    • 2018-11-21
    相关资源
    最近更新 更多