python type_error ai_generated true

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

ID: python/unittest-subtest-attribute-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-01-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.9 active — — —
3.10 active — — —
3.11 active — — —

Root Cause

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

中文

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

Workarounds

  1. 93% success
    # 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% success
    import pytest
    
    @pytest.mark.parametrize('i', range(10))
    def test_f(i):
        assert f(i) == i

Dead Ends

Common approaches that don't work:

  1. 50% fail

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

  2. 90% fail

    Subtest failures are silently swallowed, so tests pass falsely.