python runtime_error ai_generated true

test_something (tests.test_x.TestX.test_something) ... ok # 但测试体包含 assertEqual(1, 2) 却从未执行

test_something (tests.test_x.TestX.test_something) ... ok # but the test body contains: assertEqual(1, 2) and never runs

ID: python/unittest-assertion-always-true-no-self

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

版本兼容性

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

根因分析

TestCase 中名为 test_* 的辅助方法缺少 `self` 参数或被定义为 staticmethod,unittest 将其当作测试但静默失败或被跳过。

English

A helper method named like a test (test_*) inside the TestCase lacks the `self` parameter or is defined as a staticmethod, so unittest treats it as a test but it fails silently or is skipped.

generic

解决方案

  1. 95% 成功率
    class TestX(unittest.TestCase):
        def _build_payload(self):
            return {'k': 1}
    
        def test_payload(self):
            self.assertEqual(self._build_payload(), {'k': 1})
  2. 90% 成功率
    def build_payload():
        return {'k': 1}
    
    class TestX(unittest.TestCase):
        def test_payload(self):
            self.assertEqual(build_payload(), {'k': 1})

无效尝试

常见但无效的做法:

  1. 40% 失败

    Renaming fixes discovery but does not explain why the assertions were silently skipped; other tests may still be misnamed.

  2. 70% 失败

    Hides the real issue; the method is still collected as a test and reported as skipped, polluting results.