📜  Python|跳过测试失败

📅  最后修改于: 2022-05-13 01:55:05.983000             🧑  作者: Mango

Python|跳过测试失败

问题——在单元测试中跳过或将选定的测试标记为预期的失败。

unittest 模块具有可应用于选定测试方法的装饰器,以控制它们的处理,如下面的代码所示。

代码#1:

import unittest
import os
import platform
  
class Tests(unittest.TestCase):
    def test_0(self):
        self.assertTrue(True)
        @unittest.skip('skipped test')
          
    def test_1(self):
        self.fail('should have failed !')
        @unittest.skipIf(os.name =='posix', 'Not supported on Unix')
          
    def test_2(self):
        import winreg
    @unittest.skipUnless(platform.system() == 'Darwin', 'Mac specific test')
      
    def test_3(self):
        self.assertTrue(True)
        @unittest.expectedFailure
    def test_4(self):
        self.assertEqual(2 + 2, 5)
          
if __name__ == '__main__':
    unittest.main()

输出:

bash % python3 testsample.py -v
test_0 (__main__.Tests) ... ok
test_1 (__main__.Tests) ... skipped 'skipped test'
test_2 (__main__.Tests) ... skipped 'Not supported on Unix'
test_3 (__main__.Tests) ... ok
test_4 (__main__.Tests) ... expected failure
----------------------------------------------------------------------
Ran 5 tests in 0.002s
OK (skipped = 2, expected failures = 1)

这个怎么运作 :

  • skip()装饰器可用于跳过根本不需要运行的测试。
  • skipIf()skipUnless()可能是编写仅适用于某些平台或Python版本或具有其他依赖项的测试的有用方法。

使用@expectedFailure装饰器标记已知失败的测试,但测试框架不需要报告更多信息。

代码 #2 :将装饰器用于跳过整个测试类的方法

@unittest.skipUnless(platform.system() == 'Darwin', 'Mac specific tests')
class DarwinTests(unittest.TestCase):
    ...