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?
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.
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 ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With