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

logging.captureWarnings(True)的pytest用例互相干扰问题

pytest中logging捕获警告的测试用例互相影响问题

我在应用中设置了logging.captureWarnings(True),想要测试警告是否被正确记录,但遇到了测试用例互相影响的问题:

复现测试套件

test_warning_logs.py

import warnings
import logging


def test_a(caplog):
    logging.captureWarnings(True)
    logging.basicConfig()
    
    warnings.warn("foo")

    assert "foo" in caplog.text

def test_b(caplog):
    logging.captureWarnings(True)
    logging.basicConfig()
    
    warnings.warn("foo")

    assert "foo" in caplog.text

两个测试用例完全相同。单独执行(pytest test_warning_logs.py -k test_a或pytest test_warning_logs.py -k test_b)时均通过,但同时执行(pytest test_warning_logs.py)时,只有第一个用例通过,第二个用例断言失败:

============== test session starts ========================
platform linux -- Python 3.10.2, pytest-7.2.1, pluggy-1.0.0
rootdir: /home/me
plugins: mock-3.10.0, dependency-0.5.1
collected 2 items


test_warning_logs.py .F

==================== FAILURES =============================
_____________________ test_b ______________________________

caplog = <_pytest.logging.LogCaptureFixture object at 0x7f8041857c40>

    def test_b(caplog):
        logging.captureWarnings(True)
        logging.basicConfig()
    
        warnings.warn("foo")
    
>       assert "foo" in caplog.text
E       AssertionError: assert 'foo' in ''
E        +  where '' = <_pytest.logging.LogCaptureFixture object at 0x7f8041857c40>.text
[...] 

补充信息

我最初怀疑logging.captureWarnings和logging.basicConfig不具备幂等性,多次执行是问题根源,但移除test_b中的这些代码后,测试仍失败。

我推测这是pytest相关问题,因为不通过pytest直接执行代码时,两个警告都能被正常记录:

在test_warning_logs.py末尾添加以下代码:

if __name__ == '__main__':
    from unittest.mock import MagicMock

    test_a(MagicMock(text="foo"))
    test_b(MagicMock(text="foo"))

执行$ python test_warning_logs.py后输出:

WARNING:py.warnings:/home/me/test_warning_logs.py:9: UserWarning: foo
  warnings.warn("foo")

WARNING:py.warnings:/home/me/test_warning_logs.py:17: UserWarning: foo
  warnings.warn("foo")

内容的提问来源于stack exchange,提问作者Arne

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 05:55:14