Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally skip a test in python

I would like to skip some test functions when a condition is met, for example:

@skip_unless(condition)
def test_method(self):
    ...

Here I expect the test method to be reported as skipped if condition evaluated to true. I was able to do this with some effort with nose, but I would like to see if it is possible in nose2.

Related question describes a method for skipping all tests in nose2.

like image 643
argentpepper Avatar asked Apr 02 '16 19:04

argentpepper


People also ask

How do you skip a test case in python?

It is possible to skip individual test method or TestCase class, conditionally as well as unconditionally. The framework allows a certain test to be marked as an 'expected failure'. This test will 'fail' but will not be counted as failed in TestResult. Since skip() is a class method, it is prefixed by @ token.

How do you stop a test in Python?

Once you are in a TestCase , the stop() method for the TestResult is not used when iterating through the tests. 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.


1 Answers

Generic Solution:

You can use unittest skip conditions which will work with nosetests, nose2 and pytest. There are two options:

class TestTheTest(unittest.TestCase):
    @unittest.skipIf(condition, reason)
    def test_that_runs_when_condition_false(self):
        assert 1 == 1

    @unittest.skipUnless(condition, reason)
    def test_that_runs_when_condition_true(self):
        assert 1 == 1

Pytest

Using pytest framework:

@pytest.mark.skipif(condition, reason)
def test_that_runs_when_condition_false():
    assert 1 == 1
like image 171
Shubham Chaudhary Avatar answered Oct 05 '22 04:10

Shubham Chaudhary