如何在Python中有条件地跳过测试

问题描述 投票:0回答:3

我想在满足条件时跳过一些测试功能,例如:

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

在这里,如果

condition
评估为 true,我希望测试方法被报告为已跳过。我用nose做了一些努力就可以做到这一点,但我想看看nose2是否可以做到这一点。

相关问题描述了一种跳过nose2中所有测试的方法。

python unit-testing pytest nose nose2
3个回答
17
投票

通用解决方案:

您可以使用

unittest
跳过条件,该条件适用于nosetests、nose2和pytest。有两种选择:

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

这也可以用于跳过整个测试用例:

@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

使用

pytest
框架:

@pytest.mark.skipif(condition, reason)
def test_that_runs_when_condition_false():
    assert 1 == 1

4
投票

内置的 unittest.skipUnless() 方法,它应该与鼻子一起使用:


1
投票

用鼻子:

#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)
© www.soinside.com 2019 - 2024. All rights reserved.