Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.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 unittest编写多个AssertleSequal方法_Python_Python 3.x_Python Unittest - Fatal编程技术网

如何为python unittest编写多个AssertleSequal方法

如何为python unittest编写多个AssertleSequal方法,python,python-3.x,python-unittest,Python,Python 3.x,Python Unittest,我想像这样检查多个断言,在第一行代码抛出断言错误之后。有人能帮我理解这个断言吗。我知道这可以通过try-except实现,但是有没有其他的单元测试方式呢。还请告诉我,这个功能与多个AssertTrue、AssertFalse方法不同的原因是什么 import unittest class Test1(unittest.TestCase): def test_between(self): print ("before") self.assertLessEq

我想像这样检查多个断言,在第一行代码抛出断言错误之后。有人能帮我理解这个断言吗。我知道这可以通过try-except实现,但是有没有其他的单元测试方式呢。还请告诉我,这个功能与多个AssertTrue、AssertFalse方法不同的原因是什么

import unittest

class Test1(unittest.TestCase):
    def test_between(self):
        print ("before")
        self.assertLessEqual(999, 998, "Not less")  # After this next line is not executing because this is throwing an "AssertionError: 999 not less than or equal to 998 : Not less"
                                                    # How can I catch this error, I know one way is through try,Except... but is there any proper solution available?
        print ("after")
        self.assertLessEqual(999, 500, "Not less")  # 2nd Assertion

if __name__ == '__main__':
    unittest.main()
感谢您的任何帮助


关于您可以尝试的一种方法是
assertRaises
并从
with
块中调用
assertLessEqual
方法:

import unittest


class Test1(unittest.TestCase):
    def test_between(self):
        with self.assertRaises(AssertionError) as e:
            self.assertLessEqual(999, 998, "Not less")

        with self.assertRaises(AssertionError) as e:
            self.assertLessEqual(999, 500, "Not less")


if __name__ == '__main__':
    unittest.main()
您应该发现
assertTrue
assertFalse
的行为与
assertLessEqual
的行为相同,其描述如下:


就像self.assertTrue(一个self.assertLessEqual(999,1000,“不少于”)一样,为此,它会打印一条消息“AssertionError:AssertionError Not raised”还有很多其他的消息。我认为它应该只在值不小于要求的情况下打印,而对于其他情况,它不应该打印日志。我必须循环超过100个属性。如果它为每个属性打印日志消息。很难找出需要什么。所以它应该只为那些测试用例失败的对象打印。可以吗请在你的问题中明确你想做什么。就目前情况而言,这回答了你最初提出的问题。哦,伟大的人。“次级测试”这就是我想要的。谢谢你宝贵的时间。
import unittest

class Test1(unittest.TestCase):
    def test_between(self):
        for i in range(10):
            with self.subTest(i=i):
                self.assertLessEqual(i, 5)

if __name__ == '__main__':
    unittest.main()
FAIL: test_between (__main__.Test1) (i=9)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "scratchpad.py", line 7, in test_between
    self.assertLessEqual(i, 5)
AssertionError: 9 not less than or equal to 5