Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to skip setUp() for a specific test in python's unittest?

When I create a unittest.TestCase, I can define a setUp() function that will run before every test in that test case. Is it possible to skip the setUp() for a single specific test?

It's possible that wanting to skip setUp() for a given test is not a good practice. I'm fairly new to unit testing and any suggestion regarding the subject is welcome.

like image 340
7hi4g0 Avatar asked Jun 07 '13 19:06

7hi4g0


People also ask

Does setUp run before every test Python?

The only difference is that the setUp method is executed before the test method is executed, while the tearDown method is executed after the execution of the test method.


1 Answers

You can use Django's @tag decorator as a criteria to be used in the setUp method to skip if necessary.

# import tag decorator from django.test.utils import tag  # The test which you want to skip setUp @tag('skip_setup') def test_mytest(self):     assert True  def setUp(self):     method = getattr(self,self._testMethodName)     tags = getattr(method,'tags', {})     if 'skip_setup' in tags:         return #setUp skipped     #do_stuff if not skipped 

Besides skipping you can also use tags to do different setups.

P.S. If you are not using Django, the source code for that decorator is really simple:

def tag(*tags):     """     Decorator to add tags to a test class or method.     """     def decorator(obj):         setattr(obj, 'tags', set(tags))         return obj     return decorator 
like image 150
victortv Avatar answered Sep 20 '22 15:09

victortv