python type_error ai_generated true

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

ID: python/pytest-subtests-plugin-missing

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2025-04-27First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.11 active — — —
3.12 active — — —

Root Cause

self.subTest() is a unittest.TestCase method. Calling it on a pytest-style test class or a plain function that doesn't inherit from unittest.TestCase raises AttributeError.

generic

中文

self.subTest() 是 unittest.TestCase 的方法。在 pytest 风格的测试类或未继承 unittest.TestCase 的普通函数上调用会抛出 AttributeError。

Workarounds

  1. 92% success
    import unittest
    import pytest
    
    class TestMath(unittest.TestCase):
        def test_add(self):
            for a, b, exp in [(1,2,3),(2,3,5)]:
                with self.subTest(a=a, b=b):
                    self.assertEqual(a+b, exp)
  2. 94% success
    @pytest.mark.parametrize('a,b,exp', [(1,2,3),(2,3,5)])
    def test_add(a, b, exp):
        assert a + b == exp

Dead Ends

Common approaches that don't work:

  1. 70% fail

    pytest-subtests adds support for TestCase.subTest in pytest-style classes only if the class inherits TestCase; a plain class still lacks the method.

  2. 80% fail

    Fragile; the semantics of subTest (reporting multiple failures per test) aren't replicated by a naive patch.