Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I decorate a Python unittest method to skip if a property I've previously evaluated isn't True?

I'm writing a TestCase in Python using unittest, that looks something like this:

class MyTestCase(unittest.TestCase):
  def setUp(self):
    # ... check if I'm online - might result in True or False
    self.isOnline = True

  @unittest.skipIf(not self.isOnline, "Not online")
  def test_xyz(self):
    # do a test that relies on being online

However, this doesn't seem to work, I assume because @skipIf cannot use self outside the body of the function declaration. I know I can check the value of self.isOnline inside the test_xyz function and use skipTest instead, but this is less elegant. Are there any other options?

like image 470
Andrew Ferrier Avatar asked Dec 17 '14 19:12

Andrew Ferrier


People also ask

Which item in Python will stop unit test abruptly?

Somewhat related to your question, if you are using python 2.7, you can use the -f/--failfast flag when calling your test with python -m unittest . This will stop the test at the first failure.

How do you pass a command line argument in Unittest Python?

So the way I use to handle the command line arguments can be summarized as: Refactor your program to have the arguments parsing as a function. Refactor your program to handle the arguments parsing differently when doing unit testing. In the unit tests, set the arguments and pass them directly to the functions under ...


1 Answers

You could write your own decorator to which you pass the name of the flag:

def skipIfTrue(flag):
    def deco(f):
        def wrapper(self, *args, **kwargs):
            if getattr(self, flag):
                self.skipTest()
            else:
                f(self, *args, **kwargs)
        return wrapper
    return deco

Then in your class you would define the test method like this:

@skipIfTrue('isOnline')
def test_thing(self):
    print("A test")

Whether this is better than just checking in the method depends on the situation. If you are doing this with many methods, it could be better than writing the check in every one. On the other hand, if you're doing that, you might want to group them together and do one check to skip the entire suite.

like image 75
BrenBarn Avatar answered Sep 19 '22 19:09

BrenBarn