为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕仙森 2022-11-01 15:57:19
伙计们,我有一个单元测试,我不想在找到一个异常时抛出异常,但要等到最后并在最后输出提高它。:from unittest import TestCaseclass 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 3Number 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 3Index 3, Expected 4, Get 5----------------------------------------------------AssertionError: Test Failed在这种情况下如何隐藏回溯?另一篇文章建议通过 捕获异常unittest_exception = sys.exc_info(),但在这里我不想立即抛出异常而是等待所有测试用例完成。有什么建议吗?
查看完整描述

1 回答

?
ibeautiful

TA贡献1993条经验 获得超5个赞

试试这个方法


from unittest import TestCase

import unittest



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]

        for i in range(len(a)):

            with self.subTest(i=i):

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



if __name__ == '__main__':

    unittest.main()


查看完整回答
反对 回复 2022-11-01
  • 1 回答
  • 0 关注
  • 82 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信