python type_error ai_generated true

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

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

ID: python/pytest-subtests-plugin-missing

其他格式: JSON · Markdown 中文 · English
80%修复率
87%置信度
0证据数
2025-04-27首次发现

版本兼容性

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

根因分析

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

English

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

解决方案

  1. 92% 成功率
    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% 成功率
    @pytest.mark.parametrize('a,b,exp', [(1,2,3),(2,3,5)])
    def test_add(a, b, exp):
        assert a + b == exp

无效尝试

常见但无效的做法:

  1. 70% 失败

    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% 失败

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