Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/apache/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python单元测试;assertTrue()奇怪的行为_Python_Python 3.7_Python Unittest - Fatal编程技术网

Python单元测试;assertTrue()奇怪的行为

Python单元测试;assertTrue()奇怪的行为,python,python-3.7,python-unittest,Python,Python 3.7,Python Unittest,我很惊讶今天在代码审查请求中看到这样的情况: import unittest class SomeTestClass(unittest.TestCase): @classmethod def setUpClass(cls): ... cls.assertTrue(some_condition, "a message") 这激发了我对python2.7的兴趣,我知道在classmethod或staticmethod中不能调用assertXXX方法,它可能会失败。我很快

我很惊讶今天在代码审查请求中看到这样的情况:

import unittest
class SomeTestClass(unittest.TestCase):
@classmethod
def setUpClass(cls):
  ...
  cls.assertTrue(some_condition, "a message")
这激发了我对
python2.7
的兴趣,我知道在
classmethod
staticmethod
中不能调用
assertXXX
方法,它可能会失败。我很快拿出一些测试代码来检查:

import unittest
class TestClass(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
      var = 34
      cls.assertTrue(var == 34)
      cls.assertTrue(var == 33)

    def test_123(self):
      self.assertFalse(False)

if __name__ == '__main__':
   unittest.main()
希望python语言在调用
assertTrue
时失败,这是静态上下文中的一个实例方法,如果它起作用(我认为可能在
python3
中,它发生了变化),那么
cls.assertTrue(var==33)
将引发一个
AssertionError
。但令我大吃一惊的是,上述情况都没有发生,我看到:

.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
我正在使用
python3.7
。我的问题是:

  • assertTrue
    是一个实例方法时,这不应该失败吗?请注意,
    assertFalse
    和其他此类方法确实会导致故障
  • 当条件评估为
    False
    时,如果它确实起作用,则不应该
    assertTrue
    失败吗

  • 这与3.x中函数的绑定方式有关。考虑一个更简单的例子:

    class Example:
        def method(self):
            print(f'Example.method called on {self!r}')
    
    Example.method('a string')
    

    Karl Knechtel的观点很好,但是为什么
    assertFalse()
    的行为会不一样呢?我很肯定,如果你用同样的方式来称呼它的话。你的代码没有。抱歉,我没有在代码中放入
    cls.assertFalse(var==34)
    ,这与
    assertTrue
    的行为不一样。请试一试。上面我的代码示例中的
    assertFalse
    表明它在实例方法的上下文中工作。