Python | Skipping Test Failures

Problem – To skip or mark selected tests as an anticipated failure in the unit tests.

The unittest module has decorators that can be applied to selected test methods to control their handling as shown in the code given below.

Code #1 :

filter_none

edit
close

play_arrow

link
brightness_4
code

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()

chevron_right


Output:


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)

How it works :

  • The skip() decorator can be used to skip over a test that need not be run at all.
  • skipIf() and skipUnless() can be a useful way to write tests that only apply to certain platforms or Python versions, or which have other dependencies.

Use the @expectedFailure decorator to mark tests that are known failures, but for which the test framework need not report more information.

Code #2 : Applying decorators for skipping methods to entire testing classes

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.