Skip unittest test without decorator syntax

后端 未结 4 503
野的像风
野的像风 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条回答
  •  萌比男神i
    2021-02-02 14:09

    Using unittest.TestCase.skipTest:

    import unittest
    
    class TestFoo(unittest.TestCase):
        def setUp(self): print('setup')
        def tearDown(self): print('teardown')
        def test_spam(self): pass
        def test_egg(self): pass
        def test_ham(self): pass
    
    if __name__ == '__main__':
        import sys
        loader = unittest.loader.defaultTestLoader
        runner = unittest.TextTestRunner(verbosity=2)
        suite = loader.loadTestsFromModule(sys.modules['__main__'])
        for ts in suite:
            for t in ts:
                if t.id().endswith('am'): # To skip `test_spam` and `test_ham`
                    setattr(t, 'setUp', lambda: t.skipTest('criteria'))
        runner.run(suite)
    

    prints

    test_egg (__main__.TestFoo) ... setup
    teardown
    ok
    test_ham (__main__.TestFoo) ... skipped 'criteria'
    test_spam (__main__.TestFoo) ... skipped 'criteria'
    
    ----------------------------------------------------------------------
    Ran 3 tests in 0.001s
    
    OK (skipped=2)
    
    
    ----------------------------------------------------------------------
    Ran 3 tests in 0.002s
    
    OK (skipped=2)
    

    UPDATE

    Updated the code to patch setUp instead of test method. Otherwise, setUp/tearDown methods will be executed for test to be skipped.

    NOTE

    unittest.TestCase.skipTest (Test skipping) was introduced in Python 2.7, 3.1. So this method only work in Python 2.7+, 3.1+.

提交回复
热议问题