CodeQL 文档

不精确断言

ID: py/imprecise-assert
Kind: problem
Security severity: 
Severity: recommendation
Precision: very-high
Tags:
   - maintainability
   - testability
Query suites:
   - python-security-and-quality.qls

点击查看 CodeQL 仓库中的查询

unittest.TestCase 提供了一系列断言方法。除了通用形式 assertTrue()assertFalse() 之外,还提供了更具体的形式,例如 assertGreaterEquals()assertNotIn()。通过使用更具体的形式,可以在测试失败时获得更精确和信息丰富的错误消息。这可以加快调试过程。

建议

将所有不提供自定义错误消息的 assertTrue()assertFalse() 调用替换为更具体的变体。或者,使用 assertTrue(condition, message) 形式提供定制的错误消息。

示例

在这个例子中,使用了 assertTrue()assertFalse()

from unittest import TestCase

class MyTest(TestCase):
    
    
    def testInts(self):
        self.assertTrue(1 == 1)
        self.assertFalse(1 > 2)
        self.assertTrue(1 in []) #This will fail

self.assertTrue(1 in []) 失败时,这将难以确定出了什么问题。错误消息“AssertionError: False is not true” 并没有什么帮助。

通过将断言更改为更具体的形式,可以在以下示例中生成更实用的错误消息。

from unittest import TestCase

class MyTest(TestCase):
    
    
    def testInts(self):
        self.assertEqual(1, 1)
        self.assertLessEqual(1, 2)
        self.assertIn(1, []) #This will fail

在这种情况下,错误消息“AssertionError: 1 not found in []” 更有信息量。

参考

  • ©GitHub, Inc.
  • 条款
  • 隐私