python-3.x pytest.raises()不捕获自定义异常

a14dhokn  于 2023-10-21  发布在  Python
关注(0)|答案(1)|浏览(129)

当类引发pytest.raises(CustomException)时,它似乎失败了:
我有一个这样的项目文件夹:

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

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")

custom_exceptions.py:

class MyException(Exception):
    pass

pytest.ini:

[pytest]
minversion = 7.0
pythonpath = models
testpaths = test

这是在一个pyenv venv。当我运行python -m pytest时,第一个测试成功,但第二个测试失败:

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'>

为什么类型是“类型”?

anhgbhbe

anhgbhbe1#

感谢这些评论,我能够通过改变项目结构来解决这个问题:

root:
    pytest.ini
    models:
        __init__.py
        my_model.py
    custom_exceptions:
         __init__.py
         custom_exceptions.py
    test:
        __init__.py
        test_one.py

并像这样导入海关例外:models/my_models.pytest/test_one.py上的from custom_exceptions.custom_exceptions import MyException
正如上面的注解所提到的,两个import语句的名称不同。将异常文件移动到它自己的包中解决了这个问题。

相关问题