Search code examples
pythonpython-unittest

How to skip some test cases in test discovery?


In python 2.7, I use unittest module and write tests, while some of them are skipped with @unittest.skip. My codes looks like:

import unittest

class MyTest(unittest.TestCase):
    def test_1(self):
        ...

    @unittest.skip
    def test_2(self):
        ...

I have lots of such test files in a folder, and I use test discovery to run all these test files:

/%python_path/python -m unittest discover -s /%my_ut_folder% -p "*_unit_test.py"

This way, all *_unit_test.py files in the folder will be ran. In above codes, both test_1 and test_2 will be ran. What I want is, all test cases with @unittest.skip, e.g. test_2 in my above codes, should be skipped. How do I achieve this?

Any help or suggestion will be greatly appreciated!


Solution

  • Try adding a string argument to the @unittest.skip decorator, such as in the following:

    import unittest
    
    class TestThings(unittest.TestCase):
        def test_1(self):
            self.assertEqual(1,1)
    
        @unittest.skip('skipping...')
        def test_2(self):
            self.assertEqual(2,4)
    

    Running without the string argument in python 2.7 gives me the following:

    .E
    ======================================================================
    ERROR: test_2 (test_test.TestThings)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "/usr/lib64/python2.7/functools.py", line 33, in update_wrapper
        setattr(wrapper, attr, getattr(wrapped, attr))
    AttributeError: 'TestThings' object has no attribute '__name__'
    
    ----------------------------------------------------------------------
    Ran 2 tests in 0.001s
    

    whereas running with text in python 2.7 gives me:

    .s
    ----------------------------------------------------------------------
    Ran 2 tests in 0.000s
    
    OK (skipped=1)
    

    See https://docs.python.org/3/library/unittest.html or https://www.tutorialspoint.com/unittest_framework/unittest_framework_skip_test.htm for more details