python type_error ai_generated true

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

ID: python/pytest-subtest-in-pytest

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2025-02-03First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.x active — — —
8.x active — — —

Root Cause

A unittest.TestCase test using self.subTest was collected by pytest but the class doesn't inherit from unittest.TestCase, or the wrong base class was imported (e.g., pytest.TestCase doesn't exist).

generic

中文

使用 self.subTest 的 unittest.TestCase 测试被 pytest 收集,但该类没有继承自 unittest.TestCase,或导入了错误的基类(例如 pytest.TestCase 不存在)。

Workarounds

  1. 95% success
    import unittest
    
    class TestMath(unittest.TestCase):
        def test_add(self):
            for a, b, expected in [(1,1,2),(2,2,4)]:
                with self.subTest(a=a, b=b):
                    self.assertEqual(a+b, expected)
  2. 88% success
    pip install pytest-subtests
    # then use pytest.mark.parametrize instead of subTest

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Plugin helps pytest-side subtest support, but missing TestCase inheritance is the real issue.

  2. 75% fail

    Loses per-case reporting and stops at first failure.

  3. 90% fail

    Masks the class hierarchy bug.