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

Question:

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.

Asked By: 7hi4g0

||

Answers:

From the docs (italics mine):

unittest.TestCase.setUp()

Method called to prepare the test fixture. This is called immediately before calling the test method; any exception raised by
this method will be considered an error rather than a test failure.
The default implementation does nothing.

So if you don’t need any set up then don’t override unittest.TestCase.setUp.

However, if one of your test_* methods doesn’t need the set up and the others do, I would recommend putting that in a separate class.

Answered By: Steven Rumbalski

In setUp(), self._testMethodName contains the name of the test that will be executed. It’s likely better to put the test into a different class or something, of course, but it’s in there.

Answered By: user3757614

It’s feasible for user to skip some test methods based on its docstring, take an example as below:

import unittest

class simpleTest2(unittest.TestCase):
   def setUp(self):
      self.a = 10
      self.b = 20
      name = self.shortDescription()
      if name == "add":
         self.a = 10
         self.b = 20
         print name, self.a, self.b
      if name == "sub":
         self.a = 50
         self.b = 60
         print name, self.a, self.b
   def tearDown(self):
      print 'nend of test',self.shortDescription()

   def testadd(self):
      """add"""
      result = self.a+self.b
      self.assertTrue(result == 30)
   def testsub(self):
      """sub"""
      result = self.a-self.b
      self.assertTrue(result == -10)

if __name__ == '__main__':
   unittest.main()

If the setup() method is used for most test methods except one exception, you can return directly if that method is met based on the comparison of docstring.

Answered By: Eugene

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
Answered By: victortv