猿问

Python如何在单元测试中隐藏回溯

伙计们,我有一个单元测试,我不想在找到一个异常时抛出异常,但要等到最后并在最后输出提高它。:


from unittest import TestCase

class TestA(TestCase):

    def setUp(self):

        pass


    def tearDown(self):

        pass


    def test_lst(self):

        a = [1, 2, 3, 4, 5]

        b = [1, 3, 3, 5, 5]

        total_errs_count = 0

        total_errs_msg = []

        for i in range(5):

            try:

                self.assertEqual(a[i], b[i])

            except AssertionError:

                total_errs_count += 1

                total_errs_msg.append(f'Index {i}, Expected {a[i]}, Get {b[i]}')

        if total_errs_count > 0:

            for m in total_errs_msg:

                print(m)

            raise AssertionError("Test Failed")


test = TestA()

test.test_lst()

我有:


IOndex 1, Expected 2, Get 3

Number 3, Expected 4, Get 5

----------------------------------------------------

AssertionError     Traceback (most recent call last)

<ipython-input-5-b70dc996c844> in <module>

     27 

     28 test = TestA()

---> 29 test.test_lst()


<ipython-input-5-b70dc996c844> in test_lst(self)

     24             for m in total_errs_msg:

     25                 print(m)

---> 26             raise AssertionError("Test Failed")

     27 

     28 test = TestA()


AssertionError: Test Failed

但是,所需的输出是隐藏回溯:


Index 1, Expected 2, Get 3

Index 3, Expected 4, Get 5

----------------------------------------------------

AssertionError: Test Failed

在这种情况下如何隐藏回溯?另一篇文章建议通过 捕获异常unittest_exception = sys.exc_info(),但在这里我不想立即抛出异常而是等待所有测试用例完成。


有什么建议吗?


慕仙森
浏览 99回答 1
1回答

ibeautiful

试试这个方法from unittest import TestCaseimport unittestclass TestA(TestCase):&nbsp; &nbsp; def setUp(self):&nbsp; &nbsp; &nbsp; &nbsp; pass&nbsp; &nbsp; def tearDown(self):&nbsp; &nbsp; &nbsp; &nbsp; pass&nbsp; &nbsp; def test_lst(self):&nbsp; &nbsp; &nbsp; &nbsp; a = [1, 2, 3, 4, 5]&nbsp; &nbsp; &nbsp; &nbsp; b = [1, 3, 3, 5, 5]&nbsp; &nbsp; &nbsp; &nbsp; for i in range(len(a)):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; with self.subTest(i=i):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.assertEqual(a[i], b[i])if __name__ == '__main__':&nbsp; &nbsp; unittest.main()
随时随地看视频慕课网APP

相关分类

Python
我要回答