You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.21 11:23:00