python type_error ai_generated true

AttributeError: 'TestCase' 对象没有属性 'subTest'

AttributeError: 'TestCase' object has no attribute 'subTest'

ID: python/unittest-subtest-attribute-error

其他格式: JSON · Markdown 中文 · English
80%修复率
84%置信度
0证据数
2024-01-15首次发现

版本兼容性

版本状态引入弃用备注
3.9 active — — —
3.10 active — — —
3.11 active — — —

根因分析

subTest 在 Python 3.4 中引入;运行在更旧的解释器上,或测试类继承自自定义基类但未调用 super().__init__ 导致 TestCase 未正确初始化。

English

subTest was added in Python 3.4; running on an older interpreter, or the test class inherits from a custom base that shadows TestCase without calling super().__init__.

generic

解决方案

  1. 93% 成功率
    # ensure base class calls super:
    class Base(unittest.TestCase):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
    
    # then subTest works
    with self.subTest(i=i):
        self.assertEqual(f(i), i)
  2. 95% 成功率
    import pytest
    
    @pytest.mark.parametrize('i', range(10))
    def test_f(i):
        assert f(i) == i

无效尝试

常见但无效的做法:

  1. 50% 失败

    Stops at the first failure; loses the ability to report all subtest failures.

  2. 90% 失败

    Subtest failures are silently swallowed, so tests pass falsely.