pytest.raises无法捕获自定义异常的问题求助
pytest.raises无法捕获自定义异常的问题求助
大家好,我遇到了一个pytest捕获自定义异常的奇怪问题,折腾半天没搞懂,想请教下各位:
我的项目结构如下:
root/ ├── pytest.ini ├── models/ │ ├── my_model.py │ └── custom_exceptions.py └── test/ └── test_one.py
各个文件的代码分别是:
my_model.py:
from custom_exceptions import MyException class MyModel: def __init__(self, a): self.a = a self.raisers() def raisers(self): raise MyException
custom_exceptions.py:
class MyException(Exception): pass
test_one.py:
import pytest from models import my_model from models import custom_exceptions class TestOne: def test(self): assert True def test_ex(self): with pytest.raises(custom_exceptions.MyException): my_model.MyModel("a")
pytest.ini:
[pytest] minversion = 7.0 pythonpath = models testpaths = test
我是在pyenv的虚拟环境中运行测试,执行python -m pytest后,第一个测试test能正常通过,但第二个测试test_ex却失败了,报错信息如下:
self = <test_one.TestOne object at 0x7fa1f2504b50> def test_ex(self): with pytest.raises(custom_exceptions.MyException): > my_model.MyModel("a") test/test_one.py:11: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ models/my_model.py:6: in __init__ self.raisers() _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <models.my_model.MyModel object at 0x7fa1f2504790> def raisers(self): > raise MyException E custom_exceptions.MyException models/my_model.py:9: MyException ========== short test summary info ============ FAILED test/test_one.py::TestOne::test_ex - custom_exceptions.MyException
但更奇怪的是,如果我手动抛出异常,测试就能成功通过:
def test_two(self): with pytest.raises(custom_exceptions.MyException): raise custom_exceptions.MyException
为了排查问题,我在测试里加了调试代码,捕获异常后打印类型:
def test_ex(self): with pytest.raises(custom_exceptions.MyException): try: my_model.MyModel("a") except Exception as e: print(type(e)) print(type(custom_exceptions.MyException)) raise e
输出结果让我更困惑了:
<class 'custom_exceptions.MyException'> <class 'type'>
为什么custom_exceptions.MyException的类型会是type啊?有没有大佬能帮我分析下问题出在哪?
备注:内容来源于stack exchange,提问作者Wolfeius
相关产品推荐
相关产品推荐

