14

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.

3 Answers 3

20

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

This can also be used to skip an entire TestCase:

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

    def test_that_also_runs_when_condition_false(self):
        assert 1 == 1

Pytest

Using pytest framework:

@pytest.mark.skipif(condition, reason)
def test_that_runs_when_condition_false():
    assert 1 == 1
Sign up to request clarification or add additional context in comments.

Comments

5

The built in unittest.skipUnless() method and it should work with nose:

1 Comment

Up-to-date link to unittest the Skipping tests and expected failures section.
1

Using nose:

#1.py
from nose import SkipTest

class worker:
    def __init__(self):
        self.skip_condition = False

class TestBench:
    @classmethod
    def setUpClass(cls):
        cls.core = worker()
    def setup(self):
        print "setup", self.core.skip_condition
    def test_1(self):
        self.core.skip_condition = True
        assert True
    def test_2(self):
        if self.core.skip_condition:
            raise SkipTest("Skipping this test")

nosetests -v --nocapture 1.py

1.TestBench.test_1 ... setup False
ok
1.TestBench.test_2 ... setup True
SKIP: Skipping this test

----------------------------------------------------------------------
XML: /home/aladin/audio_subsystem_tests/nosetests.xml
----------------------------------------------------------------------
Ran 2 tests in 0.001s

OK (SKIP=1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.