【问题标题】:How to conditionally skip a test in python如何有条件地跳过python中的测试
【发布时间】:2016-04-02 19:10:52
【问题描述】:

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

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

在这里,如果condition 评估为真,我希望测试方法被报告为已跳过。我可以通过鼻子努力做到这一点,但我想看看在nose2中是否有可能。

Related question 描述了一种跳过nose2 中所有测试的方法。

【问题讨论】:

    标签: python unit-testing pytest nose nose2


    【解决方案1】:

    通用解决方案:

    您可以使用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
    

    Pytest

    使用pytest 框架:

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

    【讨论】:

      【解决方案2】:

      内置的unittest.skipUnless() 方法,它应该适用于鼻子:

      【讨论】:

        【解决方案3】:

        用鼻子:

        #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)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-07-14
          • 1970-01-01
          • 1970-01-01
          • 2014-12-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多