【发布时间】: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继承,而不是从另一个“特定”异常。你不是superingIOError或使用它的任何方法——你想达到什么目的? -
我试过
Exception、BaseException和OSError。IOError只是我在写这篇文章时犯的一个错误。现在更正它。 -
你能显示
FileIsEmptyError的导入语句吗? -
我已经在帖子中包含了导入和项目结构
标签: python python-3.x exception pytest