Skip unittest test without decorator syntax

后端 未结 4 402
野的像风
野的像风 2021-02-02 14:05

I have a suite of tests that I have loaded using TestLoader\'s (from the unittest module) loadTestsFromModule() method, i.e.,

suite = loader.loadTestsFromModule         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-02 14:18

    This is a bit of a hack, but because you only need to raise unittest.SkipTest you can walk through your suite and modify each test to raise it for you instead of running the actual test code:

    import unittest
    from unittest import SkipTest
    
    class MyTestCase(unittest.TestCase):
        def test_this_should_skip(self):
            pass
    
        def test_this_should_get_skipped_too(self):
            pass
    
    def _skip_test(reason):
        raise SkipTest(reason)
    
    if __name__ == '__main__':
        suite = unittest.TestLoader().loadTestsFromTestCase(MyTestCase)
        for test in suite:
            skipped_test_method = lambda: _skip_test("reason")
            setattr(test, test._testMethodName, skipped_test_method)
        unittest.TextTestRunner(verbosity=2).run(suite)
    

    When I run this, this is the output I get:

    test_this_should_get_skipped_too (__main__.MyTestCase) ... skipped 'reason'
    test_this_should_skip (__main__.MyTestCase) ... skipped 'reason'
    
    ----------------------------------------------------------------------
    Ran 2 tests in 0.000s
    
    OK (skipped=2)
    

提交回复
热议问题