如何有条件地跳过python中的测试

arg*_*per 6 python unit-testing nose pytest nose2

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

@skip_unless(condition)
def test_method(self):
    ...
Run Code Online (Sandbox Code Playgroud)

在这里,我希望测试方法如果condition评估为true,则报告为跳过。我用鼻子做了一些努力就可以做到这一点,但是我想看看是否可以在鼻子2中使用它。

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

Shu*_*ary 6

通用解决方案:

您可以使用unittest将适用于鼻子测试,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
Run Code Online (Sandbox Code Playgroud)

pytest

使用pytest框架:

@pytest.mark.skipif(condition, reason)
def test_that_runs_when_condition_false():
    assert 1 == 1
Run Code Online (Sandbox Code Playgroud)


Ole*_*siy 4

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